diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..a838c97 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,6 @@ +FROM tomcat:latest + +COPY ./tomcat /usr/local/tomcat/webapps +COPY ./target /usr/local/tomcat/webapps + +EXPOSE 8080 diff --git a/Dockerfile.db b/Dockerfile.db new file mode 100644 index 0000000..b7c34c1 --- /dev/null +++ b/Dockerfile.db @@ -0,0 +1,14 @@ +FROM mysql:latest + +ENV MYSQL_ROOT_PASSWORD: admin \ + MYSQL_DATABASE: giit \ + MYSQL_USER: example_db_user \ + MYSQL_PASSWORD: example_db_pass \ + +VOLUME ["/docker-entrypoint-initdb.d"] + +COPY ./sql /docker-entrypoint-initdb.d + +EXPOSE 3306 + +CMD ["/usr/bin/mysqld_safe"] diff --git a/Dockerfile.ng b/Dockerfile.ng new file mode 100644 index 0000000..836a82d --- /dev/null +++ b/Dockerfile.ng @@ -0,0 +1,6 @@ +FROM nginx:1.13 + +COPY ./nginx /etc/nginx/conf.d + +EXPOSE 80 +CMD ["nginx"] diff --git a/Jenkinsfile b/Jenkinsfile new file mode 100644 index 0000000..fae312a --- /dev/null +++ b/Jenkinsfile @@ -0,0 +1,75 @@ + +def CONTAINER_NAME="javaee-tutorial" +def CONTAINER_TAG="latest" +def DOCKER_HUB_USER="yuvarajmindtree" +def HTTP_PORT="8090" + +node { + + stage('Initialize'){ + def dockerHome = tool 'myDocker' + def mavenHome = tool 'myMaven' + env.PATH = "${dockerHome}/bin:${mavenHome}/bin:${env.PATH}" + } + + stage('Checkout') { + checkout scm + } + + stage('Build'){ + sh "mvn clean package" + } + + stage('Sonar'){ + try { + sh "mvn sonar:sonar" + } catch(error){ + echo "The sonar server could not be reached ${error}" + } + } +} +// stage("Image Prune"){ + // imagePrune(CONTAINER_NAME) +// } + +// stage('Image Build'){ +// imageBuild(CONTAINER_NAME, CONTAINER_TAG) +// } + +// stage('Push to Docker Registry'){ +// withCredentials([usernamePassword(credentialsId: 'dockerHubAccount', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) { +// pushToImage(CONTAINER_NAME, CONTAINER_TAG, USERNAME, PASSWORD) +// } +// } + +// stage('Run App'){ +// runApp(CONTAINER_NAME, CONTAINER_TAG, DOCKER_HUB_USER, HTTP_PORT) +// } + +//} + +//def imagePrune(containerName){ + // try { + // sh "docker image prune -f" + // sh "docker stop $containerName" + // } catch(error){} +//} + +//def imageBuild(containerName, tag){ +// sh "docker build -t $containerName:$tag -t $containerName --pull --no-cache ." +// echo "Image build complete" +//} + +//def pushToImage(containerName, tag, dockerUser, dockerPassword){ +// sh "docker login -u $dockerUser -p $dockerPassword" +// sh "docker tag $containerName:$tag $dockerUser/$containerName:$tag" +// sh "docker push $dockerUser/$containerName:$tag" +// echo "Image push complete" +//} + +//def runApp(containerName, tag, dockerHubUser, httpPort){ +// sh "docker pull $dockerHubUser/$containerName" + //sh "docker run -d --rm -p $httpPort:$httpPort --name $containerName $dockerHubUser/$containerName:$tag" +// sh "docker-compose up --name $containerName $dockerHubUser/$containerName:$tag" +// echo "Application started on port: ${httpPort} (http)" +//} diff --git a/Kubernetes/Doc/db-claim0-persistentvolumeclaim.yaml b/Kubernetes/Doc/db-claim0-persistentvolumeclaim.yaml new file mode 100644 index 0000000..b929a0f --- /dev/null +++ b/Kubernetes/Doc/db-claim0-persistentvolumeclaim.yaml @@ -0,0 +1,14 @@ +apiVersion: v1 +kind: PersistentVolume +metadata: + creationTimestamp: null +# labels: +# io.kompose.service: task-pv-volume +# name: task-pv-volume +spec: + accessModes: + - ReadWriteOnce + resources: + requests: + storage: 100Mi +status: {} diff --git a/Kubernetes/Doc/docker-compose.yml b/Kubernetes/Doc/docker-compose.yml new file mode 100644 index 0000000..d5b2df0 --- /dev/null +++ b/Kubernetes/Doc/docker-compose.yml @@ -0,0 +1,45 @@ +# MySQL database shared with tomcat containers. +db: + image: mysql:latest + environment: + MYSQL_ROOT_PASSWORD: admin + MYSQL_DATABASE: giit + MYSQL_USER: example_db_user + MYSQL_PASSWORD: example_db_pass + volumes: + - ./sql:/docker-entrypoint-initdb.d + ports: + - "3306:3306" + +# First node of the first Tomcat virtual host. +tomcat: + image: tomcat:latest + # Environment variables do not appear to be getting loaded the first time Tomcat starts! + environment: + # VIRTUAL_HOST: tomcat_1.mulligan.ie + # VIRTUAL_PORT: 8080 + JDBC_URL: jdbc:mysql://db:3306/giit?connectTimeout=0&socketTimeout=0&autoReconnect=true + MYSQL_USER: example_db_user + MYSQL_PASSWORD: example_db_pass +# volumes: +# - ./warfiel:/usr/local/tomcat/webapps + # ports: + # - "8080:8080" + links: + - db + +# nginx container that automatically creates a load balancer / reverse proxy across the 3 tomcat containers / 2 virtual hosts. +nginx: +#image: jwilder/nginx-proxy:latest + image: nginx:1.13 + restart: always + volumes: + - ./nginx:/etc/nginx/conf.d + ports: + - "8081:80" + # - "443:443" + # volumes: + # - /var/run/docker.sock:/tmp/docker.sock:ro + + links: + - tomcat diff --git a/Kubernetes/Doc/nginx-claim0-persistentvolumeclaim.yaml b/Kubernetes/Doc/nginx-claim0-persistentvolumeclaim.yaml new file mode 100644 index 0000000..a03484d --- /dev/null +++ b/Kubernetes/Doc/nginx-claim0-persistentvolumeclaim.yaml @@ -0,0 +1,14 @@ +apiVersion: v1 +kind: PersistentVolume +metadata: + creationTimestamp: null +# labels: +# io.kompose.service: nginx-pv-volume +# name: nginx-pv-volume +spec: + accessModes: + - ReadWriteOnce + resources: + requests: + storage: 100Mi +status: {} diff --git a/Kubernetes/Doc/nginx-volume.yaml b/Kubernetes/Doc/nginx-volume.yaml new file mode 100644 index 0000000..1ed32d4 --- /dev/null +++ b/Kubernetes/Doc/nginx-volume.yaml @@ -0,0 +1,14 @@ +kind: StorageClass +apiVersion: storage.k8s.io/v1 +metadata: + name: nginx-pv-volume + labels: + type: local +spec: + storageClassName: manual + capacity: + storage: 100Mi + accessModes: + - ReadWriteOnce + hostPath: + path: "/mnt/nginx" diff --git a/Kubernetes/Doc/pv-volume.yaml b/Kubernetes/Doc/pv-volume.yaml new file mode 100644 index 0000000..311a494 --- /dev/null +++ b/Kubernetes/Doc/pv-volume.yaml @@ -0,0 +1,14 @@ +kind: StorageClass +apiVersion: storage.k8s.io/v1 +metadata: + name: task-pv-volume + labels: + type: local +spec: + storageClassName: manual + capacity: + storage: 100Mi + accessModes: + - ReadWriteOnce + hostPath: + path: "/mnt/data" diff --git a/Kubernetes/db-deployment.yaml b/Kubernetes/db-deployment.yaml new file mode 100644 index 0000000..161ea4f --- /dev/null +++ b/Kubernetes/db-deployment.yaml @@ -0,0 +1,40 @@ +apiVersion: extensions/v1beta1 +kind: Deployment +metadata: + name: db + creationTimestamp: null + labels: + app: db +spec: + selector: + matchLabels: + app: db + replicas: 1 + strategy: + type: Recreate + template: + metadata: + creationTimestamp: null + labels: + app: db + spec: + containers: + - image: mysql:latest + name: db + env: + + - name: MYSQL_DATABASE + value: giit + - name: MYSQL_PASSWORD + value: example_db_pass + - name: MYSQL_USER + value: example_db_user +# - name: MYSQL_ROOT_PASSWORD +# valueFrom: +# secretKeyRef: +# name: mysql-pass +# key: password + ports: + - containerPort: 3306 + name: db +status: {} diff --git a/Kubernetes/db-service.yaml b/Kubernetes/db-service.yaml new file mode 100644 index 0000000..dece6a6 --- /dev/null +++ b/Kubernetes/db-service.yaml @@ -0,0 +1,20 @@ +apiVersion: v1 +kind: Service +metadata: + annotations: +# kompose.cmd: kompose --file Doc/docker-compose.yml convert +# kompose.version: 1.17.0 (a74acad) + creationTimestamp: null + labels: +# io.kompose.service: db + name: db +spec: + ports: + - name: "3306" + port: 3306 + targetPort: 3306 + selector: +# io.kompose.service: db + name: db +status: + loadBalancer: {} diff --git a/Kubernetes/nginx-deployment.yaml b/Kubernetes/nginx-deployment.yaml new file mode 100644 index 0000000..b4f9f6b --- /dev/null +++ b/Kubernetes/nginx-deployment.yaml @@ -0,0 +1,31 @@ +apiVersion: extensions/v1beta1 +kind: Deployment +metadata: +# annotations: +# kompose.cmd: kompose --file Doc/docker-compose.yml convert +# kompose.version: 1.17.0 (a74acad) + creationTimestamp: null + labels: + name: nginx + name: nginx +spec: + replicas: 1 + strategy: + type: Recreate + template: + metadata: + creationTimestamp: null + labels: + name: nginx + spec: + containers: + - image: nginx:latest + name: nginx + ports: + - containerPort: 80 +# resources: {} +# volumeMounts: +# - mountPath: /etc/nginx/conf.d +# name: nginx-pv-volume + restartPolicy: Always +status: {} diff --git a/Kubernetes/nginx-service.yaml b/Kubernetes/nginx-service.yaml new file mode 100644 index 0000000..d2dba48 --- /dev/null +++ b/Kubernetes/nginx-service.yaml @@ -0,0 +1,20 @@ +apiVersion: v1 +kind: Service +metadata: + annotations: +# kompose.cmd: kompose --file Doc/docker-compose.yml convert +# kompose.version: 1.17.0 (a74acad) + creationTimestamp: null + labels: +# io.kompose.service: nginx + name: nginx +spec: + ports: + - name: "8081" + port: 8081 + targetPort: 80 + selector: +# io.kompose.service: nginx + name: nginx +status: + loadBalancer: {} diff --git a/Kubernetes/nginx/nginx.conf b/Kubernetes/nginx/nginx.conf new file mode 100644 index 0000000..4f9c8b6 --- /dev/null +++ b/Kubernetes/nginx/nginx.conf @@ -0,0 +1,15 @@ + + upstream backend { + server tomcat:8080; +# server tomcat_1_node_2:8080; + # server 192.0.0.1 backup; +# server tomcat_1.mulligan.ie:8080; +# server tomcat_2.mulligan.ie:8080 + } +server { + listen 80; + location / { + proxy_pass http://backend; + } +} + diff --git a/Kubernetes/sql/create.sql b/Kubernetes/sql/create.sql new file mode 100644 index 0000000..b346b94 --- /dev/null +++ b/Kubernetes/sql/create.sql @@ -0,0 +1,182 @@ +######################## +# Drop all table +######################## + +DROP TABLE IF EXISTS book, class, course, department, order_book, resource, role, section, speciality, staff, student, takes, timetable, user; + +CREATE TABLE book +( + book_title VARCHAR(30), + isbn VARCHAR(20), + date_of_printing VARCHAR(20), + author VARCHAR(15), + press VARCHAR(15), + category CHAR, + unit_price FLOAT, + PRIMARY KEY (book_title, isbn) +) + DEFAULT CHARSET = utf8, + ENGINE = InnoDB; + +CREATE TABLE class +( + class_id VARCHAR(30), + class_name VARCHAR(10), + year VARCHAR(20), + spec_name VARCHAR(15), + PRIMARY KEY (class_id) +) + DEFAULT CHARSET = utf8, + ENGINE = InnoDB; + +CREATE TABLE course +( + course_title VARCHAR(30), + type VARCHAR(10), + credits FLOAT, + speciality VARCHAR(15), + PRIMARY KEY (course_title) +) + DEFAULT CHARSET = utf8, + ENGINE = InnoDB; + +CREATE TABLE department +( + dept_id INT AUTO_INCREMENT, + dept_name VARCHAR(15), + PRIMARY KEY (dept_id) +) + DEFAULT CHARSET = utf8, + ENGINE = InnoDB; + +CREATE TABLE order_book +( + staff_id VARCHAR(30), + sec_id INT, + book_title VARCHAR(30), + isbn VARCHAR(20), + remark VARCHAR(30), + approval TINYINT(1), + PRIMARY KEY (staff_id, sec_id, book_title, isbn) +) + DEFAULT CHARSET = utf8, + ENGINE = InnoDB; + +CREATE TABLE resource ( + id BIGINT AUTO_INCREMENT, + name VARCHAR(100), + type VARCHAR(50), + url VARCHAR(200), + parent_id BIGINT, + parent_ids VARCHAR(100), + permission VARCHAR(100), + available BOOL DEFAULT FALSE, + PRIMARY KEY (id) +) + CHARSET = utf8 + ENGINE = InnoDB; +CREATE INDEX idx_resource_parent_id ON resource (parent_id); +CREATE INDEX idx_resource_parent_ids ON resource (parent_ids); + +CREATE TABLE role ( + id BIGINT AUTO_INCREMENT, + role VARCHAR(100), + description VARCHAR(100), + resource_ids VARCHAR(100), + available BOOL DEFAULT FALSE, + PRIMARY KEY (id) +) + CHARSET = utf8 + ENGINE = InnoDB; +CREATE INDEX idx_sys_role_resource_ids ON role (resource_ids); + +CREATE TABLE section +( + sec_id INT AUTO_INCREMENT, + course_title VARCHAR(15), + year VARCHAR(5), + limitCount INT, + staff_id VARCHAR(20), + PRIMARY KEY (sec_id) +) + DEFAULT CHARSET = utf8, + ENGINE = InnoDB; + +CREATE TABLE speciality +( + spec_id INT AUTO_INCREMENT, + dept_name VARCHAR(10), + spec_name VARCHAR(15), + year VARCHAR(5), + PRIMARY KEY (spec_id) +) + DEFAULT CHARSET = utf8, + ENGINE = InnoDB; + +CREATE TABLE staff +( + staff_id VARCHAR(30), + staff_name VARCHAR(20), + PRIMARY KEY (staff_id) +) + DEFAULT CHARSET = utf8, + ENGINE = InnoDB; + +CREATE TABLE student +( + student_id VARCHAR(30), + student_name VARCHAR(20), + id_card VARCHAR(20), + year VARCHAR(5), + class_id VARCHAR(10), + telephone_number VARCHAR(20), + student_origin_base VARCHAR(10), + gender VARCHAR(4), + pic_path VARCHAR(45), + leave_of_absence BOOL, + leave_school BOOL, + PRIMARY KEY (student_id) +) + DEFAULT CHARSET = utf8, + ENGINE = InnoDB; + +CREATE TABLE takes +( + student_id VARCHAR(30), + sec_id VARCHAR(30), + score FLOAT, + PRIMARY KEY (student_id, sec_id) +) + DEFAULT CHARSET = utf8, + ENGINE = InnoDB; + +CREATE TABLE timetable +( + sec_id INT, + time VARCHAR(20), + weeks VARCHAR(20), + week VARCHAR(20), + classroom VARCHAR(10) +) + DEFAULT CHARSET = utf8, + ENGINE = InnoDB; + +CREATE TABLE user +( + user_id VARCHAR(30), + password VARCHAR(50), + salt VARCHAR(100), + role_ids VARCHAR(100), + locked BOOL DEFAULT FALSE, + PRIMARY KEY (user_id) +) + DEFAULT CHARSET = utf8, + ENGINE = InnoDB; +CREATE UNIQUE INDEX idx_user_username ON user (user_id); + +#ALTER TABLE staff ADD CONSTRAINT fk_user_staff FOREIGN KEY (staff_id) REFERENCES orders (user_id); +#ALTER TABLE order_book ADD CONSTRAINT fk_courses_user_books_classe FOREIGN KEY (staffs_id) REFERENCES staffs (staff_id), +#FOREIGN KEY (book_title,isbn) REFERENCES book (book_title,isbn), +#FOREIGN KEY (grade,professional,department) REFERENCES class (grade,professional,department), +#FOREIGN KEY (course_id) REFERENCES course (courses_id); + diff --git a/Kubernetes/sql/populate.sql b/Kubernetes/sql/populate.sql new file mode 100644 index 0000000..835d8ec --- /dev/null +++ b/Kubernetes/sql/populate.sql @@ -0,0 +1,50 @@ + +INSERT INTO user (user_id, password, salt, role_ids, locked) +VALUES ('admin', '3ab82b226b3b60f4eab8cd0a88887ba0', 'cd0faf6f821809044e35e35fd23cf44a', '1', 0); + +INSERT INTO user (user_id, password, salt, role_ids, locked) +VALUES ('student', '5476883b25e9c7bb0528b6fdfa0f5de7', '20d98880380112ff6404bdcaa4ba9c10', '2', 0); + +INSERT INTO user (user_id, password, salt, role_ids, locked) +VALUES ('student2', '5476883b25e9c7bb0528b6fdfa0f5de7', '20d98880380112ff6404bdcaa4ba9c10', '2', 0); + + +INSERT INTO user (user_id, password, salt, role_ids, locked) +VALUES ('teacher', 'f7e7844cad9aadb0c7f1722f2c9be050', 'a7bbf832a7472759146b0967a78e6ce5', '3', 0); + +INSERT INTO user (user_id, password, salt, role_ids, locked) +VALUES ('supplier', '19a885f6627571598621fe5f5e9cbbc5', '9c64193184d34fa04a205d06b93ca3d6', '4', 0); + +INSERT INTO role (role, description, resource_ids, available) VALUES ('admin', '管理员', '', 1); +INSERT INTO role (role, description, resource_ids, available) VALUES ('student', '学生', '', 1); +INSERT INTO role (role, description, resource_ids, available) VALUES ('teacher', '老师', '', 1); +INSERT INTO role (role, description, resource_ids, available) VALUES ('supplier', '供应商', '', 1); + +INSERT INTO staff (staff_id, staff_name) VALUES ('teacher', 'teacher'); + + +INSERT INTO book (book_title, isbn, date_of_printing, author, press, category, unit_price) +VALUES ('Effective JAVA', '1561315135213', '2008', 'Joshua Bloch', '工业出版社', 'A', 88); + +INSERT INTO department (dept_name) VALUES ('管理系'); +INSERT INTO department (dept_name) VALUES ('信息工程系'); +INSERT INTO department (dept_name) VALUES ('机电系'); + +INSERT INTO speciality (dept_name, spec_name) VALUES ('信息工程系', '网络工程'); + +INSERT INTO section (course_title, year, limitCount, staff_id) VALUES ('网络技术', 20161, 8, 'teacher'); + +INSERT INTO order_book (staff_id, sec_id, book_title, isbn, remark, approval) +VALUES ('teacher', 1, 'Effective JAVA', '1561315135213', '不要二手', 1); + +INSERT INTO course (course_title, type, credits, speciality) +VALUES ('网络技术', '必修课/公共课', 4, '网络工程'); + +INSERT INTO class (class_id, year, spec_name) +VALUES ('161111', 20161, '网络工程'); + +INSERT INTO takes (student_id, sec_id, score) +VALUES ('student', 1, 5); + +INSERT INTO takes (student_id, sec_id, score) +VALUES ('student2', 1, 5); \ No newline at end of file diff --git a/Kubernetes/tomcat-deployment.yaml b/Kubernetes/tomcat-deployment.yaml new file mode 100644 index 0000000..015f842 --- /dev/null +++ b/Kubernetes/tomcat-deployment.yaml @@ -0,0 +1,41 @@ +apiVersion: extensions/v1beta1 +kind: Deployment +metadata: + annotations: + labels: + app: tomcat + +# kompose.cmd: kompose --file docker-compose.yml convert +# kompose.version: 1.17.0 (a74acad) + creationTimestamp: null +# labels: +# io.kompose.service: tomcat-1-node-1 + name: tomcat +spec: + selector: + matchLabels: + app: tomcat + replicas: 1 +# strategy: +# type: Recreate + template: + metadata: + creationTimestamp: null + labels: + app: tomcat +# io.kompose.service: tomcat-1-node-1 + spec: + containers: + - env: + - name: JDBC_URL + value: "jdbc:mysql://db:3306/giit?connectTimeout=0&socketTimeout=0&autoReconnect=true" + - name: MYSQL_PASSWORD + value: example_db_pass + - name: MYSQL_USER + value: example_db_user + image: yuvarajmindtree/tomcat:latest + name: tomcat +# resources: {} +# restartPolicy: Always +status: {} + diff --git a/README.md b/README.md index 3a6caaf..bd4b648 100644 --- a/README.md +++ b/README.md @@ -1,80 +1,75 @@ -# 简介 -这是个简单的教务系统网站,并且结合了图书订购功能,希望这个小DEMO能对大家学习有帮助 +Introduction +This is a simple educational system website, and combined with the book ordering function, I hope this small DEMO can help everyone learn. -# 使用技术 +Use technology +IoC container: spring -IoC容器:spring +Web framework: springmvc -web框架:springmvc +Orm framework: mybatis -orm框架:mybatis +Security framework: shiro -安全框架:shiro +Data source: dbcp2 -数据源:dbcp2 - -日志: sl4j +Log: sl4j Json: Gson -前端框架:Bootstrap - -# 起步: - -1.初始化项目 - -1)下载Mysql,创建一个数据库名字为giit,导入create.sql与populate.sql,直接运行其中sql即可 +Front End Framework: Bootstrap -2)下载Tomcat +Start: +1. Initialize the project -3)使用Intellij Idea导入项目,之后配置项目启动方式,使用刚才下载好的Tomcat - -4)运行 +1) Download Mysql, create a database name for giit, import create.sql and populate.sql, run sql directly -![image](https://pic4.zhimg.com/v2-87231f2eb533cdab3d3e04c7a89457af_b.png) +2) Download Tomcat -# 使用简介: +3) Import the project using Intellij Idea, then configure the project startup mode, use the Tomcat just downloaded -1.权限介绍: +4) running -根据导入的populate.sql,运行网站初始时会存在四个权限角色: +image -1).管理员,账号为admin +Introduction to use: +1. Introduction to permissions: -2).学生,账号为student +According to the imported populate.sql, there are four permission roles when running the website initially: -3).教师,账号为teache +1). Administrator, account is admin -4).供应商,账号为supplier +2). Student, account number is student -*密码均为123456* +3). Teacher, account number is teache -# 功能介绍: -## 1.基本信息功能: -其中可以设置一些基本的学校信息,也就是数据库中的实体-关系,之后就可以基于这些基本的关系信息进行更加复杂的功能,例如选课后可以记录多少学生选择了这门课程,只会教师提交图书后计算图书总数可以通过其中的关系得到 +4). Supplier, account number is supplier -1)系部信息 +The password is 123456 -2)专业信息 +Features: +1. Basic information function: +Some basic school information, that is, entity-relationships in the database, can be set up, and then more complex functions can be performed based on these basic relationship information. For example, after class selection, how many students can select this course, only the teacher submits The total number of books counted after the book can be obtained through the relationship -3)班级信息 +1) Department information -4)课程信息 +2) Professional information -5)学生管理 +3) Class information -![image](https://pic1.zhimg.com/v2-44688d7a989ae25d9db6767a50a208f8_b.png) +4) Course Information +5) Student Management -## 2.图书管理功能: -1)教师上传图书 +image -2)秘书审批图书 +2. Book management function: +1) Teacher uploads books -3)查看已审核图书 +2) Secretary approves books -![image](https://pic3.zhimg.com/v2-3ff2f0da17e8609f85da3b61671cf0de_b.png) +3) View reviewed books -# 数据库表结构: -![image](http://7xi78h.com1.z0.glb.clouddn.com/db.png) +image +Database table structure: +image diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..eee87cc --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,63 @@ +# MySQL database shared with tomcat containers. +db: + image: mysql:latest + environment: + MYSQL_ROOT_PASSWORD: admin + MYSQL_DATABASE: giit + MYSQL_USER: example_db_user + MYSQL_PASSWORD: example_db_pass + volumes: + - ./sql:/docker-entrypoint-initdb.d + # expose: + # - "3306" + +# First node of the first Tomcat virtual host. +tomcat_1_node_1: + image: tomcat:latest + # Environment variables do not appear to be getting loaded the first time Tomcat starts! + environment: + # VIRTUAL_HOST: tomcat_1.mulligan.ie + # VIRTUAL_PORT: 8080 + JDBC_URL: jdbc:mysql://db:3306/giit?connectTimeout=0&socketTimeout=0&autoReconnect=true + MYSQL_USER: example_db_user + MYSQL_PASSWORD: example_db_pass + volumes: + - ./tomcat:/usr/local/tomcat/webapps + # expose: + # - "8080" + links: + - db + +# Second node of the first Tomcat virtual host. +tomcat_1_node_2: + image: tomcat:latest + # Environment variables do not appear to be getting loaded the first time Tomcat starts! + environment: + # VIRTUAL_HOST: tomcat_1.mulligan.ie + # VIRTUAL_PORT: 8080 + JDBC_URL: jdbc:mysql://db:3306/giit?connectTimeout=0&socketTimeout=0&autoReconnect=true + MYSQL_USER: example_db_user + MYSQL_PASSWORD: example_db_pass + volumes: + - ./tomcat:/usr/local/tomcat/webapps + # expose: + # - "8080" + links: + - db + +# nginx container that automatically creates a load balancer / reverse proxy across the 3 tomcat containers / 2 virtual hosts. +nginx: +#image: jwilder/nginx-proxy:latest + image: nginx:1.13 + restart: always + volumes: + - ./nginx:/etc/nginx/conf.d + ports: + - "8081:80" + # - "443:443" + # volumes: + # - /var/run/docker.sock:/tmp/docker.sock:ro + + links: + - tomcat_1_node_1 + - tomcat_1_node_2 diff --git a/nginx/nginx.conf b/nginx/nginx.conf new file mode 100644 index 0000000..8b73876 --- /dev/null +++ b/nginx/nginx.conf @@ -0,0 +1,15 @@ + + upstream backend { + server tomcat_1_node_1:8080; + server tomcat_1_node_2:8080; + # server 192.0.0.1 backup; +# server tomcat_1.mulligan.ie:8080; +# server tomcat_2.mulligan.ie:8080 + } +server { + listen 80; + location / { + proxy_pass http://backend; + } +} + diff --git a/src/main/webapp/WEB-INF/view/admin/college/clazz.jsp b/src/main/webapp/WEB-INF/view/admin/college/clazz.jsp index b75aa5c..a272818 100644 --- a/src/main/webapp/WEB-INF/view/admin/college/clazz.jsp +++ b/src/main/webapp/WEB-INF/view/admin/college/clazz.jsp @@ -7,14 +7,14 @@
-

班级管理

+ < h1 class = " page-header " >Class Management
<%----%>
- 班级信息 + Class information
@@ -23,8 +23,8 @@ - 所属专业 - 班级号 + < th >Professional + < th > class number @@ -36,7 +36,7 @@ ${clazz.clazzId} 删除 + Onclick = " return confirm('whether you want to delete the professional') " >delete @@ -56,7 +56,7 @@ <%----%>
- 添加班级 + Add class
@@ -65,4 +65,3 @@ - diff --git a/src/main/webapp/WEB-INF/view/admin/college/clazz_add.jsp b/src/main/webapp/WEB-INF/view/admin/college/clazz_add.jsp index 413d6b5..77f0dd8 100644 --- a/src/main/webapp/WEB-INF/view/admin/college/clazz_add.jsp +++ b/src/main/webapp/WEB-INF/view/admin/college/clazz_add.jsp @@ -6,7 +6,7 @@
-

添加班级

+ < h1 class = " page-header " >Add class
@@ -14,24 +14,24 @@
- 班级信息 + Class information
- + < label > belongs to the department - + < label > belongs to the profession - + < label >year of opening --%>
@@ -65,78 +65,61 @@
diff --git a/src/main/webapp/WEB-INF/view/admin/college/course.jsp b/src/main/webapp/WEB-INF/view/admin/college/course.jsp index 7273f6d..c32a571 100644 --- a/src/main/webapp/WEB-INF/view/admin/college/course.jsp +++ b/src/main/webapp/WEB-INF/view/admin/college/course.jsp @@ -5,7 +5,7 @@
-

课程管理

+ < h1 class = " page-header " > Course Management
@@ -14,7 +14,7 @@
- 课程信息 + course information
@@ -24,10 +24,10 @@ - 名称 - 类型 - 学分 - 所属专业 + < th > name + < th >type + < th > credits + < th >Professional @@ -40,7 +40,7 @@ ${course.speciality} 删除 + Onclick = " return confirm('whether you want to delete the lesson') " >delete @@ -66,4 +66,3 @@ - diff --git a/src/main/webapp/WEB-INF/view/admin/college/course_add.jsp b/src/main/webapp/WEB-INF/view/admin/college/course_add.jsp index 1a11720..f09549c 100644 --- a/src/main/webapp/WEB-INF/view/admin/college/course_add.jsp +++ b/src/main/webapp/WEB-INF/view/admin/college/course_add.jsp @@ -5,7 +5,7 @@
-

添加课程

+ < h1 class = " page-header " >Add a course
@@ -13,45 +13,45 @@
- 课程信息 + course information
- + < label > Course name <%-- 省--%> <%-- 市--%> - + < label > credits - + < label > belongs to the profession - + < label > course type
@@ -65,4 +65,3 @@ - diff --git a/src/main/webapp/WEB-INF/view/admin/system/resource/resource_add.jsp b/src/main/webapp/WEB-INF/view/admin/system/resource/resource_add.jsp index 2b4b2c0..2219ecf 100644 --- a/src/main/webapp/WEB-INF/view/admin/system/resource/resource_add.jsp +++ b/src/main/webapp/WEB-INF/view/admin/system/resource/resource_add.jsp @@ -6,7 +6,7 @@
-

用户管理

+ < h1 class = " page-header " > User Management
@@ -14,22 +14,22 @@
- 用户信息 + User Info
- + < label > role name - + < label > role description - + < label > owned resources
@@ -52,5 +52,3 @@ - - diff --git a/src/main/webapp/WEB-INF/view/admin/system/role/role.jsp b/src/main/webapp/WEB-INF/view/admin/system/role/role.jsp index bc1c7f3..80c79b0 100644 --- a/src/main/webapp/WEB-INF/view/admin/system/role/role.jsp +++ b/src/main/webapp/WEB-INF/view/admin/system/role/role.jsp @@ -6,7 +6,7 @@
-

角色管理

+ < h1 class = " page-header " > Role Management
@@ -14,7 +14,7 @@
- 角色信息 + Role information
@@ -22,10 +22,10 @@ - - - - + < th >role name + < th >character description + < th > owned resources + < th > operation @@ -36,14 +36,14 @@
角色名称角色描述拥有的资源操作
${role.resourceIdsStr} 删除 + Onclick = " return confirm('whether you want to delete the role') " >delete
添加角色 + Role = " Button " > Add Role
@@ -63,4 +63,3 @@ - diff --git a/src/main/webapp/WEB-INF/view/admin/system/role/role_add.jsp b/src/main/webapp/WEB-INF/view/admin/system/role/role_add.jsp index 87a384b..47809f1 100644 --- a/src/main/webapp/WEB-INF/view/admin/system/role/role_add.jsp +++ b/src/main/webapp/WEB-INF/view/admin/system/role/role_add.jsp @@ -6,7 +6,7 @@
-

用户管理

+ < h1 class = " page-header " > User Management
@@ -14,21 +14,21 @@
- 用户信息 + User Info
- + < label > role name - + < label > role description - <%----%> + <%-- --%> <%----%>
@@ -52,4 +52,3 @@ - diff --git a/src/main/webapp/WEB-INF/view/admin/system/user/user.jsp b/src/main/webapp/WEB-INF/view/admin/system/user/user.jsp index 4c50618..5d5c90d 100644 --- a/src/main/webapp/WEB-INF/view/admin/system/user/user.jsp +++ b/src/main/webapp/WEB-INF/view/admin/system/user/user.jsp @@ -6,7 +6,7 @@
-

用户管理

+ < h1 class = " page-header " > User Management
@@ -14,7 +14,7 @@
- 用户信息 + User Info
@@ -22,10 +22,10 @@ - - - - + < th >username + < th >password + < th > permissions + < th >Email <%----%> @@ -40,14 +40,14 @@ <%----%>
用户名密码权限邮箱
修改 删除 + Onclick = " return confirm('whether you want to delete this user') " >delete
添加用户 + Role = " button " >Add user
diff --git a/src/main/webapp/WEB-INF/view/admin/system/user/user_add.jsp b/src/main/webapp/WEB-INF/view/admin/system/user/user_add.jsp index 2eb2dec..76f6888 100644 --- a/src/main/webapp/WEB-INF/view/admin/system/user/user_add.jsp +++ b/src/main/webapp/WEB-INF/view/admin/system/user/user_add.jsp @@ -7,7 +7,7 @@
-

用户管理

+ < h1 class = " page-header " > User Management
@@ -15,19 +15,19 @@
- 用户信息 + User Info
- + < label >username - + < label >password - + < label >mailbox - + < label >list of characters (hold down the shift key to select multiple)

- + < label > new password - + < label >mailbox
- 角色列表: + < form:label path = " roleIds " >list of roles: - (按住shift键多选) + (hold down the shift key to select more)
diff --git a/src/main/webapp/WEB-INF/view/student/elective.jsp b/src/main/webapp/WEB-INF/view/student/elective.jsp index 26aa916..296b5a9 100644 --- a/src/main/webapp/WEB-INF/view/student/elective.jsp +++ b/src/main/webapp/WEB-INF/view/student/elective.jsp @@ -6,13 +6,13 @@
-

选课

+

Elective course

- 已开设课程信息 + Course information has been created
@@ -20,9 +20,9 @@ - - - + < th > Course ID + < th > Course Name + < th >teachers @@ -34,7 +34,7 @@ diff --git a/src/main/webapp/WEB-INF/view/student/main.jsp b/src/main/webapp/WEB-INF/view/student/main.jsp index 17069b4..c2e88a5 100644 --- a/src/main/webapp/WEB-INF/view/student/main.jsp +++ b/src/main/webapp/WEB-INF/view/student/main.jsp @@ -6,7 +6,7 @@
-

学生主页

+ < h1 class = " page-header " >Student Homepage
@@ -14,7 +14,7 @@
- 学生主页 + Student homepage
diff --git a/src/main/webapp/WEB-INF/view/student/nav.jsp b/src/main/webapp/WEB-INF/view/student/nav.jsp index f3bd4fc..8f8484c 100644 --- a/src/main/webapp/WEB-INF/view/student/nav.jsp +++ b/src/main/webapp/WEB-INF/view/student/nav.jsp @@ -11,7 +11,7 @@ - 桂林电子科技大学教材订购系统 + < title >Guilin University of Electronic Science and Technology Textbook Ordering System @@ -50,7 +50,7 @@ - 桂林电子科技大学教材订购系统 + < a class = " navbar-brand " href = " # " > Guilin University of Electronic Technology textbook ordering system
@@ -60,11 +60,11 @@ @@ -77,16 +77,16 @@ - \ No newline at end of file + diff --git a/src/main/webapp/WEB-INF/view/supplier/main.jsp b/src/main/webapp/WEB-INF/view/supplier/main.jsp index b46c67e..b1d130a 100644 --- a/src/main/webapp/WEB-INF/view/supplier/main.jsp +++ b/src/main/webapp/WEB-INF/view/supplier/main.jsp @@ -6,14 +6,14 @@
-

已添加教材

+ < h1 class = " page-header " >Textbook added
- 已添加教材 + Added textbook
@@ -23,12 +23,12 @@ id="dataTables-example">
- + < th > title - - - - + < th > date of printing + < th > author + < th >publisher + < th > number @@ -58,4 +58,3 @@ - diff --git a/src/main/webapp/WEB-INF/view/supplier/nav.jsp b/src/main/webapp/WEB-INF/view/supplier/nav.jsp index b7c28bd..c48095a 100644 --- a/src/main/webapp/WEB-INF/view/supplier/nav.jsp +++ b/src/main/webapp/WEB-INF/view/supplier/nav.jsp @@ -11,7 +11,7 @@ - 桂林电子科技大学教材订购系统 + < title >Guilin University of Electronic Science and Technology Textbook Ordering System @@ -50,7 +50,7 @@ - 桂林电子科技大学教材订购系统 + < a class = " navbar-brand " href = " # " > Guilin University of Electronic Technology textbook ordering system @@ -60,11 +60,11 @@ @@ -77,11 +77,11 @@ - \ No newline at end of file + diff --git a/src/main/webapp/WEB-INF/view/supplier/supplier.jsp b/src/main/webapp/WEB-INF/view/supplier/supplier.jsp index 23477c3..9d33d0a 100644 --- a/src/main/webapp/WEB-INF/view/supplier/supplier.jsp +++ b/src/main/webapp/WEB-INF/view/supplier/supplier.jsp @@ -6,14 +6,14 @@
-

采购清单

+ < h1 class = " page-header " >Purchase List
- 采购清单 + Purchasing List
@@ -23,12 +23,12 @@ id="dataTables-example">
- + < th > title - - - - + < th > date of printing + < th > author + < th >publisher + < th > number @@ -67,4 +67,3 @@ - diff --git a/src/main/webapp/WEB-INF/view/teacher/main.jsp b/src/main/webapp/WEB-INF/view/teacher/main.jsp index ae76108..f42d0bf 100644 --- a/src/main/webapp/WEB-INF/view/teacher/main.jsp +++ b/src/main/webapp/WEB-INF/view/teacher/main.jsp @@ -6,7 +6,7 @@
-

教师主页

+ < h1 class = " page-header " >Teacher Homepage
@@ -14,7 +14,7 @@
- 教师主页 + Teacher homepage
diff --git a/src/main/webapp/WEB-INF/view/teacher/nav.jsp b/src/main/webapp/WEB-INF/view/teacher/nav.jsp index 6d10bb3..cd8accf 100644 --- a/src/main/webapp/WEB-INF/view/teacher/nav.jsp +++ b/src/main/webapp/WEB-INF/view/teacher/nav.jsp @@ -11,7 +11,7 @@ - 桂林电子科技大学教材订购系统 + < title >Guilin University of Electronic Science and Technology Textbook Ordering System @@ -50,7 +50,7 @@ - 桂林电子科技大学教材订购系统 + < a class = " navbar-brand " href = " # " > Guilin University of Electronic Technology textbook ordering system
@@ -80,7 +80,7 @@ 主页
  • - 成绩录入 + < a href = " # " > Grade entry
  • 教材添加 @@ -90,4 +90,4 @@
  • - \ No newline at end of file + diff --git a/src/main/webapp/WEB-INF/view/teacher/orderbook.jsp b/src/main/webapp/WEB-INF/view/teacher/orderbook.jsp index 155935a..8159ed2 100644 --- a/src/main/webapp/WEB-INF/view/teacher/orderbook.jsp +++ b/src/main/webapp/WEB-INF/view/teacher/orderbook.jsp @@ -7,13 +7,13 @@
    -

    已添加教材

    + < h1 class = " page-header " >Textbook added
    -

    添加教材

    + < h1 class = " page-header " >Add a textbook
    @@ -43,14 +43,14 @@
    课程ID课程名称授课老师
    ${section.teacher} 选课 + Onclick = " return confirm('whether to choose this lesson') " >chouse
    书名 ISBN印刷日期作者出版社数量
    书名 ISBN印刷日期作者出版社数量
    - + < th > title - - - - - - + < th > date of printing + < th > author + < th >publisher + < th >Textbook category + < th > unit price + < th >Remarks @@ -129,12 +129,10 @@ });

    Advanced IO and Tomcat

    Table of Contents

    Introduction

    + +

    + IMPORTANT NOTE: Usage of these features requires using the + HTTP connectors. The AJP connectors do not support them. +

    + +

    Asynchronous writes

    + +

    + When using HTTP connectors (based on APR or NIO/NIO2), + Tomcat supports using sendfile to send large static files. + These writes, as soon as the system load increases, will be performed + asynchronously in the most efficient way. Instead of sending a large response using + blocking writes, it is possible to write content to a static file, and write it + using a sendfile code. A caching valve could take advantage of this to cache the + response data in a file rather than store it in memory. Sendfile support is + available if the request attribute org.apache.tomcat.sendfile.support + is set to Boolean.TRUE. +

    + +

    + Any servlet can instruct Tomcat to perform a sendfile call by setting the appropriate + request attributes. It is also necessary to correctly set the content length + for the response. When using sendfile, it is best to ensure that neither the + request or response have been wrapped, since as the response body will be sent later + by the connector itself, it cannot be filtered. Other than setting the 3 needed + request attributes, the servlet should not send any response data, but it may use + any method which will result in modifying the response header (like setting cookies). +

    + +
      +
    • org.apache.tomcat.sendfile.filename: Canonical filename of the file which will be sent as + a String
    • +
    • org.apache.tomcat.sendfile.start: Start offset as a Long
    • +
    • org.apache.tomcat.sendfile.end: End offset as a Long
    • +
    +

    + In addition to setting these parameters it is necessary to set the content-length header. + Tomcat will not do that for you, since you may have already written data to the output stream. +

    + +

    + Note that the use of sendfile will disable any compression that Tomcat may + otherwise have performed on the response. +

    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/api/index.html b/tomcat/docs/api/index.html new file mode 100644 index 0000000..261884d --- /dev/null +++ b/tomcat/docs/api/index.html @@ -0,0 +1,34 @@ + + + + + + API docs + + + + +Tomcat's internal javadoc is not installed by default. Download and install +the "fulldocs" package to get it. + +You can also access the javadoc online in the Tomcat + +documentation bundle. + + + diff --git a/tomcat/docs/appdev/build.xml.txt b/tomcat/docs/appdev/build.xml.txt new file mode 100644 index 0000000..51d8350 --- /dev/null +++ b/tomcat/docs/appdev/build.xml.txt @@ -0,0 +1,508 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tomcat/docs/appdev/deployment.html b/tomcat/docs/appdev/deployment.html new file mode 100644 index 0000000..70247c6 --- /dev/null +++ b/tomcat/docs/appdev/deployment.html @@ -0,0 +1,244 @@ + +Application Developer's Guide (8.5.43) - Deployment

    Deployment

    Table of Contents

    Background

    + +

    Before describing how to organize your source code directories, +it is useful to examine the runtime organization of a web application. +Prior to the Servlet API Specification, version 2.2, there was little +consistency between server platforms. However, servers that conform +to the 2.2 (or later) specification are required to accept a +Web Application Archive in a standard format, which is discussed +further below.

    + +

    A web application is defined as a hierarchy of directories and files +in a standard layout. Such a hierarchy can be accessed in its "unpacked" +form, where each directory and file exists in the filesystem separately, +or in a "packed" form known as a Web ARchive, or WAR file. The former format +is more useful during development, while the latter is used when you +distribute your application to be installed.

    + +

    The top-level directory of your web application hierarchy is also the +document root of your application. Here, you will place the HTML +files and JSP pages that comprise your application's user interface. When the +system administrator deploys your application into a particular server, he +or she assigns a context path to your application (a later section +of this manual describes deployment on Tomcat). Thus, if the +system administrator assigns your application to the context path +/catalog, then a request URI referring to +/catalog/index.html will retrieve the index.html +file from your document root.

    + +

    Standard Directory Layout

    + +

    To facilitate creation of a Web Application Archive file in the required +format, it is convenient to arrange the "executable" files of your web +application (that is, the files that Tomcat actually uses when executing +your app) in the same organization as required by the WAR format itself. +To do this, you will end up with the following contents in your +application's "document root" directory:

    +
      +
    • *.html, *.jsp, etc. - The HTML and JSP pages, along + with other files that must be visible to the client browser (such as + JavaScript, stylesheet files, and images) for your application. + In larger applications you may choose to divide these files into + a subdirectory hierarchy, but for smaller apps, it is generally + much simpler to maintain only a single directory for these files. +

    • +
    • /WEB-INF/web.xml - The Web Application Deployment + Descriptor for your application. This is an XML file describing + the servlets and other components that make up your application, + along with any initialization parameters and container-managed + security constraints that you want the server to enforce for you. + This file is discussed in more detail in the following subsection. +

    • +
    • /WEB-INF/classes/ - This directory contains any Java + class files (and associated resources) required for your application, + including both servlet and non-servlet classes, that are not combined + into JAR files. If your classes are organized into Java packages, + you must reflect this in the directory hierarchy under + /WEB-INF/classes/. For example, a Java class named + com.mycompany.mypackage.MyServlet + would need to be stored in a file named + /WEB-INF/classes/com/mycompany/mypackage/MyServlet.class. +

    • +
    • /WEB-INF/lib/ - This directory contains JAR files that + contain Java class files (and associated resources) required for your + application, such as third party class libraries or JDBC drivers.
    • +
    + +

    When you install an application into Tomcat (or any other 2.2 or later +Servlet container), the classes in the WEB-INF/classes/ +directory, as well as all classes in JAR files found in the +WEB-INF/lib/ directory, are made visible to other classes +within your particular web application. Thus, if +you include all of the required library classes in one of these places (be +sure to check licenses for redistribution rights for any third party libraries +you utilize), you will simplify the installation of your web application -- +no adjustment to the system class path (or installation of global library +files in your server) will be necessary.

    + +

    Much of this information was extracted from Chapter 9 of the Servlet +API Specification, version 2.3, which you should consult for more details.

    + +

    Shared Library Files

    + +

    Like most servlet containers, Tomcat also supports mechanisms to install +library JAR files (or unpacked classes) once, and make them visible to all +installed web applications (without having to be included inside the web +application itself). The details of how Tomcat locates and shares such +classes are described in the +Class Loader How-To documentation. +The location commonly used within a Tomcat installation for shared code is +$CATALINA_HOME/lib. JAR files placed here are visible both to +web applications and internal Tomcat code. This is a good place to put JDBC +drivers that are required for both your application or internal Tomcat use +(such as for a JDBCRealm).

    + +

    Out of the box, a standard Tomcat installation includes a variety +of pre-installed shared library files, including:

    +
      +
    • The Servlet 3.1 and JSP 2.3 APIs that are fundamental + to writing servlets and JavaServer Pages.

    • +
    + +

    Web Application Deployment Descriptor

    + +

    As mentioned above, the /WEB-INF/web.xml file contains the +Web Application Deployment Descriptor for your application. As the filename +extension implies, this file is an XML document, and defines everything about +your application that a server needs to know (except the context path, +which is assigned by the system administrator when the application is +deployed).

    + +

    The complete syntax and semantics for the deployment descriptor is defined +in Chapter 13 of the Servlet API Specification, version 2.3. Over time, it +is expected that development tools will be provided that create and edit the +deployment descriptor for you. In the meantime, to provide a starting point, +a basic web.xml file +is provided. This file includes comments that describe the purpose of each +included element.

    + +

    NOTE - The Servlet Specification includes a Document +Type Descriptor (DTD) for the web application deployment descriptor, and +Tomcat enforces the rules defined here when processing your application's +/WEB-INF/web.xml file. In particular, you must +enter your descriptor elements (such as <filter>, +<servlet>, and <servlet-mapping> in +the order defined by the DTD (see Section 13.3).

    + +

    Tomcat Context Descriptor

    + +

    A /META-INF/context.xml file can be used to define Tomcat specific +configuration options, such as an access log, data sources, session manager +configuration and more. This XML file must contain one Context element, which +will be considered as if it was the child of the Host element corresponding +to the Host to which the web application is being deployed. The +Tomcat configuration documentation contains +information on the Context element.

    + +

    Deployment With Tomcat

    + +

    The description below uses the variable name $CATALINA_BASE to refer the + base directory against which most relative paths are resolved. If you have + not configured Tomcat for multiple instances by setting a CATALINA_BASE + directory, then $CATALINA_BASE will be set to the value of $CATALINA_HOME, + the directory into which you have installed Tomcat.

    + +

    In order to be executed, a web application must be deployed on +a servlet container. This is true even during development. +We will describe using Tomcat to provide the execution environment. +A web application can be deployed in Tomcat by one of the following +approaches:

    +
      +
    • Copy unpacked directory hierarchy into a subdirectory in directory + $CATALINA_BASE/webapps/. Tomcat will assign a + context path to your application based on the subdirectory name you + choose. We will use this technique in the build.xml + file that we construct, because it is the quickest and easiest approach + during development. Be sure to restart Tomcat after installing or + updating your application. +

    • +
    • Copy the web application archive file into directory + $CATALINA_BASE/webapps/. When Tomcat is started, it will + automatically expand the web application archive file into its unpacked + form, and execute the application that way. This approach would typically + be used to install an additional application, provided by a third party + vendor or by your internal development staff, into an existing + Tomcat installation. NOTE - If you use this approach, + and wish to update your application later, you must both replace the + web application archive file AND delete the expanded + directory that Tomcat created, and then restart Tomcat, in order to reflect + your changes. +

    • +
    • Use the Tomcat "Manager" web application to deploy and undeploy + web applications. Tomcat includes a web application, deployed + by default on context path /manager, that allows you to + deploy and undeploy applications on a running Tomcat server without + restarting it. See Manager App How-To + for more information on using the Manager web application.

    • +
    • Use "Manager" Ant Tasks In Your Build Script. Tomcat + includes a set of custom task definitions for the Ant + build tool that allow you to automate the execution of commands to the + "Manager" web application. These tasks are used in the Tomcat deployer. +

    • +
    • Use the Tomcat Deployer. Tomcat includes a packaged tool + bundling the Ant tasks, and can be used to automatically precompile JSPs + which are part of the web application before deployment to the server. +

    • +
    + +

    Deploying your app on other servlet containers will be specific to each +container, but all containers compatible with the Servlet API Specification +(version 2.2 or later) are required to accept a web application archive file. +Note that other containers are NOT required to accept an +unpacked directory structure (as Tomcat does), or to provide mechanisms for +shared library files, but these features are commonly available.

    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/appdev/index.html b/tomcat/docs/appdev/index.html new file mode 100644 index 0000000..4decd9b --- /dev/null +++ b/tomcat/docs/appdev/index.html @@ -0,0 +1,87 @@ + +Application Developer's Guide (8.5.43) - Table of Contents

    Table of Contents

    Preface

    + +

    This manual includes contributions from many members of the Tomcat Project +developer community. The following authors have provided significant content: +

    + + +

    Table of Contents

    + +

    The information presented is divided into the following sections:

    +
      +
    • Introduction - + Briefly describes the information covered here, with + links and references to other sources of information.
    • +
    • Installation - + Covers acquiring and installing the required software + components to use Tomcat for web application development.
    • +
    • Deployment Organization - + Discusses the standard directory layout for a web application + (defined in the Servlet API Specification), the Web Application + Deployment Descriptor, and options for integration with Tomcat + in your development environment.
    • +
    • Source Organization - + Describes a useful approach to organizing the source code + directories for your project, and introduces the + build.xml used by Ant to manage compilation.
    • +
    • Development Processes - + Provides brief descriptions of typical development processes + utilizing the recommended deployment and source organizations.
    • +
    • Example Application - + This directory contains a very simple, but functionally complete, + "Hello, World" application built according to the principles + described in this manual. You can use this application to + practice using the described techniques.
    • +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/appdev/installation.html b/tomcat/docs/appdev/installation.html new file mode 100644 index 0000000..6f5fd51 --- /dev/null +++ b/tomcat/docs/appdev/installation.html @@ -0,0 +1,115 @@ + +Application Developer's Guide (8.5.43) - Installation

    Installation

    Installation

    + +

    In order to use Tomcat for developing web applications, you must first +install it (and the software it depends on). The required steps are outlined +in the following subsections.

    + +

    JDK

    + +

    Tomcat 8.5 was designed to run on Java SE 7 or later. +

    + +

    Compatible JDKs for many platforms (or links to where they can be found) +are available at +http://www.oracle.com/technetwork/java/javase/downloads/index.html.

    + +
    + +

    Tomcat

    + +

    Binary downloads of the Tomcat server are available from +https://tomcat.apache.org/. +This manual assumes you are using the most recent release +of Tomcat 8. Detailed instructions for downloading and installing +Tomcat are available here.

    + +

    In the remainder of this manual, example shell scripts assume that you have +set an environment variable CATALINA_HOME that contains the +pathname to the directory in which Tomcat has been installed. Optionally, if +Tomcat has been configured for multiple instances, each instance will have its +own CATALINA_BASE configured.

    + +
    + + +

    Ant

    + +

    Binary downloads of the Ant build tool are available from +https://ant.apache.org/. +This manual assumes you are using Ant 1.8 or later. The instructions may +also be compatible with other versions, but this has not been tested.

    + +

    Download and install Ant. +Then, add the bin directory of the Ant distribution to your +PATH environment variable, following the standard practices for +your operating system platform. Once you have done this, you will be able to +execute the ant shell command directly.

    + +
    + + +

    CVS

    + +

    Besides the required tools described above, you are strongly encouraged +to download and install a source code control system, such as the +Concurrent Version System (CVS), to maintain historical +versions of the source files that make up your web application. Besides +the server, you will also need appropriate client +tools to check out source code files, and check in modified versions.

    + +

    Detailed instructions for installing and using source code control +applications is beyond the scope of this manual. However, CVS server and +client tools for many platforms (along with documentation) can be downloaded +from http://www.cvshome.org/.

    + +
    + + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/appdev/introduction.html b/tomcat/docs/appdev/introduction.html new file mode 100644 index 0000000..fbce89f --- /dev/null +++ b/tomcat/docs/appdev/introduction.html @@ -0,0 +1,100 @@ + +Application Developer's Guide (8.5.43) - Introduction

    Introduction

    Overview

    + +

    Congratulations! You've decided to (or been told to) learn how to +build web applications using servlets and JSP pages, and picked the +Tomcat server to use for your learning and development. But now what +do you do?

    + +

    This manual is a primer covering the basic steps of using Tomcat to +set up a development environment, organize your source code, and then +build and test your application. It does not discuss architectures or +recommended coding practices for web application development, +or provide in depth instructions on operating the development +tools that are discussed. References to sources of additional information +are included in the following subsections.

    + +

    The discussion in this manual is aimed at developers who will be using +a text editor along with command line tools to develop and debug their +applications. As such, the recommendations are fairly generic – but you +should easily be able to apply them in either a Windows-based or Unix-based +development environment. If you are utilizing an Integrated Development +Environment (IDE) tool, you will need to adapt the advice given here to +the details of your particular environment.

    + +
    + +

    The following links provide access to selected sources of online +information, documentation, and software that is useful in developing +web applications with Tomcat.

    +
      +
    • https://jcp.org/aboutJava/communityprocess/mrel/jsr245/index2.html - + JavaServer Pages (JSP) Specification, Version 2.3. Describes + the programming environment provided by standard implementations + of the JavaServer Pages (JSP) technology. In conjunction with + the Servlet API Specification (see below), this document describes + what a portable API page is allowed to contain. Specific + information on scripting (Chapter 9), tag extensions (Chapter 7), + and packaging JSP pages (Appendix A) is useful. The Javadoc + API Documentation is included in the specification, and with the + Tomcat download.

    • +
    • http://jcp.org/aboutJava/communityprocess/final/jsr340/index.html - + Servlet API Specification, Version 3.1. Describes the + programming environment that must be provided by all servlet + containers conforming to this specification. In particular, you + will need this document to understand the web application + directory structure and deployment file (Chapter 10), methods of + mapping request URIs to servlets (Chapter 12), container managed + security (Chapter 13), and the syntax of the web.xml + Web Application Deployment Descriptor (Chapter 14). The Javadoc + API Documentation is included in the specification, and with the + Tomcat download.

    • +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/appdev/processes.html b/tomcat/docs/appdev/processes.html new file mode 100644 index 0000000..903e447 --- /dev/null +++ b/tomcat/docs/appdev/processes.html @@ -0,0 +1,315 @@ + +Application Developer's Guide (8.5.43) - Development Processes

    Development Processes

    Table of Contents

    Development Processes

    + +

    Although application development can take many forms, this manual proposes +a fairly generic process for creating web applications using Tomcat. The +following sections highlight the commands and tasks that you, as the developer +of the code, will perform. The same basic approach works when you have +multiple programmers involved, as long as you have an appropriate source code +control system and internal team rules about who is working on what parts +of the application at any given time.

    + +

    The task descriptions below assume that you will be using CVS for source +code control, and that you have already configured access to the appropriate +CVS repository. Instructions for doing this are beyond the scope of this +manual. If you are using a different source code control environment, you +will need to figure out the corresponding commands for your system.

    + + +

    One-Time Setup of Ant and Tomcat for Development

    + +

    In order to take advantage of the special Ant tasks that interact with the +Manager web application, you need to perform the following tasks +once (no matter how many web applications you plan to develop).

    +
      +
    • Configure the Ant custom tasks. The implementation code for the + Ant custom tasks is in a JAR file named + $CATALINA_HOME/lib/catalina-ant.jar, which must be + copied in to the lib directory of your Ant installation. +

    • +
    • Define one or more Tomcat users. The Manager web + application runs under a security constraint that requires a user to be + logged in, and have the security role manager-script assigned + to him or her. How such users are defined depends on which Realm you have + configured in Tomcat's conf/server.xml file -- see the + Realm Configuration How-To for more + information. You may define any number of users (with any username + and password that you like) with the manager-script role. +

    • +
    + +
    + + +

    Create Project Source Code Directory

    + +

    The first step is to create a new project source directory, and customize +the build.xml and build.properties files you will +be using. The directory structure is described in the +previous section, or you can use the +sample application as a starting point.

    + +

    Create your project source directory, and define it within your CVS +repository. This might be done by a series of commands like this, where +{project} is the name under which your project should be +stored in the CVS repository, and {username} is your login username:

    +
    cd {my home directory}
    +mkdir myapp <-- Assumed "project source directory"
    +cd myapp
    +mkdir docs
    +mkdir src
    +mkdir web
    +mkdir web/WEB-INF
    +cvs import -m "Initial Project Creation" {project} \
    +    {username} start
    + +

    Now, to verify that it was created correctly in CVS, we will perform a +checkout of the new project:

    +
    cd ..
    +mv myapp myapp.bu
    +cvs checkout {project}
    + +

    Next, you will need to create and check in an initial version of the +build.xml script to be used for development. For getting +started quickly and easily, base your build.xml on the +basic build.xml file, included with this manual, +or code it from scratch.

    +
    cd {my home directory}
    +cd myapp
    +emacs build.xml     <-- if you want a real editor :-)
    +cvs add build.xml
    +cvs commit
    + +

    Until you perform the CVS commit, your changes are local to your own +development directory. Committing makes those changes visible to other +developers on your team that are sharing the same CVS repository.

    + +

    The next step is to customize the Ant properties that are +named in the build.xml script. This is done by creating a +file named build.properties in your project's top-level +directory. The supported properties are listed in the comments inside +the sample build.xml script. At a minimum, you will generally +need to define the catalina.home property defining where +Tomcat is installed, and the manager application username and password. +You might end up with something like this:

    +
    # Context path to install this application on
    +app.path=/hello
    +
    +# Tomcat installation directory
    +catalina.home=/usr/local/apache-tomcat-<version-major-minor/>
    +
    +# Manager webapp username and password
    +manager.username=myusername
    +manager.password=mypassword
    + +

    In general, you will not want to check the +build.properties file in to the CVS repository, because it +is unique to each developer's environment.

    + +

    Now, create the initial version of the web application deployment +descriptor. You can base web.xml on the +basic web.xml file, or code it from scratch.

    +
    cd {my home directory}
    +cd myapp/web/WEB-INF
    +emacs web.xml
    +cvs add web.xml
    +cvs commit
    + +Note that this is only an example web.xml file. The full definition +of the deployment descriptor file is in the +Servlet Specification. + +
    + + +

    Edit Source Code and Pages

    + +

    The edit/build/test tasks will generally be your most common activities +during development and maintenance. The following general principles apply. +As described in Source Organization, newly created +source files should be located in the appropriate subdirectory, under your +project source directory.

    + +

    Whenever you wish to refresh your development directory to reflect the +work performed by other developers, you will ask CVS to do it for you:

    +
    cd {my home directory}
    +cd myapp
    +cvs update -dP
    + +

    To create a new file, go to the appropriate directory, create the file, +and register it with CVS. When you are satisfied with it's contents (after +building and testing is successful), commit the new file to the repository. +For example, to create a new JSP page:

    +
    cd {my home directory}
    +cd myapp/web        <-- Ultimate destination is document root
    +emacs mypage.jsp
    +cvs add mypage.jsp
    +... build and test the application ...
    +cvs commit
    + +

    Java source code that is defined in packages must be organized in a +directory hierarchy (under the src/ subdirectory) that +matches the package names. For example, a Java class named +com.mycompany.mypackage.MyClass.java should be stored in file +src/com/mycompany/mypackage/MyClass.java. +Whenever you create a new subdirectory, don't forget to +register it with CVS.

    + +

    To edit an existing source file, you will generally just start editing +and testing, then commit the changed file when everything works. Although +CVS can be configured to required you to "check out" or "lock" a file you +are going to be modifying, this is generally not used.

    + +
    + + +

    Build the Web Application

    + +

    When you are ready to compile the application, issue the following +commands (generally, you will want a shell window open that is set to +the project source directory, so that only the last command is needed):

    +
    cd {my home directory}
    +cd myapp        <-- Normally leave a window open here
    +ant
    + +

    The Ant tool will be execute the default "compile" target in your +build.xml file, which will compile any new or updated Java +code. If this is the first time you compile after a "build clean", +it will cause everything to be recompiled.

    + +

    To force the recompilation of your entire application, do this instead:

    +
    cd {my home directory}
    +cd myapp
    +ant all
    + +

    This is a very good habit immediately before checking in changes, to +make sure that you have not introduced any subtle problems that Javac's +conditional checking did not catch.

    + +
    + + +

    Test Your Web Application

    + +

    To test your application, you will want to install it under Tomcat. The +quickest way to do that is to use the custom Ant tasks that are included in +the sample build.xml script. Using these commands might follow +a pattern like this:

    +
      +
    • Start Tomcat if needed. If Tomcat is not already running, + you will need to start it in the usual way. +

    • +
    • Compile your application. Use the ant compile + command (or just ant, since this is the default). Make + sure that there are no compilation errors. +

    • +
    • Install the application. Use the ant install + command. This tells Tomcat to immediately start running your app on + the context path defined in the app.path build property. + Tomcat does NOT have to be restarted for this to + take effect. +

    • +
    • Test the application. Using your browser or other testing + tools, test the functionality of your application. +

    • +
    • Modify and rebuild as needed. As you discover that changes + are required, make those changes in the original source + files, not in the output build directory, and re-issue the + ant compile command. This ensures that your changes will + be available to be saved (via cvs commit) later on -- + the output build directory is deleted and recreated as necessary. +

    • +
    • Reload the application. Tomcat will recognize changes in + JSP pages automatically, but it will continue to use the old versions + of any servlet or JavaBean classes until the application is reloaded. + You can trigger this by executing the ant reload command. +

    • +
    • Remove the application when you are done. When you are through + working on this application, you can remove it from live execution by + running the ant remove command. +

    • +
    + +

    Do not forget to commit your changes to the source code repository when +you have completed your testing!

    + +
    + + +

    Creating a Release

    + +

    When you are through adding new functionality, and you've tested everything +(you DO test, don't you :-), it is time to create the distributable version +of your web application that can be deployed on the production server. The +following general steps are required:

    +
      +
    • Issue the command ant all from the project source + directory, to rebuild everything from scratch one last time. +

    • +
    • Use the cvs tag command to create an identifier for + all of the source files utilized to create this release. This allows + you to reliably reconstruct a release (from sources) at a later + time. +

    • +
    • Issue the command ant dist to create a distributable + web application archive (WAR) file, as well as a JAR file containing + the corresponding source code. +

    • +
    • Package the contents of the dist directory using the + tar or zip utility, according to + the standard release procedures used by your organization. +

    • +
    + +
    + + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/appdev/sample/build.xml b/tomcat/docs/appdev/sample/build.xml new file mode 100644 index 0000000..51d8350 --- /dev/null +++ b/tomcat/docs/appdev/sample/build.xml @@ -0,0 +1,508 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tomcat/docs/appdev/sample/docs/README.txt b/tomcat/docs/appdev/sample/docs/README.txt new file mode 100644 index 0000000..f146b0e --- /dev/null +++ b/tomcat/docs/appdev/sample/docs/README.txt @@ -0,0 +1,17 @@ + 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. + +This is a dummy README file for the sample +web application. diff --git a/tomcat/docs/appdev/sample/index.html b/tomcat/docs/appdev/sample/index.html new file mode 100644 index 0000000..589bd71 --- /dev/null +++ b/tomcat/docs/appdev/sample/index.html @@ -0,0 +1,55 @@ + + + + + + +Sample Application + + +

    Sample Application

    +

    + The example app has been packaged as a war file and can be downloaded + here (Note: make sure your browser doesn't + change file extension or append a new one). +

    +

    + The easiest way to run this application is simply to move the war file + to your CATALINA_BASE/webapps directory. A default Tomcat install + will automatically expand and deploy the application for you. You can + view it with the following URL (assuming that you're running tomcat on + port 8080 which is the default): +
    + http://localhost:8080/sample +

    +

    + If you just want to browse the contents, you can unpack the war file + with the jar command. +

    +
    +        jar -xvf sample.war
    +      
    +

    + Note: CATALINA_BASE is usually the directory in which you + unpacked the Tomcat distribution. For more information on + CATALINA_HOME, CATALINA_BASE and the difference between + them see RUNNING.txt in the directory you unpacked your Tomcat + distribution. +

    + + \ No newline at end of file diff --git a/tomcat/docs/appdev/sample/sample.war b/tomcat/docs/appdev/sample/sample.war new file mode 100644 index 0000000..0a127e6 Binary files /dev/null and b/tomcat/docs/appdev/sample/sample.war differ diff --git a/tomcat/docs/appdev/sample/src/mypackage/Hello.java b/tomcat/docs/appdev/sample/src/mypackage/Hello.java new file mode 100644 index 0000000..6984ffe --- /dev/null +++ b/tomcat/docs/appdev/sample/src/mypackage/Hello.java @@ -0,0 +1,83 @@ +/* + * 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. + */ +package mypackage; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + + +/** + * Simple servlet to validate that the Hello, World example can + * execute servlets. In the web application deployment descriptor, + * this servlet must be mapped to correspond to the link in the + * "index.html" file. + * + * @author Craig R. McClanahan + */ + +public final class Hello extends HttpServlet { + + private static final long serialVersionUID = 1L; + + /** + * Respond to a GET request for the content produced by + * this servlet. + * + * @param request The servlet request we are processing + * @param response The servlet response we are producing + * + * @exception IOException if an input/output error occurs + * @exception ServletException if a servlet error occurs + */ + @Override + public void doGet(HttpServletRequest request, + HttpServletResponse response) + throws IOException, ServletException { + + response.setContentType("text/html"); + response.setCharacterEncoding("UTF-8"); + try (PrintWriter writer = response.getWriter()) { + + writer.println(""); + writer.println(""); + writer.println(""); + writer.println("Sample Application Servlet Page"); + writer.println(""); + writer.println(""); + + + writer.println("
    "); + writer.println("\"\""); + writer.println("
    "); + writer.println("

    Sample Application Servlet

    "); + writer.println("

    "); + writer.println("This is the output of a servlet that is part of"); + writer.println("the Hello, World application."); + writer.println("

    "); + + writer.println(""); + writer.println(""); + } + } + + +} diff --git a/tomcat/docs/appdev/sample/web/WEB-INF/web.xml b/tomcat/docs/appdev/sample/web/WEB-INF/web.xml new file mode 100644 index 0000000..cbcba17 --- /dev/null +++ b/tomcat/docs/appdev/sample/web/WEB-INF/web.xml @@ -0,0 +1,40 @@ + + + + + Hello, World Application + + This is a simple web application with a source code organization + based on the recommendations of the Application Developer's Guide. + + + + HelloServlet + mypackage.Hello + + + + HelloServlet + /hello + + + diff --git a/tomcat/docs/appdev/sample/web/hello.jsp b/tomcat/docs/appdev/sample/web/hello.jsp new file mode 100644 index 0000000..bd5680a --- /dev/null +++ b/tomcat/docs/appdev/sample/web/hello.jsp @@ -0,0 +1,37 @@ +<%-- + 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. +--%> +<%@ page session="false" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %> + + + + +Sample Application JSP Page + + + +
    + +
    +

    Sample Application JSP Page

    +This is the output of a JSP page that is part of the Hello, World +application. + + +<%= new String("Hello!") %> + + + diff --git a/tomcat/docs/appdev/sample/web/images/tomcat.gif b/tomcat/docs/appdev/sample/web/images/tomcat.gif new file mode 100644 index 0000000..f2aa6f8 Binary files /dev/null and b/tomcat/docs/appdev/sample/web/images/tomcat.gif differ diff --git a/tomcat/docs/appdev/sample/web/index.html b/tomcat/docs/appdev/sample/web/index.html new file mode 100644 index 0000000..1c6938a --- /dev/null +++ b/tomcat/docs/appdev/sample/web/index.html @@ -0,0 +1,39 @@ + + + + +Sample "Hello, World" Application + + + +
    + +
    +

    Sample "Hello, World" Application

    +

    This is the home page for a sample application used to illustrate the +source directory organization of a web application utilizing the principles +outlined in the Application Developer's Guide. + +

    To prove that they work, you can execute either of the following links:

    + + + + diff --git a/tomcat/docs/appdev/source.html b/tomcat/docs/appdev/source.html new file mode 100644 index 0000000..97d80af --- /dev/null +++ b/tomcat/docs/appdev/source.html @@ -0,0 +1,321 @@ + +Application Developer's Guide (8.5.43) - Source Organization

    Source Organization

    Table of Contents

    Directory Structure

    + +

    The description below uses the variable name $CATALINA_BASE to refer the + base directory against which most relative paths are resolved. If you have + not configured Tomcat for multiple instances by setting a CATALINA_BASE + directory, then $CATALINA_BASE will be set to the value of $CATALINA_HOME, + the directory into which you have installed Tomcat.

    + +

    A key recommendation of this manual is to separate the directory +hierarchy containing your source code (described in this section) from +the directory hierarchy containing your deployable application +(described in the preceding section). Maintaining this separation has +the following advantages:

    +
      +
    • The contents of the source directories can be more easily administered, + moved, and backed up if the "executable" version of the application + is not intermixed. +

    • +
    • Source code control is easier to manage on directories that contain + only source files. +

    • +
    • The files that make up an installable distribution of your + application are much easier to select when the deployment + hierarchy is separate.

    • +
    + +

    As we will see, the ant development tool makes the creation +and processing of such directory hierarchies nearly painless.

    + +

    The actual directory and file hierarchy used to contain the source code +of an application can be pretty much anything you like. However, the +following organization has proven to be quite generally applicable, and is +expected by the example build.xml configuration file that +is discussed below. All of these components exist under a top level +project source directory for your application:

    +
      +
    • docs/ - Documentation for your application, in whatever + format your development team is using.

    • +
    • src/ - Java source files that generate the servlets, + beans, and other Java classes that are unique to your application. + If your source code is organized in packages (highly + recommended), the package hierarchy should be reflected as a directory + structure underneath this directory.

    • +
    • web/ - The static content of your web site (HTML pages, + JSP pages, JavaScript files, CSS stylesheet files, and images) that will + be accessible to application clients. This directory will be the + document root of your web application, and any subdirectory + structure found here will be reflected in the request URIs required to + access those files.

    • +
    • web/WEB-INF/ - The special configuration files required + for your application, including the web application deployment descriptor + (web.xml, defined in the + Servlet Specification), + tag library descriptors for custom tag libraries + you have created, and other resource files you wish to include within + your web application. Even though this directory appears to be a + subdirectory of your document root, the Servlet Specification + prohibits serving the contents of this directory (or any file it contains) + directly to a client request. Therefore, this is a good place to store + configuration information that is sensitive (such as database connection + usernames and passwords), but is required for your application to + operate successfully.
    • +
    + +

    During the development process, two additional directories will be +created on a temporary basis:

    +
      +
    • build/ - When you execute a default build + (ant), this directory will contain an exact image + of the files in the web application archive for this application. + Tomcat allows you to deploy an application in an unpacked + directory like this, either by copying it to the + $CATALINA_BASE/webapps directory, or by installing + it via the "Manager" web application. The latter approach is very + useful during development, and will be illustrated below. +

    • +
    • dist/ - When you execute the ant dist + target, this directory will be created. It will create an exact image + of the binary distribution for your web application, including an license + information, documentation, and README files that you have prepared.
    • +
    + +

    Note that these two directories should NOT be archived in +your source code control system, because they are deleted and recreated (from +scratch) as needed during development. For that reason, you should not edit +any source files in these directories if you want to maintain a permanent +record of the changes, because the changes will be lost the next time that a +build is performed.

    + +

    External Dependencies

    + +

    What do you do if your application requires JAR files (or other + resources) from external projects or packages? A common example is that + you need to include a JDBC driver in your web application, in order to + operate.

    + +

    Different developers take different approaches to this problem. + Some will encourage checking a copy of the JAR files you depend on into + the source code control archives for every application that requires those + JAR files. However, this can cause significant management issues when you + use the same JAR in many applications - particular when faced with a need + to upgrade to a different version of that JAR file.

    + +

    Therefore, this manual recommends that you NOT store + a copy of the packages you depend on inside the source control archives + of your applications. Instead, the external dependencies should be + integrated as part of the process of building your + application. In that way, you can always pick up the appropriate version + of the JAR files from wherever your development system administrator has + installed them, without having to worry about updating your application + every time the version of the dependent JAR file is changed.

    + +

    In the example Ant build.xml file, we will demonstrate + how to define build properties that let you configure the locations + of the files to be copied, without having to modify build.xml + when these files change. The build properties used by a particular + developer can be customized on a per-application basis, or defaulted to + "standard" build properties stored in the developer's home directory.

    + +

    In many cases, your development system administrator will have already + installed the required JAR files into the lib directory of Tomcat. + If this has been done, you need + to take no actions at all - the example build.xml file + automatically constructs a compile classpath that includes these files.

    + +
    + +

    Source Code Control

    + +

    As mentioned earlier, it is highly recommended that you place all of the +source files that comprise your application under the management of a +source code control system like the Concurrent Version System (CVS). If you +elect to do this, every directory and file in the source hierarchy should be +registered and saved -- but none of the generated files. If you register +binary format files (such as images or JAR libraries), be sure to indicate +this to your source code control system.

    + +

    We recommended (in the previous section) that you should not store the +contents of the build/ and dist/ directories +created by your development process in the source code control system. An +easy way to tell CVS to ignore these directories is to create a file named +.cvsignore (note the leading period) in your top-level source +directory, with the following contents:

    +
    build
    +dist
    +build.properties
    + +

    The reason for mentioning build.properties here will be +explained in the Processes section.

    + +

    Detailed instructions for your source code control environment are beyond +the scope of this manual. However, the following steps are followed when +using a command-line CVS client:

    +
      +
    • To refresh the state of your source code to that stored in the + the source repository, go to your project source directory, and + execute cvs update -dP. +

    • +
    • When you create a new subdirectory in the source code hierarchy, register + it in CVS with a command like cvs add {subdirname}. +

    • +
    • When you first create a new source code file, navigate to the directory + that contains it, and register the new file with a command like + cvs add {filename}. +

    • +
    • If you no longer need a particular source code file, navigate to the + containing directory and remove the file. Then, deregister it in CVS + with a command like cvs remove {filename}. +

    • +
    • While you are creating, modifying, and deleting source files, changes + are not yet reflected in the server repository. To save your changes in + their current state, go to the project source directory + and execute cvs commit. You will be asked to write a brief + description of the changes you have just completed, which will be stored + with the new version of any updated source file.
    • +
    + +

    CVS, like other source code control systems, has many additional features +(such as the ability to tag the files that made up a particular release, and +support for multiple development branches that can later be merged). See the +links and references in the Introduction for +more information.

    + +

    BUILD.XML Configuration File

    + +

    We will be using the ant tool to manage the compilation of +our Java source code files, and creation of the deployment hierarchy. Ant +operates under the control of a build file, normally called +build.xml, that defines the processing steps required. This +file is stored in the top-level directory of your source code hierarchy, and +should be checked in to your source code control system.

    + +

    Like a Makefile, the build.xml file provides several +"targets" that support optional development activities (such as creating +the associated Javadoc documentation, erasing the deployment home directory +so you can build your project from scratch, or creating the web application +archive file so you can distribute your application. A well-constructed +build.xml file will contain internal documentation describing +the targets that are designed for use by the developer, versus those targets +used internally. To ask Ant to display the project documentation, change to +the directory containing the build.xml file and type:

    +
    ant -projecthelp
    + +

    To give you a head start, a basic build.xml file +is provided that you can customize and install in the project source directory +for your application. This file includes comments that describe the various +targets that can be executed. Briefly, the following targets are generally +provided:

    +
      +
    • clean - This target deletes any existing + build and dist directories, so that they + can be reconstructed from scratch. This allows you to guarantee that + you have not made source code modifications that will result in + problems at runtime due to not recompiling all affected classes. +

    • +
    • compile - This target is used to compile any source code + that has been changed since the last time compilation took place. The + resulting class files are created in the WEB-INF/classes + subdirectory of your build directory, exactly where the + structure of a web application requires them to be. Because + this command is executed so often during development, it is normally + made the "default" target so that a simple ant command will + execute it. +

    • +
    • all - This target is a short cut for running the + clean target, followed by the compile target. + Thus, it guarantees that you will recompile the entire application, to + ensure that you have not unknowingly introduced any incompatible changes. +

    • +
    • javadoc - This target creates Javadoc API documentation + for the Java classes in this web application. The example + build.xml file assumes you want to include the API + documentation with your app distribution, so it generates the docs + in a subdirectory of the dist directory. Because you normally + do not need to generate the Javadocs on every compilation, this target is + usually a dependency of the dist target, but not of the + compile target. +

    • +
    • dist - This target creates a distribution directory for + your application, including any required documentation, the Javadocs for + your Java classes, and a web application archive (WAR) file that will be + delivered to system administrators who wish to install your application. + Because this target also depends on the deploy target, the + web application archive will have also picked up any external dependencies + that were included at deployment time.
    • +
    + +

    For interactive development and testing of your web application using +Tomcat, the following additional targets are defined:

    +
      +
    • install - Tell the currently running Tomcat to make + the application you are developing immediately available for execution + and testing. This action does not require Tomcat to be restarted, but + it is also not remembered after Tomcat is restarted the next time. +

    • +
    • reload - Once the application is installed, you can + continue to make changes and recompile using the compile + target. Tomcat will automatically recognize changes made to JSP pages, + but not to servlet or JavaBean classes - this command will tell Tomcat + to restart the currently installed application so that such changes are + recognized. +

    • +
    • remove - When you have completed your development and + testing activities, you can optionally tell Tomcat to remove this + application from service. +
    • +
    + +

    Using the development and testing targets requires some additional +one-time setup that is described on the next page.

    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/appdev/web.xml.txt b/tomcat/docs/appdev/web.xml.txt new file mode 100644 index 0000000..b560a73 --- /dev/null +++ b/tomcat/docs/appdev/web.xml.txt @@ -0,0 +1,166 @@ + + + + + + + + + + + My Web Application + + This is version X.X of an application to perform + a wild and wonderful task, based on servlets and + JSP pages. It was written by Dave Developer + (dave@mycompany.com), who should be contacted for + more information. + + + + + + + webmaster + myaddress@mycompany.com + + The EMAIL address of the administrator to whom questions + and comments about this application should be addressed. + + + + + + + + controller + + This servlet plays the "controller" role in the MVC architecture + used in this application. It is generally mapped to the ".do" + filename extension with a servlet-mapping element, and all form + submits in the app will be submitted to a request URI like + "saveCustomer.do", which will therefore be mapped to this servlet. + + The initialization parameter names for this servlet are the + "servlet path" that will be received by this servlet (after the + filename extension is removed). The corresponding value is the + name of the action class that will be used to process this request. + + com.mycompany.mypackage.ControllerServlet + + listOrders + com.mycompany.myactions.ListOrdersAction + + + saveCustomer + com.mycompany.myactions.SaveCustomerAction + + + 5 + + + + graph + + This servlet produces GIF images that are dynamically generated + graphs, based on the input parameters included on the request. + It is generally mapped to a specific request URI like "/graph". + + + + + + + + controller + *.do + + + + graph + /graph + + + + + + + 30 + + + + diff --git a/tomcat/docs/apr.html b/tomcat/docs/apr.html new file mode 100644 index 0000000..b2c0510 --- /dev/null +++ b/tomcat/docs/apr.html @@ -0,0 +1,173 @@ + +Apache Tomcat 8 (8.5.43) - Apache Portable Runtime (APR) based Native library for Tomcat

    Apache Portable Runtime (APR) based Native library for Tomcat

    Table of Contents

    Introduction

    + +

    + Tomcat can use the Apache Portable Runtime to + provide superior scalability, performance, and better integration with native server + technologies. The Apache Portable Runtime is a highly portable library that is at + the heart of Apache HTTP Server 2.x. APR has many uses, including access to advanced IO + functionality (such as sendfile, epoll and OpenSSL), OS level functionality (random number + generation, system status, etc), and native process handling (shared memory, NT + pipes and Unix sockets). +

    + +

    + These features allows making Tomcat a general purpose webserver, will enable much better + integration with other native web technologies, and overall make Java much more viable as + a full fledged webserver platform rather than simply a backend focused technology. +

    + +

    Installation

    + +

    + APR support requires three main native components to be installed: +

    +
      +
    • APR library
    • +
    • JNI wrappers for APR used by Tomcat (libtcnative)
    • +
    • OpenSSL libraries
    • +
    + +

    Windows

    + +

    + Windows binaries are provided for tcnative-1, which is a statically compiled .dll which includes + OpenSSL and APR. It can be downloaded from here + as 32bit or AMD x86-64 binaries. + In security conscious production environments, it is recommended to use separate shared dlls + for OpenSSL, APR, and libtcnative-1, and update them as needed according to security bulletins. + Windows OpenSSL binaries are linked from the Official OpenSSL + website (see related/binaries). +

    + +
    + +

    Linux

    + +

    + Most Linux distributions will ship packages for APR and OpenSSL. The JNI wrapper (libtcnative) will + then have to be compiled. It depends on APR, OpenSSL, and the Java headers. +

    + +

    + Requirements: +

    +
      +
    • APR 1.2+ development headers (libapr1-dev package)
    • +
    • OpenSSL 1.0.2+ development headers (libssl-dev package)
    • +
    • JNI headers from Java compatible JDK 1.4+
    • +
    • GNU development environment (gcc, make)
    • +
    + +

    + The wrapper library sources are located in the Tomcat binary bundle, in the + bin/tomcat-native.tar.gz archive. + Once the build environment is installed and the source archive is extracted, the wrapper library + can be compiled using (from the folder containing the configure script): +

    +
    ./configure && make && make install
    + +
    + +

    APR Components

    + +

    + Once the libraries are properly installed and available to Java (if loading fails, the library path + will be displayed), the Tomcat connectors will automatically use APR. Configuration of the connectors + is similar to the regular connectors, but have a few extra attributes which are used to configure + APR components. Note that the defaults should be well tuned for most use cases, and additional + tweaking shouldn't be required. +

    + +

    + When APR is enabled, the following features are also enabled in Tomcat: +

    +
      +
    • Secure session ID generation by default on all platforms (platforms other than Linux required + random number generation using a configured entropy)
    • +
    • OS level statistics on memory usage and CPU usage by the Tomcat process are displayed by + the status servlet
    • +
    + +

    APR Lifecycle Listener Configuration

    APR Connectors Configuration

    + +

    HTTP/HTTPS

    + +

    For HTTP configuration, see the HTTP + connector configuration documentation.

    + +

    For HTTPS configuration, see the + HTTPS connector configuration + documentation.

    + +

    An example SSL Connector declaration is:

    +
    <Connector port="443" maxHttpHeaderSize="8192"
    +                 maxThreads="150"
    +                 enableLookups="false" disableUploadTimeout="true"
    +                 acceptCount="100" scheme="https" secure="true"
    +                 SSLEnabled="true"
    +                 SSLCertificateFile="${catalina.base}/conf/localhost.crt"
    +                 SSLCertificateKeyFile="${catalina.base}/conf/localhost.key" />
    + + +
    + +

    AJP

    + +

    For AJP configuration, see the AJP + connector configuration documentation.

    + +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/architecture/index.html b/tomcat/docs/architecture/index.html new file mode 100644 index 0000000..d2df7da --- /dev/null +++ b/tomcat/docs/architecture/index.html @@ -0,0 +1,77 @@ + +Apache Tomcat 8 Architecture (8.5.43) - Table of Contents

    Table of Contents

    Preface

    + +

    This section of the Tomcat documentation attempts to explain +the architecture and design of the Tomcat server. It includes significant +contributions from several tomcat developers: +

    + + +

    Table of Contents

    + +

    The information presented is divided into the following sections:

    +
      +
    • Overview - + An overview of the Tomcat server architecture with key terms + and concepts.
    • +
    • Server Startup - + A detailed description, with sequence diagrams, of how the Tomcat + server starts up.
    • +
    • Request Process Flow - + A detailed description of how Tomcat handles a request.
    • +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/architecture/overview.html b/tomcat/docs/architecture/overview.html new file mode 100644 index 0000000..ed4da5b --- /dev/null +++ b/tomcat/docs/architecture/overview.html @@ -0,0 +1,146 @@ + +Apache Tomcat 8 Architecture (8.5.43) - Architecture Overview

    Architecture Overview

    Overview

    +

    +This page provides an overview of the Tomcat server architecture. +

    +

    Terms

    + +

    Server

    +

    +In the Tomcat world, a +Server represents the whole container. +Tomcat provides a default implementation of the +Server interface +which is rarely customized by users. +

    +
    + +

    Service

    +

    +A Service is an intermediate component +which lives inside a Server and ties one or more Connectors to exactly one +Engine. The Service element is rarely customized by users, as the default +implementation is simple and sufficient: +Service interface. +

    +
    + +

    Engine

    +

    +An +Engine represents request processing +pipeline for a specific Service. As a Service may have multiple Connectors, +the Engine receives and processes all requests from these connectors, handing +the response back to the appropriate connector for transmission to the client. +The Engine interface +may be implemented to supply custom Engines, though this is uncommon. +

    +

    +Note that the Engine may be used for Tomcat server clustering via the +jvmRoute parameter. Read the Clustering documentation for more information. +

    +
    + +

    Host

    +

    +A Host is an association of a network name, +e.g. www.yourcompany.com, to the Tomcat server. An Engine may contain +multiple hosts, and the Host element also supports network aliases such as +yourcompany.com and abc.yourcompany.com. Users rarely create custom +Hosts +because the +StandardHost +implementation provides significant additional functionality. +

    +
    + +

    Connector

    +

    +A Connector handles communications with the client. There are multiple +connectors available with Tomcat. These include the +HTTP connector which is used for +most HTTP traffic, especially when running Tomcat as a standalone server, +and the AJP connector which implements +the AJP protocol used when connecting Tomcat to a web server such as +Apache HTTPD server. Creating a customized connector is a significant +effort. +

    +
    + +

    Context

    +

    +A +Context +represents a web application. A Host may contain multiple +contexts, each with a unique path. The +Context +interface may be implemented to create custom Contexts, but +this is rarely the case because the + +StandardContext provides significant additional functionality. +

    +
    +

    Comments

    +

    +Tomcat is designed to be a fast and efficient implementation of the +Servlet Specification. Tomcat came about as the reference implementation +of this specification, and has remained rigorous in adhering to the +specification. At the same time, significant attention has been paid +to Tomcat's performance and it is now on par with other servlet containers, +including commercial ones. +

    +

    +In recent releases of Tomcat, mostly starting with Tomcat 5, +we have begun efforts to make more aspects of Tomcat manageable via +JMX. In addition, the Manager and Admin webapps have been greatly +enhanced and improved. Manageability is a primary area of concern +for us as the product matures and the specification becomes more +stable. +

    +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/architecture/requestProcess.html b/tomcat/docs/architecture/requestProcess.html new file mode 100644 index 0000000..049efb3 --- /dev/null +++ b/tomcat/docs/architecture/requestProcess.html @@ -0,0 +1,85 @@ + +Apache Tomcat 8 Architecture (8.5.43) - Request Process Flow

    Request Process Flow

    Request Process Flow

    + +

    +This page describes the process used by Tomcat to handle +an incoming request. This process is largely defined by +the Servlet Specification, which outlines the order +of events that must take place. +

    + +

    description

    +

    +TODO +

    +
    + +

    diagrams

    +

    +A UML sequence diagram of the request process is available +here. +

    +

    +A UML sequence diagram of the authentication process is available +here. +

    + +
    + +

    comments

    +

    +The Servlet Specification provides many opportunities for +listening in (using Listeners) or modifying (using Filters) +the request handling process even before the request arrives +at the servlet that will handle it. +

    + +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/architecture/requestProcess/authentication-process.png b/tomcat/docs/architecture/requestProcess/authentication-process.png new file mode 100644 index 0000000..e23c333 Binary files /dev/null and b/tomcat/docs/architecture/requestProcess/authentication-process.png differ diff --git a/tomcat/docs/architecture/requestProcess/request-process.png b/tomcat/docs/architecture/requestProcess/request-process.png new file mode 100644 index 0000000..33ae3c3 Binary files /dev/null and b/tomcat/docs/architecture/requestProcess/request-process.png differ diff --git a/tomcat/docs/architecture/startup.html b/tomcat/docs/architecture/startup.html new file mode 100644 index 0000000..2caa403 --- /dev/null +++ b/tomcat/docs/architecture/startup.html @@ -0,0 +1,84 @@ + +Apache Tomcat 8 Architecture (8.5.43) - Startup

    Startup

    Server Startup

    + +

    +This page describes how the Tomcat server starts up. There are several +different ways to start tomcat, including: +

    +
      +
    • From the command line.
    • +
    • From a Java program as an embedded server.
    • +
    • Automatically as a Windows service.
    • +
    + +

    description

    +

    +A text description of the startup procedure is available +here. +

    +
    + +

    diagram

    +

    +A UML sequence diagram of the startup procedure is available +here. +

    +
    + +

    comments

    +

    +The startup process can be customized in many ways, both +by modifying Tomcat code and by implementing your own +LifecycleListeners which are then registered in the server.xml +configuration file. +

    + +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/architecture/startup/serverStartup.pdf b/tomcat/docs/architecture/startup/serverStartup.pdf new file mode 100644 index 0000000..34aa598 Binary files /dev/null and b/tomcat/docs/architecture/startup/serverStartup.pdf differ diff --git a/tomcat/docs/architecture/startup/serverStartup.txt b/tomcat/docs/architecture/startup/serverStartup.txt new file mode 100644 index 0000000..716c8d0 --- /dev/null +++ b/tomcat/docs/architecture/startup/serverStartup.txt @@ -0,0 +1,139 @@ + 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. + +Tomcat Startup Sequence + +Sequence 1. Start from Command Line +Class: org.apache.catalina.startup.Bootstrap +What it does: + a) Set up classloaders + commonLoader (common)-> System Loader + sharedLoader (shared)-> commonLoader -> System Loader + catalinaLoader(server) -> commonLoader -> System Loader + (by default the commonLoader is used for the + sharedLoader and the serverLoader) + b) Load startup class (reflection) + org.apache.catalina.startup.Catalina + setParentClassloader -> sharedLoader + Thread.contextClassloader -> catalinaLoader + c) Bootstrap.daemon.init() complete + +Sequence 2. Process command line argument (start, stop) +Class: org.apache.catalina.startup.Bootstrap (assume command->start) +What it does: + a) Catalina.setAwait(true); + b) Catalina.load() + b1) initDirs() -> set properties like + catalina.home + catalina.base == catalina.home (most cases) + b2) initNaming + setProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY, + org.apache.naming.java.javaURLContextFactory ->default) + b3) createStartDigester() + Configures a digester for the main server.xml elements like + org.apache.catalina.core.StandardServer (can change of course :) + org.apache.catalina.deploy.NamingResources + Stores naming resources in the J2EE JNDI tree + org.apache.catalina.LifecycleListener + implements events for start/stop of major components + org.apache.catalina.core.StandardService + The single entry for a set of connectors, + so that a container can listen to multiple connectors + ie, single entry + org.apache.catalina.Connector + Connectors to listen for incoming requests only + It also adds the following rulesets to the digester + NamingRuleSet + EngineRuleSet + HostRuleSet + ContextRuleSet + b4) Load the server.xml and parse it using the digester + Parsing the server.xml using the digester is an automatic + XML-object mapping tool, that will create the objects defined in server.xml + Startup of the actual container has not started yet. + b5) Assigns System.out and System.err to the SystemLogHandler class + b6) Calls initialize on all components, this makes each object register itself with the + JMX agent. + During the process call the Connectors also initialize the adapters. + The adapters are the components that do the request pre-processing. + Typical adapters are HTTP1.1 (default if no protocol is specified, + org.apache.coyote.http11.Http11NioProtocol) + AJP1.3 for mod_jk etc. + + c) Catalina.start() + c1) Starts the NamingContext and binds all JNDI references into it + c2) Starts the services under which are: + StandardService -> starts Engine (ContainerBase -> Realm,Cluster etc) + c3) StandardHost (started by the service) + Configures a ErrorReportValvem to do proper HTML output for different HTTP + errors codes + Starts the Valves in the pipeline (at least the ErrorReportValve) + Configures the StandardHostValve, + this valves ties the Webapp Class loader to the thread context + it also finds the session for the request + and invokes the context pipeline + Starts the HostConfig component + This component deploys all the webapps + (webapps & conf/Catalina/localhost/*.xml) + HostConfig will create a Digester for your context, this digester + will then invoke ContextConfig.start() + The ContextConfig.start() will process the default web.xml (conf/web.xml) + and then process the applications web.xml (WEB-INF/web.xml) + + c4) During the lifetime of the container (StandardEngine) there is a background thread that + keeps checking if the context has changed. If a context changes (timestamp of war file, + context xml file, web.xml) then a reload is issued (stop/remove/deploy/start) + + d) Tomcat receives a request on an HTTP port + d1) The request is received by a separate thread which is waiting in the ThreadPoolExecutor + class. It is waiting for a request in a regular ServerSocket.accept() method. + When a request is received, this thread wakes up. + d2) The ThreadPoolExecutor assigns the a TaskThread to handle the request. + It also supplies a JMX object name to the catalina container (not used I believe) + d3) The processor to handle the request in this case is Coyote Http11Processor, + and the process method is invoked. + This same processor is also continuing to check the input stream of the socket + until the keep alive point is reached or the connection is disconnected. + d4) The HTTP request is parsed using an internal buffer class (Http11InputBuffer) + The buffer class parses the request line, the headers, etc and store the result in a + Coyote request (not an HTTP request) This request contains all the HTTP info, such + as servername, port, scheme, etc. + d5) The processor contains a reference to an Adapter, in this case it is the + CoyoteAdapter. Once the request has been parsed, the Http11Processor + invokes service() on the adapter. In the service method, the Request contains a + CoyoteRequest and CoyoteResponse (null for the first time) + The CoyoteRequest(Response) implements HttpRequest(Response) and HttpServletRequest(Response) + The adapter parses and associates everything with the request, cookies, the context through a + Mapper, etc + d6) When the parsing is finished, the CoyoteAdapter invokes its container (StandardEngine) + and invokes the invoke(request,response) method. + This initiates the HTTP request into the Catalina container starting at the engine level + d7) The StandardEngine.invoke() simply invokes the container pipeline.invoke() + d8) By default the engine only has one valve the StandardEngineValve, this valve simply + invokes the invoke() method on the Host pipeline (StandardHost.getPipeLine()) + d9) the StandardHost has two valves by default, the StandardHostValve and the ErrorReportValve + d10) The standard host valve associates the correct class loader with the current thread + It also retrieves the Manager and the session associated with the request (if there is one) + If there is a session access() is called to keep the session alive + d11) After that the StandardHostValve invokes the pipeline on the context associated + with the request. + d12) The first valve that gets invoked by the Context pipeline is the FormAuthenticator + valve. Then the StandardContextValve gets invoke. + The StandardContextValve invokes any context listeners associated with the context. + Next it invokes the pipeline on the Wrapper component (StandardWrapperValve) + d13) During the invocation of the StandardWrapperValve, the JSP wrapper (Jasper) gets invoked + This results in the actual compilation of the JSP. + And then invokes the actual servlet. + e) Invocation of the servlet class diff --git a/tomcat/docs/balancer-howto.html b/tomcat/docs/balancer-howto.html new file mode 100644 index 0000000..645af48 --- /dev/null +++ b/tomcat/docs/balancer-howto.html @@ -0,0 +1,61 @@ + +Apache Tomcat 8 (8.5.43) - Load Balancer How-To

    Load Balancer How-To

    Table of Contents

    Using the JK 1.2.x native connector

    + +Please refer to the JK 1.2.x documentation. + +

    Using Apache HTTP Server 2.x with mod_proxy

    + +Please refer to the mod_proxy documentation for Apache HTTP Server 2.2. This supports either +HTTP or AJP load balancing. This new version of mod_proxy is also usable with +Apache HTTP Server 2.0, but mod_proxy will have to be compiled separately using the code +from Apache HTTP Server 2.2. + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/building.html b/tomcat/docs/building.html new file mode 100644 index 0000000..4d95099 --- /dev/null +++ b/tomcat/docs/building.html @@ -0,0 +1,278 @@ + +Apache Tomcat 8 (8.5.43) - Building Tomcat

    Building Tomcat

    Table of Contents

    Introduction

    + +

    +Building Apache Tomcat from source is very easy, and is the first step to +contributing to Tomcat. The complete and comprehensive instructions are +provided in the file BUILDING.txt. +The following is a quick step by step guide. +

    + +

    Download a Java Development Kit (JDK) version 7

    + +

    +Building Apache Tomcat requires a JDK (version 7) to be installed. You can download one from
    +http://www.oracle.com/technetwork/java/javase/downloads/index.html
    +http://openjdk.java.net/install/index.html
    +or another JDK vendor. +

    + +

    +IMPORTANT: Set an environment variable JAVA_HOME to the pathname of the +directory into which you installed the JDK release. +

    + +

    Install Apache Ant 1.9.8 or later

    + +

    +Download a binary distribution of Ant 1.9.8 or later from +here. +

    + +

    +Unpack the binary distribution into a convenient location so that the +Ant release resides in its own directory (conventionally named +apache-ant-1.9.x). For the remainder of this guide, +the symbolic name ${ant.home} is used to refer to the full pathname of + the Ant installation directory. +

    + +

    +IMPORTANT: Create an ANT_HOME environment variable to point the directory ${ant.home}, +and modify the PATH environment variable to include directory +${ant.home}/bin in its list. This makes the ant command line script +available, which will be used to actually perform the build. +

    + +

    Checkout or obtain the Tomcat source code

    + +

    + Tomcat SVN repository URL: + https://svn.apache.org/repos/asf/tomcat/tc8.5.x/trunk/ +

    +

    + Tomcat source packages: + https://tomcat.apache.org/download-80.cgi. +

    + +

    + Checkout the source using SVN, selecting a tag for released version or + trunk for the current development code, or download and unpack a + source package. For the remainder of this guide, the symbolic name + ${tomcat.source} is used to refer to the + location where the source has been placed. +

    + +

    Configure download area

    + +

    + Building Tomcat involves downloading a number of libraries that it depends on. + It is strongly recommended to configure download area for those libraries. +

    + +

    + By default the build is configured to download the dependencies into the + ${user.home}/tomcat-build-libs directory. You can change this + (see below) but it must be an absolute path. +

    + +

    + The build is controlled by creating a + ${tomcat.source}/build.properties file. It can be used to + redefine any property that is present in build.properties.default + and build.xml files. The build.properties file + does not exist by default. You have to create it. +

    + +

    + The download area is defined by property base.path. For example: +

    + +
    # ----- Default Base Path for Dependent Packages -----
    +# Replace this path with the directory path where
    +# dependencies binaries should be downloaded.
    +base.path=/home/me/some-place-to-download-to
    + +

    + Different versions of Tomcat are allowed to share the same download area. +

    + +

    + Another example: +

    + +
    base.path=${user.dir}/../libraries-tomcat8.5
    + +

    + Users who access the Internet through a proxy must use the properties + file to indicate to Ant the proxy configuration: +

    + +
    # ----- Proxy setup -----
    +proxy.host=proxy.domain
    +proxy.port=8080
    +proxy.use=on
    + +

    Building Tomcat

    + +

    +Use the following commands to build Tomcat: +

    + +

    +cd ${tomcat.source}
    +ant +

    + +

    +Once the build has completed successfully, a usable Tomcat installation will have been +produced in the ${tomcat.source}/output/build directory, and can be started +and stopped with the usual scripts. +

    +

    Building with Eclipse

    + +

    +IMPORTANT: This is not a supported means of building Tomcat; this information is +provided without warranty :-). +The only supported means of building Tomcat is with the Ant build described above. +However, some developers like to work on Java code with a Java IDE, +and the following steps have been used by some developers. +

    + +

    +NOTE: This will not let you build everything under Eclipse; +the build process requires use of Ant for the many stages that aren't +simple Java compilations. +However, it will allow you to view and edit the Java code, +get warnings, reformat code, perform refactorings, run Tomcat +under the IDE, and so on. +

    + +

    +WARNING: Do not forget to create and configure + ${tomcat.source}/build.properties file as described above + before running any Ant targets. +

    + +

    +Sample Eclipse project files and launch targets are provided in the +res/ide-support/eclipse directory of the source tree. +The instructions below will automatically copy these into the required locations. +

    +

    +An Ant target is provided as a convenience to download all binary dependencies, and to create +the Eclipse project and classpath files in the root of the source tree. +

    + +

    +cd ${tomcat.source}
    +ant ide-eclipse +

    + +

    +Start Eclipse and create a new Workspace. +

    + +

    +Open the Preferences dialog and then select Java->Build Path->Classpath +Variables to add two new Classpath Variables: +

    + + +
    书名 Isbn印刷日期作者出版社教材类别单价备注
    + + +
    TOMCAT_LIBS_BASEThe same location as the base.path + setting in build.properties, where the binary dependencies have been downloaded
    ANT_HOMEthe base path of Ant 1.9.8 or later
    + + +

    +Use File->Import and choose Existing Projects into Workspace. +From there choose the root directory of the Tomcat source tree (${tomcat.source}) +and import the Tomcat project located there. +

    + +

    +start-tomcat and stop-tomcat launch configurations are provided in +res/ide-support/eclipse and will be available in the Run->Run Configurations +dialog. Use these to start and stop Tomcat from Eclipse. +If you want to configure these yourself (or are using a different IDE) +then use org.apache.catalina.startup.Bootstrap as the main class, +start/stop etc. as program arguments, and specify -Dcatalina.home=... +(with the name of your build directory) as VM arguments. +

    + +

    +Tweaking a few formatting preferences will make it much easier to keep consistent with Tomcat +coding conventions (and have your contributions accepted): +

    + + + + + + + + +
    Java -> Code Style -> Formatter -> Edit...Tab policy: Spaces only
    Tab and Indentation size: 4
    General -> Editors -> Text EditorsDisplayed tab width: 2
    Insert spaces for tabs
    Show whitespace characters (optional)
    XML -> XML Files -> EditorIndent using spaces
    Indentation size: 2
    Ant -> Editor -> FormatterTab size: 2
    Use tab character instead of spaces: unchecked
    + +

    +The recommended configuration of Compiler Warnings is documented in +res/ide-support/eclipse/java-compiler-errors-warnings.txt file. +

    + +

    Building with other IDEs

    +

    +The same general approach should work for most IDEs; it has been reported +to work in IntelliJ IDEA, for example. +

    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/cgi-howto.html b/tomcat/docs/cgi-howto.html new file mode 100644 index 0000000..001574c --- /dev/null +++ b/tomcat/docs/cgi-howto.html @@ -0,0 +1,175 @@ + +Apache Tomcat 8 (8.5.43) - CGI How To

    CGI How To

    Table of Contents

    Introduction

    + +

    The CGI (Common Gateway Interface) defines a way for a web server to +interact with external content-generating programs, which are often +referred to as CGI programs or CGI scripts. +

    + +

    Within Tomcat, CGI support can be added when you are using Tomcat as your +HTTP server and require CGI support. Typically this is done +during development when you don't want to run a web server like +Apache httpd. +Tomcat's CGI support is largely compatible with Apache httpd's, +but there are some limitations (e.g., only one cgi-bin directory). +

    + +

    CGI support is implemented using the servlet class +org.apache.catalina.servlets.CGIServlet. Traditionally, +this servlet is mapped to the URL pattern "/cgi-bin/*".

    + +

    By default CGI support is disabled in Tomcat.

    +

    Installation

    + +

    CAUTION - CGI scripts are used to execute programs +external to the Tomcat JVM. If you are using the Java SecurityManager this +will bypass your security policy configuration in catalina.policy.

    + +

    To enable CGI support:

    + +
      +
    1. There are commented-out sample servlet and servlet-mapping elements for +CGI servlet in the default $CATALINA_BASE/conf/web.xml file. +To enable CGI support in your web application, copy that servlet and +servlet-mapping declarations into WEB-INF/web.xml file of your +web application.

      + +

      Uncommenting the servlet and servlet-mapping in +$CATALINA_BASE/conf/web.xml file enables CGI for all installed +web applications at once.

      +
    2. + +
    3. Set privileged="true" on the Context element for your +web application.

      + +

      Only Contexts which are marked as privileged are allowed to use the +CGI servlet. Note that modifying the global $CATALINA_BASE/conf/context.xml +file affects all web applications. See +Context documentation for details.

      +
    4. +
    + +

    Configuration

    + +

    There are several servlet init parameters which can be used to +configure the behaviour of the CGI servlet.

    +
      +
    • cgiMethods - Comma separated list of HTTP methods. Requests +using one of these methods will be passed to the CGI script for the script to +generate the response. The default value is GET,POST. Use +* for the script to handle all requests regardless of method. +Unless over-ridden by the configuration of this parameter, requests using HEAD, +OPTIONS or TRACE will have handled by the superclass.
    • +
    • cgiPathPrefix - The CGI search path will start at +the web application root directory + File.separator + this prefix. +By default there is no value, which results in the web application root +directory being used as the search path. The recommended value is +WEB-INF/cgi
    • +
    • cmdLineArgumentsDecoded - If command line argumemnts +are enabled (via enableCmdLineArguments) and Tomcat is running +on Windows then each individual decoded command line argument must match this +pattern else the request will be rejected. This is to protect against known +issues passing command line arguments from Java to Windows. These issues can +lead to remote code execution. For more information on these issues see +Markus +Wulftange's blog and this archived +blog +by Daniel Colascione.
    • +
    • cmdLineArgumentsEncoded - If command line argumemnts +are enabled (via enableCmdLineArguments) individual encoded +command line argument must match this pattern else the request will be rejected. +The default matches the allowed values defined by RFC3875 and is +[a-zA-Z0-9\Q%;/?:@&,$-_.!~*'()\E]+
    • +
    • enableCmdLineArguments - Are command line arguments +generated from the query string as per section 4.4 of 3875 RFC? The default is +false.
    • +
    • environment-variable- - An environment to be set for the +execution environment of the CGI script. The name of variable is taken from the +parameter name. To configure an environment variable named FOO, configure a +parameter named environment-variable-FOO. The parameter value is used as the +environment variable value. The default is no environment variables.
    • +
    • executable - The name of the executable to be used to +run the script. You may explicitly set this parameter to be an empty string +if your script is itself executable (e.g. an exe file). Default is +perl.
    • +
    • executable-arg-1, executable-arg-2, +and so on - additional arguments for the executable. These precede the +CGI script name. By default there are no additional arguments.
    • +
    • envHttpHeaders - A regular expression used to select the +HTTP headers passed to the CGI process as environment variables. Note that +headers are converted to upper case before matching and that the entire header +name must match the pattern. Default is +ACCEPT[-0-9A-Z]*|CACHE-CONTROL|COOKIE|HOST|IF-[-0-9A-Z]*|REFERER|USER-AGENT +
    • +
    • parameterEncoding - Name of the parameter encoding +to be used with the CGI servlet. Default is +System.getProperty("file.encoding","UTF-8"). That is the system +default encoding, or UTF-8 if that system property is not available.
    • +
    • passShellEnvironment - Should the shell environment +variables from Tomcat process (if any) be passed to the CGI script? Default is +false.
    • +
    • stderrTimeout - The time (in milliseconds) to wait for +the reading of stderr to complete before terminating the CGI process. Default +is 2000.
    • +
    + +

    The CGI script executed depends on the configuration of the CGI Servlet and +how the request is mapped to the CGI Servlet. The CGI search path starts at the +web application root directory + File.separator + cgiPathPrefix. The +pathInfo is then searched unless it is null - in +which case the servletPath is searched.

    + +

    The search starts with the first path segment and expands one path segment +at a time until no path segments are left (resulting in a 404) or a script is +found. Any remaining path segments are passed to the script in the +PATH_INFO environment variable.

    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/changelog.html b/tomcat/docs/changelog.html new file mode 100644 index 0000000..6b9658d --- /dev/null +++ b/tomcat/docs/changelog.html @@ -0,0 +1,6644 @@ + +Apache Tomcat 8 (8.5.43) - Changelog

    Changelog

    Tomcat 8.5.43 (markt)

    +

    Catalina

    +
      +
    • Update: + Modify the Default and WebDAV Servlets so that a 405 status code is + returned for PUT and DELETE requests when + disabled via the readonly initialisation parameter. +
    • +
    • Fix: + Align the contents of the Allow header with the response + code for the Default and WebDAV Servlets. For any given resource a + method that returns a 405 status code will not be listed in the + Allow header and a method listed in the Allow + header will not return a 405 status code. (markt) +
    • +
    • Fix: + When using WebDAV to copy a file resource to a destination that requires + a collection to be overwritten, ensure that the operation succeeds + rather than fails (with a 500 response). This enables Tomcat to pass two + additional tests from the Litmus WebDAV test suite. (markt) +
    • +
    • Fix: + 49464: Improve the Default Servlet's handling of static files + when the file encoding is not compatible with the required response + encoding. (markt) +
    • +
    • Fix: Fix typo in UTF-32LE charset name. Patch by zhanhb vi Github. + (fschumacher) +
    • +
    • Add: + 58590: Add the ability for a UserDatabase to monitor the + backing XML file for changes and reload the source file if a change in + the last modified time is detected. This is enabled by default meaning + that changes to $CATALINA_BASE/conf/tomcat-users.xml will + now take effect a short time after the file is saved. (markt) +
    • +
    • Fix: + Improve parsing of Range request headers. (markt) +
    • +
    • Fix: + Range headers that specify a range unit Tomcat does not recognise should + be ignored rather than triggering a 416 response. Based on a pull + request by zhanhb. (markt) +
    • +
    • Fix: + When comparing a date from a If-Range header, an exact + match is required. Based on a pull request by zhanhb. (markt) +
    • +
    • Fix: + Add an option to the default servlet to disable processing of PUT + requests with Content-Range headers as partial PUTs. The default + behaviour (processing as partial PUT) is unchanged. Based on a pull + request by zhanhb. (markt) +
    • +
    • Fix: + Improve parsing of Content-Range headers. (markt) +
    • +
    • Fix: + Ensure that the HEAD response is consistent with the GET response when + HttpServlet is relied upon to generate the HEAD response + and the GET response uses chunking. (markt) +
    • +
    • Update: + Update the recommended minimum Tomcat Native version to 1.2.23. (markt) +
    • +
    +
    +

    Coyote

    +
      +
    • Fix: + Avoid a potential hang when a client connects using TLS 1.0 to a Tomcat + HTTPS connector configured to use NIO or NIO with OpenSSL 1.1.1 or + later. (markt) +
    • +
    • Fix: + Once a URI is identified as invalid don't attempt to process it further. + Based on a PR by Alex Repert. (markt) +
    • +
    • Fix: + Fix to avoid the possibility of long poll times for individual pollers + when using mutliple pollers with APR. (markt) +
    • +
    • Fix: + Refactor the fix for 63205 so it only applies when using + PKCS12 keystores as regressions have been reported with some other + keystore types. (markt) +
    • +
    +
    +

    Jasper

    +
      +
    • Add: + Include file names in error messages if SMAP processor is unable to + delete or rename a class file during SMAP generation. (markt) +
    • +
    +
    +

    WebSocket

    +
      +
    • Fix: + 63521: As required by the WebSocket specification, if a POJO + that is deployed as a result of the SCI scan for annotated POJOs is + subsequently deployed via the programmatic API ignore the programmatic + deployment. (markt) +
    • +
    +
    +

    Other

    +
      +
    • Code: + Switch i18n message files to use UTF-8 and convert to ASCII at build + time. (markt) +
    • +
    • Fix: + 63523: Restore SSLUtilBase methods as protected to preserve + compatibility. (remm) +
    • +
    • Fix: + Switch the check for terminal availability to test for stdin as using + stdout does not work when output is piped to another process. Patch + provided by Radosław Józwik. (markt) +
    • +
    +
    +

    2019-06-07 Tomcat 8.5.42 (markt)

    +

    Catalina

    +
      +
    • Add: + 57287: Add file sorting to DefaultServlet (schultz) +
    • +
    • Fix: + Ensure that the default servlet reads the entire global XSLT file if + one is defined. Identified by Coverity Scan. (markt) +
    • +
    • Fix: + Avoid potential NullPointerException when generating an + HTTP Allow header. Identified by Coverity Scan. (markt) +
    • +
    • Add: + Remove any fragment included in the target path used to obtain a + RequestDispatcher. The requested target path is logged as a + warning since this is an application error. (markt) +
    • +
    +
    +

    Coyote

    +
      +
    • Update: + Add additional NIO2 style read and write methods closer to core NIO2, + for possible use with an asynchronous workflow like CompletableFuture. + (remm) +
    • +
    • Fix: + Avoid useless exception wrapping in async IO. (remm) +
    • +
    • Fix: + 63412: Security manager failure when using the async IO + API from a webapp. (remm) +
    • +
    • Fix: + Fix concurrency issue that lead to incorrect HTTP/2 connection timeout. + (remm/markt) +
    • +
    • Update: + Reduce the default for maxConcurrentStreams on the + Http2Protocol from 200 to 100 to align with typical + defaults for HTTP/2 implementations. (markt) +
    • +
    • Update: + Reduce the default HTTP/2 header list size from 4GB to 32kB to align + with typical HTTP/2 implementations. (markt) +
    • +
    • Add: + Add support for same-site cookie attribute. Patch provided by John + Kelly. (markt) +
    • +
    • Fix: + Correct a bug in the stream flushing code that could lead to multiple + threads processing the stream concurrently which in turn could cause + errors processing the stream. (markt) +
    • +
    +
    +

    Cluster

    +
      +
    • Fix: + 62841: Refactor the DeltaRequest serialization + to reduce the window during which the DeltaSession is + locked and to remove a potential cause of deadlocks during + serialization. (markt) +
    • +
    • Fix: + 63441: Further streamline the processing of session creation + messages in the DeltaManager to reduce the possibility of a + session update message being processed before the session has been + created. (markt) +
    • +
    +
    +

    Tribes

    +
      +
    • Fix: + Treat NoRouteToHostException the same way as + SocketTimeoutException when checking the health of group + members. This avoids a SEVERE log message every time the check is + performed when the host associated with a group member is not powered + on. (markt) +
    • +
    +
    +

    Other

    +
      +
    • Update: + Switch from FindBugs to SpotBugs. (fschumacher) +
    • +
    • Fix: + 63403: Fix TestHttp2InitialConnection test failures when + running with a non-English locale. (kkolinko) +
    • +
    • Fix: + Use the test command to check for terminal availability + rather than the tty command since the tty + based test fails on non-English locales. (markt) +
    • +
    +
    +

    2019-05-13 Tomcat 8.5.41 (markt)

    +

    Catalina

    +
      +
    • Fix: + Fix a potential resource leak when executing CGI scripts from a WAR + file. Identified by Coverity scan. (markt) +
    • +
    • Fix: + Fix a potential concurrency issue in the StringCache identified by + Coverity scan. (markt) +
    • +
    • Fix: + Fix a potential concurrency issue in the main Sendfile thread of the APR + connector. Identified by Coverity scan. (markt) +
    • +
    • Fix: + Fix a potential resource leak when running a web application from a WAR + file. Identified by Coverity scan. (markt) +
    • +
    • Fix: + Fix a potential resource leak on some exception paths in the + DataSourceRealm. Identified by Coverity scan. (markt) +
    • +
    • Fix: + Fix a potential resource leak on an exception path when parsing JSP + files. Identified by Coverity scan. (markt) +
    • +
    • Fix: + Fix a potential resource leak when a JNDI lookup returns an object of an + in compatible class. Identified by Coverity scan. (markt) +
    • +
    • Code: + Refactor ManagerServlet to avoid loading classes when + filtering JNDI resources for resources of a specified type. (markt) +
    • +
    • Fix: + Avoid OutOfMemoryErrors and + ArrayIndexOutOfBoundsExceptions when accessing large files + via the default servlet when resource caching has been disabled. (markt) +
    • +
    • Fix: + Avoid a NullPointerException when a Context is + defined in server.xml with a docBase but not + the optional path. (markt) +
    • +
    • Fix: + 63324: Refactor the CrawlerSessionManagerValve + so that the object placed in the session is compatible with session + serialization with mem-cached. Patch provided by Martin Lemanski. + (markt) +
    • +
    • Fix: + 63333: Override the isAvailable() method in the + JAASRealm so that only login failures caused by invalid + credentials trigger account lock out when the LockOutRealm + is in use. Patch provided by jchobantonov. (markt) +
    • +
    +
    +

    Coyote

    +
      +
    • Fix: + When running on newer JREs that don't support SSLv2Hello, don't warn + that it is not available unless explicitly configured. (markt) +
    • +
    • Code: + Refactor Hostname validation to improve performance. Patch provided by + Uwe Hees. (markt) +
    • +
    • Fix: + Expand HTTP/2 timeout handling to include connection window exhaustion + on write. This is the fix for CVE-2019-10072. (markt) +
    • +
    +
    +

    Other

    +
      +
    • Fix: + 63335: Ensure that stack traces written by the + OneLineFormatter are fully indented. The entire stack trace + is now indented by an additional TAB character. (markt) +
    • +
    • Fix: + When using the OneLineFormatter, don't print a blank line + in the log after printing a stack trace. (markt) +
    • +
    • Update: + Update the internal fork of Apache Commons DBCP 2 to dcdbc72 + (2019-04-24) to pick up some clean-up and enhancements less the JDBC 4.2 + related changes that require Java 8. (markt) +
    • +
    • Update: + Update the internal fork of Apache Commons Pool 2 to 0664f4d + (2019-04-30) to pick up some enhancements and bug fixes. (markt) +
    • +
    • Update: + Update the internal fork of Apache Commons FileUpload to 41e4047 + (2019-04-24) pick up some enhancements. (markt) +
    • +
    +
    +

    2019-04-12 Tomcat 8.5.40 (markt)

    +

    Catalina

    +
      +
    • Fix: + 63196: Provide a default (X-Forwarded-Proto) for + the protocolHeader attribute of the + RemoteIpFilter and RemoteIpValve. (markt) +
    • +
    • Fix: + 63235: Refactor Charset cache to reduce start time. (markt) +
    • +
    • Fix: + 63249: Use a consistent log level (WARN) when + logging the failure to register or deregister a JMX Bean. (markt) +
    • +
    • Fix: + 63249: Use a consistent log level (ERROR) when + logging the LifecycleException associated with the failure + to start or stop a component. (markt) +
    • +
    • Fix: + When the SSI directive fsize is used with an invalid + target, return a file size of - rather than + 1k. (markt) +
    • +
    • Fix: + 63251: Implement a work-around for a known JRE bug (JDK-8194653) + that may cause a dead-lock when Tomcat starts. (markt) +
    • +
    • Fix: + 63275: When using a RequestDispatcher ensure + that HttpServletRequest.getContextPath() returns an encoded + path in the dispatched request. (markt) +
    • +
    • Fix: + 63286: Document the differences in behaviour between the + LogFormat directive in httpd and the pattern + attribute in the AccessLogValve for %D and + %T. (markt) +
    • +
    • Fix: + 63311: Add support for https URLs to the local resolver within + Tomcat used to resolve standard XML DTDs and schemas when Tomcat is + configured to validate XML configuration files such as web.xml. (markt) +
    • +
    • Fix: + Encode the output of the SSI printenv command. This is the + fix for CVE-2019-0221. (markt) +
    • +
    • Code: + Use constants for SSI encoding values. (markt) +
    • +
    • Add: + When the CGI Servlet is configured with + enableCmdLineArguments set to true, limit the encoded form + of the individual command line arguments to those values allowed by RFC + 3875. This restriction may be relaxed by the use of the new + initialisation parameter cmdLineArgumentsEncoded. (markt) +
    • +
    • Add: + When the CGI Servlet is configured with + enableCmdLineArguments set to true, limit the decoded form + of the individual command line arguments to known safe values when + running on Windows. This restriction may be relaxed by the use of the + new initialisation parameter cmdLineArgumentsDecoded. This + is the fix for CVE-2019-0232. (markt) +
    • +
    • Update: + Change the default for the enableCmdLineArguments parameter + of the CGI servlet from true to false as + additional hardening against CVE-2019-0232. (markt) +
    • +
    +
    +

    Coyote

    +
      +
    • Fix: + Fix bad interaction between NIO2 async read API and the regular read. + (remm) +
    • +
    • Fix: + Refactor NIO2 write pending strategy for the classic IO API. (remm) +
    • +
    • Fix: + Harmonize NIO2 isReadyForWrite with isReadyForRead code. (remm) +
    • +
    • Fix: + When using a JSSE TLS connector that supported ALPN (Java 9 onwards) and + a protocol was not negotiated, Tomcat failed to fallback to HTTP/1.1 and + instead dropped the connection. (markt) +
    • +
    • Fix: + Correct a regression in the TLS connector refactoring in Tomcat 9.0.17 + that prevented the use of PKCS#8 private keys with OpenSSL based + connectors. (markt) +
    • +
    • Fix: + When performing an upgrade from HTTP/1.1 to HTTP/2, ensure that any + query string present in the original HTTP/1.1 request is passed to the + HTTP/2 request processing. (markt) +
    • +
    • Fix: + When Tomcat writes a final response without reading all of an HTTP/2 + request, reset the stream to inform the client that the remaining + request body is not required. (markt) +
    • +
    • Fix: + 63312: Correct a regression in the error page handling that + prevented error pages from issuing redirects or taking other action that + required the response status code to be changed. (markt) +
    • +
    +
    +

    Jasper

    +
      +
    • Add: + Add support for specifying Java 11 (with the value 11) as + the compiler source and/or compiler target for JSP compilation. (markt) +
    • +
    • Add: + Add support for specifying Java 12 (with the value 12) and + Java 13 (with the value 13) as the compiler source and/or + compiler target for JSP compilation. If used with an ECJ version that + does not support these values, a warning will be logged and the latest + supported version will used. Based on a patch by Thomas Collignon. + (markt) +
    • +
    +
    +

    WebSocket

    +
      +
    • Fix: + Improve the handling of exceptions during TLS handshakes for the + WebSocket client. (markt) +
    • +
    +
    +

    Web applications

    +
      +
    • Fix: + 63184: Expand the SSI documentation to provide more + information on the supported directives and their attributes. Patch + provided by nightwatchcyber. (markt) +
    • +
    • Add: + Add a note to the documentation about the risk of DoS with poorly + written regular expressions and the RewriteValve. Patch + provided by salgattas. (markt) +
    • +
    +
    +

    jdbc-pool

    +
      +
    • Fix: + 63320: Ensure that StatementCache caches + statements that include arrays in arguments. (kfujino) +
    • +
    +
    +

    2019-03-19 Tomcat 8.5.39 (markt)

    +

    Catalina

    +
      +
    • Fix: + Minor HTTP/2 push fixes. (remm) +
    • +
    • Fix: + Refactor how cookies are transferred from the base request to a + PushBuilder so that they are accessible, and may be edited, + via the standard PushBuilder methods for working with HTTP + headers. (markt) +
    • +
    • Add: + Refactor error handling to enable errors that occur before processing is + passed to the application to be handled by the application provided + error handling and/or the container provided error handling + (ErrorReportValve) as appropriate. (markt) +
    • +
    • Add: + Pass 404 errors triggered by a missing ROOT web application to the + container error handling to generate the response body. (markt) +
    • +
    • Add: + Pass 400 errors triggered by invalid request targets to the container + error handling to generate the response body. (markt) +
    • +
    • Add: + Pass errors triggered by invalid requests or unavailable services to the + application provided error handling and/or the container provided error + handling (ErrorReportValve) as appropriate. (markt) +
    • +
    • Code: + Refactor the MBean implementations for the internal Tomcat components + to reduce code duplication. (markt) +
    • +
    • Update: + Simplify the value of jarsToSkip property in + catalina.properties file for tomcat-i18n jar files. + Use prefix pattern instead of listing each language. (kkolinko) +
    • +
    • Fix: + Restore the getter and setter for the access log valve attribute + maxLogMessageBufferSize that were accidentally removed. + (markt) +
    • +
    • Add: + 63206: Add a new attribute to Context - + createUploadTargets which, if true enables + Tomcat to create the temporary upload location used by a Servlet if the + location specified by the Servlet does not already exist. The default + value is false. (markt) +
    • +
    • Fix: + 63210: Ensure that the Apache Commons DBCP 2 based default + connection pool is correctly shutdown when it is no longer required. + This ensures that a non-daemon thread is not left running that will + prevent Tomcat from shutting down cleanly. (markt) +
    • +
    • Fix: + 63213: Ensure the correct escaping of group names when + searching for nested groups when the JNDIRealm is configured with + roleNested set to true. (markt) +
    • +
    • Fix: + 63236: Use String.intern() as suggested by + Phillip Webb to reduce memory wasted due to String duplication. This + changes saves ~245k when starting a clean installation. With additional + thanks to YourKit Java profiler for helping to track down the wasted + memory and the root causes. (markt) +
    • +
    • Fix: + 63246: Fix a potential NullPointerException when + calling AsyncContext.dispatch(). (markt) +
    • +
    +
    +

    Coyote

    +
      +
    • Fix: + Ensure that the toString(), toBytes() and + toChars() methods of MessageBytes behave + consistently and do not throw a NullPointerException both + on newly created objects and immediately after a call to + recycle(). This should not impact typical Tomcat users. It + may impact users who use these classes directly in their own code. + (markt) +
    • +
    • Fix: + When performing an HTTP/1.1 upgrade to HTTP/2 (h2c) ensure that the hostname + and port from the HTTP/1.1 Host header of the upgraded request are made + available via the standard methods + ServletRequest.getServerName() and + ServletRequest.getServerPort(). (markt) +
    • +
    • Fix: + Make PEM file parser a public utility class. (remm) +
    • +
    • Fix: + Refactor the APR/Native endpoint TLS configuration code to enable JSSE + style configuration - including JKS keystores - to be used with the + APR/Native connector. (markt) +
    • +
    • Add: + With the TLS configuration refactoring, the configuration attributes + sessionCacheSize and sessionTimeout are no + longer limited to JSSE implementations. They may now be used with + OpenSSL implementations as well. (markt) +
    • +
    • Fix: + Refactor NIO2 read pending strategy for the classic IO API. (remm) +
    • +
    • Fix: + 63182: Avoid extra read notifications for HTTP/1.1 with + NIO2 when using asynchronous threads. (remm) +
    • +
    • Add: + 63205: Add a work-around for a known + JRE KeyStore + loading bug. (markt) +
    • +
    • Update: + Sync with NIO2 async API from Tomcat 9 branch. (remm) +
    • +
    • Fix: + NIO2 should try to use SocketTimeoutException everywhere rather than a + mix of it and InterruptedByTimeout. (remm) +
    • +
    • Fix: + Correct an error in the request validation that meant that HTTP/2 push + requests always resulted in a 400 response. (markt) +
    • +
    • Fix: + 63223: Correctly account for push requests when tracking + currently active HTTP/2 streams. (markt) +
    • +
    • Fix: + Verify HTTP/2 stream is still writable before assuming a timeout + occurred. (remm) +
    • +
    • Fix: + Avoid some overflow cases with OpenSSL to improve efficiency, as the + OpenSSL engine has an internal buffer. (remm) +
    • +
    • Fix: + Harmonize HTTP/1.1 NIO2 keepalive code. (remm) +
    • +
    +
    +

    WebSocket

    +
      +
    • Code: + Remove the STREAMS_DROP_EMPTY_MESSAGES system property that + was introduced to work-around four failing TCK tests. An alternative + solution has been implemented. Sending messages via + getSendStream() and getSendWriter() will now + only result in messages on the wire if data is written to the + OutputStream or Writer. Writing zero length + data will result in an empty message. Note that sending a message via an + Encoder may result in the message being send via + getSendStream() or getSendWriter(). (markt) +
    • +
    +
    +

    Web applications

    +
      +
    • Fix: + Use client's preferred language for the Server Status page of the + Manager web application. Review and fix several cases when the + client's language preference was not respected in Manager and + Host Manager web applications. (kkolinko) +
    • +
    • Fix: + Fix messages used by Manager and Host Manager web applications. + Disambiguate message keys used when adding or removing a host. + Improve display of summary values on the status page: separate + terms and values with a whitespace. Improve wording of messages + for expire sessions command. (kkolinko) +
    • +
    • Fix: + Do not add CSRF nonce parameter and suppress Referer header for external + links in Manager and Host Manager web applications. (kkolinko) +
    • +
    +
    +

    Tribes

    +
      +
    • Fix: + Ensure that members registered in the addSuspects list are static + members. (kfujino) +
    • +
    +
    +

    Other

    +
      +
    • Add: + Expand the coverage and quality of the Russian translations provided + with Apache Tomcat. (kkolinko) +
    • +
    • Fix: + 63041: Revert the changes for 53930 that added + support for the CATALINA_OUT_CMD environment variable as + they prevented correct operation with systemd configurations that did + not explicitly specify a PID file. (markt) +
    • +
    +
    +

    2019-02-08 Tomcat 8.5.38 (markt)

    +

    Catalina

    +
      +
    • Fix: + 54741: Add a new method, + Tomcat.addWebapp(String,URL), that allows a web application + to be deployed from a URL when using Tomcat in embedded mode. (markt) +
    • +
    • Fix: + Ensure that the ServletOutputStream implementation is + consistent with the requirements of asynchronous I/O and that all of the + write methods use a single write rather than multiple writes. (markt) +
    • +
    • Fix: + Correct the Javadoc for Context.getDocBase() and + Context.setDocBase() and remove text that indicates that a + URL may be used for the docBase as this has not been the + case for quite some time. (markt) +
    • +
    • Add: + Ensure that Tomcat is fully terminated when running as a service. + (markt) +
    • +
    • Code: + Treat I/O errors during request body reads the same way as I/O errors + during response body writes. The errors are treated as client side + errors rather than server side errors and only logged at debug level. + (markt) +
    • +
    • Fix: + 63038: Ensure that a ClassNotFoundException is + thrown when attempting to load a class from a corrupted JAR file. + (markt) +
    • +
    • Add: + Make the removal of leading and trailing whitespace from credentials + passed to BASIC authentication configurable via a new attribute, + trimCredentials on the BasicAuthenticator. + (markt) +
    • +
    • Fix: + 63003: Extend the unloadDelay attribute on a + Context to include in-flight asynchronous requests. (markt) +
    • +
    • Add: + 63026: Add a new attribute, forceDnHexEscape, to + the JNDIRealm that forces escaping in the String + representation of a distinguished name to use the \nn form. + This may avoid issues with realms using Active Directory which appears + to be more tolerant of optional escaping when the \nn form + is used. (markt) +
    • +
    • Fix: + Avoid a swallowed (and therefore ignored) access failure during web + application class loading when running under a + SecurityManager. (markt) +
    • +
    • Update: + Update the recommended minimum Tomcat Native version to 1.2.21. (markt) +
    • +
    • Fix: + 63137: If the resources for a web application have been + configured with multiple locations mapped to + /WEB-INF/classes, ensure that all of those locations are + used when building the web application class path. Patch provided by + Marcin Gołębski. (markt) +
    • +
    +
    +

    Coyote

    +
      +
    • Add: + 63009: Include the optional content-length + header in HTTP/2 responses where an appropriate value is available. + (markt) +
    • +
    • Fix: + 63022: Do not use the socket open state when using the + wrapper isClosed method for NIO and NIO2, as it will disable all + further processing. (remm) +
    • +
    • Fix: + Fix socket close discrepancies for NIO2, now the wrapper close + is used everywhere except for socket accept problems. (remm) +
    • +
    +
    +

    Jasper

    +
      +
    • Fix: + 63056: Correct a regression in the fix for 53737 + that did not correctly scan the web application directory structure for + JSPs. (markt) +
    • +
    • Fix: + Update the performance optimisation for using expressions in tags that + depend on uninitialised tag attributes with implied scope to make the + performance optimisation aware of the new public class + (java.lang.Enum$EnumDesc) added in Java 12. (markt) +
    • +
    +
    +

    WebSocket

    +
      +
    • Fix: + 57974: Ensure implementation of + Session.getOpenSessions() returns correct value for both + client-side and server-side calls. (markt) +
    • +
    • Fix: + 63019: Use payload remaining bytes rather than limit when + writing. Submitted by Benoit Courtilly. (remm) +
    • +
    • Fix: + When running under a SecurityManager, ensure that the + ServiceLoader look-up for the default + javax.websocket.server.ServerEndpointConfig.Configurator + implementation completes correctly rather than silently using the + hard-coded fall-back. (markt) +
    • +
    • Fix: + Ensure that the network connection is closed if the client receives an + I/O error trying to communicate with the server. (markt) +
    • +
    • Fix: + Ignore synthetic methods when scanning POJO methods. (markt) +
    • +
    • Fix: + Implement the requirements of section 5.2.1 of the WebSocket 1.1 + specification and ensure that if the deployment of one Endpoint fails, + no Endpoints are deployed for that web application. (markt) +
    • +
    • Fix: + Implement the requirements of section 4.3 of the WebSocket 1.1 + specification and ensure that the deployment of an Endpoint fails if + @PathParam is used with an invalid parameter type. (markt) +
    • +
    • Fix: + Ensure a DeploymentException rather than an + IllegalArgumentException is thrown if a method annotated + with @OnMessage does not conform to the requirements set + out in the Javadoc. (markt) +
    • +
    • Fix: + Improve algorithm that determines if two @OnMessage + annotations have been added for the same message type. Prior to this + change some matches were missed. (markt) +
    • +
    +
    +

    Web applications

    +
      +
    • Fix: + 63103: Remove the unused source.jsp file and associated tag + from the examples web application as it is no longer used. (markt) +
    • +
    • Fix: + 63143: Ensure that the Manager web application respects the + language preferences of the user as configured in the browser when the + language of the default system locale is not English. (markt) +
    • +
    +
    +

    Tribes

    +
      +
    • Add: + Add EncryptInterceptor to the portfolio of available clustering + interceptors. This adds symmetric encryption of session data + to Tomcat clustering regardless of the type of cluster manager + or membership being used. (schultz) +
    • +
    • Update: + Update the packaged version of the Tomcat Native Library to 1.2.21 to + pick up the memory leak fixes when using NIO/NIO2 with OpenSSL. (markt) +
    • +
    +
    +

    Other

    +
      +
    • Fix: + 63041: Correct a regression in the fix for 53930 + that prevented Tomcat from working correctly with systemd. Patch + provided by Patrik S. (markt) +
    • +
    • Update: + Update the NSIS Installer used to build the Windows installer to version + 3.04. (markt) +
    • +
    +
    +

    2018-12-18 Tomcat 8.5.37 (markt)

    +

    Catalina

    +
      +
    • Update: + Update the recommended minimum Tomcat Native version to 1.2.19. (markt) +
    • +
    +
    +

    Other

    +
      +
    • Update: + Update the packaged version of the Tomcat Native Library to 1.2.19 to + pick up the latest Windows binaries built with APR 1.6.5 and OpenSSL + 1.1.1a. (markt) +
    • +
    +
    +

    not released Tomcat 8.5.36 (markt)

    +

    Catalina

    +
      +
    • Fix: + 62788: Add explicit logging configuration to write log files + using UTF-8 to align with Tomcat's use of UTF-8 by default + elsewhere. (markt) +
    • +
    • Fix: + The default Servlet should not override a previously set content-type. + (remm) +
    • +
    • Add: + 62897: Provide a property + (clearReferencesThreadLocals) on the standard + Context implementation that enables the check for memory + leaks via ThreadLocals to be disabled because this check + depends on the use of an API that has been deprecated in later versions + of Java. (markt) +
    • +
    • Fix: + Fix more storeconfig issues with duplicated SSL attributes. (remm) +
    • +
    • Fix: + 62968: Avoid unnecessary (and relatively expensive) + getResources() call in the Mapper when processing rule 7. + (markt) +
    • +
    • Fix: + 62978: Update the RemoteIpValve to handle multiple values in + the x-forwarded-proto header. Patch provided by Tom Groot. + (markt) +
    • +
    • Fix: + Update the RemoteIpFilter to handle multiple values in the + x-forwarded-proto header. Based on a patch provided by Tom + Groot. (markt) +
    • +
    • Code: + 62986: Refactor the code that performs class scanning during + web application start to make integration simpler for downstream users. + Patch provided by rmannibucau. (markt) +
    • +
    • Fix: + 62988: Fix the LoadBalancerDrainingValve so it + works when the session cookie configuration is not explicitly declared. + Based on a patch provided by Andreas Kurth. (markt) +
    • +
    • Fix: + 63002: Fix setting rewrite qsdiscard flag. (remm) +
    • +
    • Fix: + Implement the requirements of section 8.2.2 2c of the Servlet + specification and prevent a web application from deploying if it has + fragments with duplicate names and is configured to use relative + ordering of fragments. (markt) +
    • +
    +
    +

    Coyote

    +
      +
    • Fix: + Avoid an exception when using Tomcat Native built with a version of + OpenSSL that does not support TLSv1.3. (markt) +
    • +
    • Fix: + 62899: Prevent the incorrect timing out of connections when + Servlet non-blocking I/O is used to read a request body over an HTTP/2 + stream. (markt) +
    • +
    • Fix: + Avoid bad SSLHostConfig JMX registrations before init. (remm) +
    • +
    +
    +

    Jasper

    +
      +
    • Add: + 53737: Extend JspC, the precompilation tool, to include + support for resource JARs. (markt) +
    • +
    • Fix: + 62976: Avoid an IllegalStateException when using + background compilation when tag files are packaged in JAR files. (markt) +
    • +
    +
    +

    Web applications

    +
      +
    • Fix: + 62918: Filter out subtype mbeans to avoid breaking the + connector status page. (remm) +
    • +
    +
    +

    Other

    +
      +
    • Fix: + Prevent an error when running in a Cygwin shell and the + JAVA_ENDORSED_DIRS system property is empty. Patch provided + by Zemian Deng. (markt) +
    • +
    • Add: + 53930: Add support for the CATALINA_OUT_CMD + environment variable that defines a command to which captured stdout and + stderr will be redirected. Patch provided by Casey Lucas. (markt) +
    • +
    +
    +

    2018-11-07 Tomcat 8.5.35 (markt)

    +

    Catalina

    +
      +
    • Add: + 61692: Add the ability to control which HTTP methods are + handled by the CGI Servlet via a new initialization parameter + cgiMethods. (markt) +
    • +
    • Fix: + 62687: Expose content length information for resources + when using a compressed war. (remm) +
    • +
    • Fix: + 62737: Fix rewrite substitutions parsing of {} nesting. + (remm) +
    • +
    • Fix: + Add rewrite flags output when getting the rewrite configuration back. + (remm) +
    • +
    • Fix: + Add missing qsdiscard flag to the rewrite flags as a cleaner way to + discard the query string. (remm) +
    • +
    • Fix: + Add documentation about the files context.xml.default and + web.xml.default that can be used to customize conf/context.xml + and conf/web.xml on a per host basis. (fschumacher) +
    • +
    • Fix: + Ensure that a canonical path is always used for the docBase of a Context + to ensure consistent behaviour. (markt) +
    • +
    • Fix: + 62803: Fix SSL connector configuration processing + in storeconfig. (remm) +
    • +
    • Fix: + 62797: Pass throwable to keep client aborts with status 200 + rather than 500. Patch submitted by zikfat. (remm) +
    • +
    • Fix: + 62809: Correct a regression in the implementation of DIGEST + authentication support for the Deployer Ant tasks (bug 45832) + that prevented the DeployTask from working when + authentication was required. (markt) +
    • +
    • Update: + Update the recommended minimum Tomcat Native version to 1.2.18. (markt) +
    • +
    • Add: + Ignore an attribute named source on Context + elements provided by StandardContext. This is to suppress + warnings generated by the Eclipse / Tomcat integration provided by + Eclipse. Based on a patch by mdfst13. (markt) +
    • +
    • Add: + 62830: Added JniLifeCycleListener and static + methods Library.loadLibrary(libraryName) and + Library.load(filename) to load a native library by a + shared class loader so that more than one Webapp can use it. (isapir) +
    • +
    • Fix: + Correct a typo in the Spanish resource files. Patch provided by Diego + Agulló. (markt) +
    • +
    • Fix: + 62868: Order the Enumeration<URL> provided + by WebappClassLoaderBase.getResources(String) according to + the setting of the delegate flag. (markt) +
    • +
    +
    +

    Coyote

    +
      +
    • Add: + Add TLSv1.3 to the default protocols and to the all + alias for JSSE based TLS connectors when running on a JVM that + supports TLS version 1.3. One such JVM is OpenJDK version 11. (rjung) +
    • +
    • Fix: + 62685: Correct an error in host name validation parsing that + did not allow a fully qualified domain name to terminate with a period. + Patch provided by AG. (markt) +
    • +
    • Fix: + 62739: Do not reject requests with an empty HTTP Host header. + Such requests are unusual but not invalid. Patch provided by Michael + Orr. (markt) +
    • +
    • Add: + 62748: Add TLS 1.3 support for the APR/Native connector and + the NIO/NIO2 connector when using the OpenSSL backed JSSE + implementation. (schultz/markt) +
    • +
    • Fix: + 62791: Remove an unnecessary check in the NIO TLS + implementation that prevented from secure WebSocket connections from + being established. (markt) +
    • +
    • Fix: + Fix server initiated TLS renegotiation to obtain a client certificate + when using NIO/NIO2 and the OpenSSL backed JSSE TLS implementation. + (markt) +
    • +
    • Fix: + 62871: Improve MBeans for Endpoint instances (type + ThreadPool in JMX) by using explicit declaration of + attributes and operations rather than relying on introspection. Add a + new MBean to expose the Socketproperties values. (markt) +
    • +
    +
    +

    Jasper

    +
      +
    • Fix: + Correct parsing of XML whitespace in TLD function signatures that + incorrectly only looked for the space character. (markt) +
    • +
    • Fix: + 62674: Correct a regression in the stand-alone JSP compiler + utility, JspC, caused by the fix for 53492, that + caused the JSP compiler to hang. (markt) +
    • +
    • Fix: + 62721: Correct generation of web.xml header when using JspC. + (markt) +
    • +
    • Fix: + 62757: Correct a regression in the fix for 62603 + that caused NullPointerExceptions when compiling tag files + on first access when development mode was disabled and background + compilation was enabled. Based on a patch by Jordi Llach. (markt) +
    • +
    +
    +

    WebSocket

    +
      +
    • Fix: + 62731: Make the URI returned by + HandshakeRequest.getRequestURI() and + Session.getRequestURI() absolute so that the scheme, host + and port are accessible. (markt) +
    • +
    +
    +

    Web applications

    +
      +
    • Fix: + 62676: Expand the CORS filter documentation to make it clear + that explicit configuration is required to enable support for + cross-origin requests. (markt) +
    • +
    • Fix: + 62712: Correct NPE in Manager application when attempting to + view configured certificates for an APR/native TLS connector. (markt) +
    • +
    • Fix: + 62761: Correct the advanced CORS example in the Filter + documentation to use a valid configuration. (markt) +
    • +
    • Fix: + 62786: Add a note to the Context documentation to explain + that, by default, settings for a Context element defined in server.xml + will be overwritten by settings specified in a default context file such + as conf/context.xml. (markt) +
    • +
    • Fix: + Create a little visual separation between the Undeploy button and the + other buttons in the Manager application. Patch provided by Łukasz + Jąder. (markt) +
    • +
    +
    +

    Other

    +
      +
    • Update: + Update the internal fork of Apache Commons Pool 2 to d4e0e88 + (2018-09-12) to pick up some bug fixes and enhancements. (markt) +
    • +
    • Update: + Update the packaged version of the Tomcat Native Library to 1.2.18 to + pick up the latest Windows binaries built with APR 1.6.5 and OpenSSL + 1.1.1. (markt) +
    • +
    +
    +

    2018-09-10 Tomcat 8.5.34 (markt)

    +

    Catalina

    +
      +
    • Add: + Make the isLocked() method of the LockOutRealm + public and expose the method via JMX. (markt) +
    • +
    • Fix: + Improve the handling of path parameters when working with + RequestDispatcher objects. (markt) +
    • +
    • Fix: + 62664: Process requests with content type + multipart/form-data to servlets with a + @MultipartConfig annotation regardless of HTTP method. + (markt) +
    • +
    • Fix: + 62667: Add recursion to rewrite substitution parsing. (remm) +
    • +
    • Fix: + 62669: When using the SSIFilter and a resource does not + specify a content type, do not force the content type to + application/x-octet-stream. (markt) +
    • +
    • Fix: + 62670: Adjust the memory leak protection for the + DriverManager so that JDBC drivers located in + $CATALINA_HOME/lib and $CATALINA_BASE/lib are + loaded via the service loader mechanism when the protection is enabled. + (markt) +
    • +
    • Fix: + When generating a redirect to a directory in the Default Servlet, avoid + generating a protocol relative redirect. (markt) +
    • +
    +
    +

    Coyote

    +
      +
    • Fix: + Fix potential deadlocks when using asynchronous Servlet processing with + HTTP/2 connectors. (markt) +
    • +
    • Fix: + 62620: Fix corruption of response bodies when writing large + bodies using asynchronous processing over HTTP/2. (markt) +
    • +
    • Fix: + 62628: Additional fixes for output corruption of response + bodies when writing large bodies using asynchronous processing over + HTTP/2. (markt) +
    • +
    +
    +

    Jasper

    +
      +
    • Fix: + Correct the JSP version in the X-PoweredBy HTTP header generated when + the xpoweredBy option is enabled. (markt) +
    • +
    • Fix: + 62662: Fix the corruption of web.xml output during JSP + compilation caused by the fix for 53492. Patch provided by + Bernhard Frauendienst. (markt) +
    • +
    +
    +

    Web applications

    +
      +
    • Add: + Expand the information in the documentation web application regarding + the use of CATALINA_HOME and CATALINA_BASE. + Patch provided by Marek Czernek. (markt) +
    • +
    • Fix: + 62652: Make it clearer that the version of DBCP that is + packaged in Tomcat 8.5.x is DBCP 2. Correct the names of some DBCP 2 + configuration attributes that changed between 1.x and 2.x. (markt) +
    • +
    • Add: + 62666: Expand internationalisation support in the Manager + application to include the server status page and provide Russian + translations in addition to English. Patch provided by Artem Chebykin. + (markt) +
    • +
    +
    +

    Other

    +
      +
    • Fix: + Switch the build script to use http for downloads from an ASF mirror + using the closer.lua script to avoid failures due to HTTPS to HTTP + redirects. (rjung) +
    • +
    +
    +

    2018-08-17 Tomcat 8.5.33 (markt)

    +

    Catalina

    +
      +
    • Fix: + Ensure that the HTTP Vary header is set correctly when using the CORS + filter and improve the cacheability of requests that pass through the + COPRS filter. (markt) +
    • +
    • Fix: + 62527: Revert restriction of JNDI to the java: + namespace. (remm) +
    • +
    • Add: + Introduce a new class - MultiThrowable - to report + exceptions when multiple actions are taken where each action may throw + an exception but all actions are taken before any errors are reported. + Use this new class when reporting multiple container (e.g. web + application) failures during start. (markt) +
    • +
    • Fix: + Correctly decode URL paths (+ should not be decoded to a + space in the path) in the RequestDispatcher and the web + application class loader. (markt) +
    • +
    • Add: + Make logout more robust if JASPIC subject is unexpectedly unavailable. + (markt) +
    • +
    • Fix: + 62547: JASPIC cleanSubject() was not called on + logout when the authenticator was configured to cache the authenticated + Principal. Patch provided by Guillermo González de Agüero. (markt) +
    • +
    • Add: + 62559: Add jaxb-*.jar to the list of JARs + ignored by StandardJarScanner. (markt) +
    • +
    • Add: + 62560: Add oraclepki.jar to the list of JARs + ignored by StandardJarScanner. (markt) +
    • +
    • Add: + 62607: Return a non-zero exit code from + catalina.[bat|sh] run if Tomcat fails to start. (markt) +
    • +
    • Code: + Remove ServletException from declaration of + Tomcat.addWebapp(String,String) since it is never thrown. + Patch provided by Tzafrir. (markt) +
    • +
    • Fix: + Use short circuit logic to prevent potential NPE in CorsFilter. (fschumacher) +
    • +
    • Code: + Simplify construction of appName from container name in JAASRealm. (fschumacher) +
    • +
    +
    +

    Coyote

    +
      +
    • Update: + 60560: Add support for using an inherited channel to + the NIO connector. Based on a patch submitted by Thomas Meyer with + testing and suggestions by Coty Sutherland. (remm) +
    • +
    • Fix: + 62507: Ensure that JSSE based TLS connectors work correctly + with a DKS keystore. Note: DKS keystores require Java 8 or later. + (markt) +
    • +
    • Fix: + Refactor code that adds an additional header name to the + Vary HTTP response header to use a common utility method + that addresses several additional edge cases. (markt) +
    • +
    • Fix: + 62515: When a connector is configured (via setting + bindOnInit to false) to bind/unbind the server + socket during start/stop, close the socket earlier in the stop process + so new connections do not sit in the TCP backlog during the shutdown + process only to be dropped as stop completes. In this scenario new + connections will now be refused immediately. (markt) +
    • +
    • Fix: + 62526: Correctly handle PKCS12 format key stores when the key + store password is configured to be the empty string. (markt) +
    • +
    • Fix: + Fix error in back-port of HTTP/2 compression that meant compression was + never enabled. (markt) +
    • +
    • Fix: + 62605: Ensure ReadListener.onDataAvailable() is + called when the initial request body data arrives after the request + headers when using asynchronous processing over HTTP/2. (markt) +
    • +
    • Fix: + 62614: Ensure that + WriteListener.onWritePossible() is called after + isReady() returns false and the window size is + subsequently incremented when using asynchronous processing over HTTP/2. + (markt) +
    • +
    +
    +

    Jasper

    +
      +
    • Fix: + 53011: When pre-compiling with JspC, report all compilation + errors rather than stopping after the first error. A new option + -failFast can be used to restore the previous behaviour of + stopping after the first error. Based on a patch provided by Marc Pompl. + (markt) +
    • +
    • Add: + 53492: Make the Java file generation process multi-threaded. + By default, one thread will be used per core. Based on a patch by Dan + Fabulich. (markt) +
    • +
    • Add: + 62453: Add a performance optimisation for using expressions + in tags that depend on uninitialised tag attributes with implied scope. + Generally, using an explicit scope with tag attributes in EL is the best + way to avoid various potential performance issues. (markt) +
    • +
    • Fix: + Correctly decode URL paths (+ should not be decoded to a + space in the path) in the Jasper class loader. (markt) +
    • +
    • Fix: + 62603: Fix a potential race condition when development mode + is disabled and background compilation checks are enabled. It was + possible that some updates would not take effect and/or + ClassNotFoundExceptions would occur. (markt) +
    • +
    +
    +

    WebSocket

    +
      +
    • Fix: + 62596: Remove the limit on the size of the initial HTTP + upgrade request used to establish the web socket connection. (markt) +
    • +
    +
    +

    Web applications

    +
      +
    • Add: + 61565: Add the ability to trigger a reloading of TLS host + configuration (certificate and key files, server.xml is not re-parsed) + via the Manager web application. (markt) +
    • +
    • Add: + 62558: Add Russian translations for the Manager and Host + Manager web applications. Based on a patch by Ivan Krasnov. (markt) +
    • +
    • Add: + 62561: Add advanced class loader configuration information + regarding the use of the Server and Shared class loaders to the + documentation web application. (markt) +
    • +
    +
    +

    Tribes

    +
      +
    • Fix: + Ensures that the specified rxBufSize is correctly set to + receiver buffer size. (kfujino) +
    • +
    +
    +

    Other

    +
      +
    • Update: + Support building with Java 9+ while preserving the Java 7 compatibility + at runtime (requires Ant 1.9.8 or later). (ebourg) +
    • +
    • Update: + Update WSDL4J library to version 1.6.3 (from 1.6.2). (kkolinko) +
    • +
    • Update: + Update JUnit library to version 4.12 (from 4.11). (kkolinko) +
    • +
    • Update: + Downgrade CGLib library used for testing with EasyMock to version + 2.2.2 (from 2.2.3) as version 2.2.3 is not available from Maven Central. + (markt/kkolinko) +
    • +
    • Add: + Implement checksum checks when downloading dependencies that are used + to build Tomcat. (kkolinko) +
    • +
    • Fix: + Fixed spelling. Patch provided by Jimmy Casey via GitHub. (violetagg) +
    • +
    • Update: + Update the internal fork of Apache Commons Pool 2 to 3e02523 + (2018-08-09) to pick up some bug fixes and enhancements. (markt) +
    • +
    • Update: + Update the internal fork of Apache Commons DBCP 2 to abc0484 + (2018-08-09) to pick up some bug fixes and enhancements. (markt) +
    • +
    • Fix: + Correct various spelling errors throughout the source code and + documentation. Patch provided by Kazuhiro Sera. (markt) +
    • +
    +
    +

    2018-06-25 Tomcat 8.5.32 (markt)

    +

    Catalina

    +
      +
    • Fix: + Treat the <mapped-name> element of a + <env-entry> in web.xml in the same way as the + mappedName element of the equivalent @Resource + annotation. Both now attempt to set the mappedName property + of the resource. (markt) +
    • +
    • Fix: + Correct the processing of resources with + <injection-target>s defined in web.xml. First look + for a match using JavaBean property names and then, only if a match is + not found, look for a match using fields. (markt) +
    • +
    • Fix: + When restoring a saved request with a request body after FORM + authentication, ensure that calls to the HttpServletRequest + methods getRequestURI(), getQueryString() and + getProtocol() are not corrupted by the processing of the + saved request body. (markt) +
    • +
    • Fix: + JNDI resources that are defined with injection targets but no value are + now treated as if the resource is not defined. (markt) +
    • +
    • Fix: + Ensure that JNDI names used for <lookup-name> entries + in web.xml and for lookup elements of + @Resource annotations specify a name with an explicit + java: namespace. (markt) +
    • +
    • Code: + Refactor the org.apache.naming package to reduce duplicate + code. Duplicate code identified by the Simian tool. (markt) +
    • +
    • Fix: + 50019: Add support for <lookup-name>. + Based on a patch by Gurkan Erdogdu. (markt) +
    • +
    • Add: + 51953: Add the RemoteCIDRFilter and + RemoteCIDRValve that can be used to allow/deny requests + based on IPv4 and/or IPv6 client address where the IP ranges are defined + using CIDR notation. Based on a patch by Francis Galiegue. (markt) +
    • +
    • Fix: + 62343: Make CORS filter defaults more secure. This is the fix + for CVE-2018-8014. (markt) +
    • +
    • Fix: + Ensure that the web application resources implementation does not + incorrectly cache results for resources that are only visible as class + loader resources. (markt) +
    • +
    • Fix: + Make all loggers associated with Tomcat provided Filters non-static to + ensure that log messages are not lost when a web application is + reloaded. (markt) +
    • +
    • Fix: + Correct the manifest for the annotations-api.jar. The JAR implements the + Common Annotations API 1.2 and the manifest should reflect that. (markt) +
    • +
    • Fix: + Switch to non-static loggers where there is a possibility of a logger + becoming associated with a web application class loader causing log + messages to be lost if the web application is stopped. (markt) +
    • +
    • Add: + 62389: Add the IPv6 loopback address to the default + internalProxies regular expression. Patch by Craig Andrews. + (markt) +
    • +
    • Fix: + In the RemoteIpValve and RemoteIpFilter, + correctly handle the case when the request passes through one or more + trustedProxies but no internalProxies. Based + on a patch by zhanhb. (markt) +
    • +
    • Fix: + Correct the logic in MBeanFactory.removeConnector() to + ensure that the correct Connector is removed when there are multiple + Connectors using different addresses but the same port. (markt) +
    • +
    • Fix: + Make JAASRealm mis-configuration more obvious by requiring + the authenticated Subject to include at least one Principal of a type + specified by userClassNames. (markt) +
    • +
    • Fix: + 62476: Use GMT timezone for the value of + Expires header as required by HTTP specification + (RFC 7231, 7234). (kkolinko) +
    • +
    +
    +

    Coyote

    +
      +
    • Fix: + Consistent exception propagation for NIO2 SSL close. (remm) +
    • +
    • Fix: + Log an error message if the AJP connector detects that the reverse proxy + is sending AJP messages that are too large for the configured + packetSize. (markt) +
    • +
    • Fix: + Relax Host validation by removing the requirement that the final + component of a FQDN must be alphabetic. (markt) +
    • +
    • Fix: + 62371: Improve logging of Host validation failures. (markt) +
    • +
    • Fix: + Add missing handshake timeout for NIO2. (remm) +
    • +
    • Fix: + Correctly handle a digest authorization header when the user name + contains an escaped character. (markt) +
    • +
    • Fix: + Correctly handle a digest authorization header when one of the hex + field values ends the header with in an invalid character. (markt) +
    • +
    • Fix: + Correctly handle an invalid quality value in an + Accept-Language header. (markt) +
    • +
    • Docs: + 62423: Fix SSL docs CRL attribute typo. (remm) +
    • +
    • Fix: + Improve IPv6 validation by ensuring that IPv4-Mapped IPv6 addresses do + not contain leading zeros in the IPv4 part. Based on a patch by Katya + Stoycheva. (markt) +
    • +
    • Fix: + Fix NullPointerException thrown from + replaceSystemProperties() when trying to log messages. (csutherl) +
    • +
    • Fix: + Avoid unnecessary processing of async timeouts. (markt) +
    • +
    +
    +

    Jasper

    +
      +
    • Add: + 50234: Add the capability to generate a web-fragment.xml file + to JspC. (markt) +
    • +
    • Fix: + 62080: Ensure that all reads of the current thread's context + class loader made by the UEL API and implementation are performed via a + PrivilegedAction to ensure that a + SecurityException is not triggered when running under a + SecurityManager. (mark) +
    • +
    • Fix: + 62350: Refactor + org.apache.jasper.runtime.BodyContentImpl so a + SecurityException is not thrown when running under a + SecurityManger and additional permissions are not required in the + catalina.policy file. This is a follow-up to the fix for + 43925. (kkolinko/markt) +
    • +
    • Fix: + Update web.xml, web-fragment.xml and web.xml extracts generated by JspC + to use the Servlet 3.1 version of the relevant schemas. (markt) +
    • +
    +
    +

    Cluster

    +
      +
    • Fix: + Remove duplicate calls when creating a replicated session to reduce the + time taken to create the session and thereby reduce the chances of a + subsequent session update message being ignored because the session does + not yet exist. (markt) +
    • +
    +
    +

    WebSocket

    +
      +
    • Fix: + When decoding of path parameter failed, make sure to throw + DecodeException instead of throwing + ArrayIndexOutOfBoundsException. (kfujino) +
    • +
    • Fix: + Enable host name verification when using TLS with the WebSocket client. + (markt) +
    • +
    +
    +

    Web applications

    + + + 62395: Clarify the meaning of the connector attribute + minSpareThreads in the documentation web application. + (markt) + + + Correct the documentation for the allowHostHeaderMismatch + attribute of the standard HTTP Connector implementations. (markt) + + +
    +

    Tribes

    +
      +
    • Fix: + Ensure that the correct default value is returned when retrieve unset + properties in McastService. (kfujino) +
    • +
    +
    +

    jdbc-pool

    +
      +
    • Fix: + When logValidationErrors is set to true, the connection + validation error is logged as SEVERE instead of + WARNING. (kfujino) +
    • +
    +
    +

    Other

    +
      +
    • Fix: + 62391: Remove references to javaw.exe as this + file is not required by Tomcat and the references prevent the use of the + Server JRE. (markt) +
    • +
    • Update: + Update the packaged version of the Tomcat Native Library to 1.2.17 to + pick up the latest Windows binaries built with APR 1.6.3 and OpenSSL + 1.0.2o. (markt) +
    • +
    • Update: + 62458: Update the internal fork of Commons Pool 2 to dfef97b + (2018-06-18) to pick up some bug fixes and enhancements. (markt) +
    • +
    • Update: + Update the internal fork of Commons DBCP 2 to 2.4.0. (markt) +
    • +
    +
    +

    2018-05-03 Tomcat 8.5.31 (markt)

    +

    Catalina

    +
      +
    • Fix: + 62263: Avoid a NullPointerException when the + RemoteIpValve processes a request for which no Context can + be found. (markt) +
    • +
    • Fix: + Fix a rare edge case that is unlikely to occur in real usage. This edge + case meant that writing long streams of UTF-8 characters to the HTTP + response that consisted almost entirely of surrogate pairs could result + in one surrogate pair being dropped. (markt) +
    • +
    • Fix: + Register MBean when DataSource Resource + type="javax.sql.XADataSource". Patch provided by Masafumi Miura. + (csutherl) +
    • +
    • Add: + Update the internal fork of Apache Commons BCEL to r1829827 to add early + access Java 11 support to the annotation scanning code. (markt) +
    • +
    • Fix: + 62297: Enable the CrawlerSessionManagerValve to + correctly handle bots that crawl multiple hosts and/or web applications + when the Valve is configured on a Host or an Engine. (fschumacher) +
    • +
    • Fix: + 62309: Fix a SecurityException when using JASPIC + under a SecurityManager when authentication is not + mandatory. (markt) +
    • +
    • Fix: + 62329: Correctly list resources in JAR files when directories + do not have dedicated entries. Patch provided by Meelis Müür. (markt) +
    • +
    • Add: + Collapse multiple leading / characters to a single + / in the return value of + HttpServletRequest#getContextPath() to avoid issues if the + value is used with HttpServletResponse#sendRedirect(). This + behaviour is enabled by default and configurable via the new Context + attribute allowMultipleLeadingForwardSlashInPath. (markt) +
    • +
    • Fix: + Improve handing of overflow in the UTF-8 decoder with supplementary + characters. (markt) +
    • +
    +
    +

    Coyote

    +
      +
    • Fix: + Correct off-by-one error in thread pool that allowed thread pools to + increase in size to one more than the configured limit. Patch provided + by usc. (markt) +
    • +
    • Fix: + Prevent unexpected TLS handshake failures caused by errors during a + previous handshake that were not correctly cleaned-up when using the NIO + or NIO2 connector with the OpenSSLImplementation. (markt) +
    • +
    • Add: + Enable strict validation of the provided host name and port for all + connectors. Requests with invalid host names and/or ports will be + rejected with a 400 response. (markt) +
    • +
    • Add: + 62273: Implement configuration options to work-around + specification non-compliant user agents (including all the major + browsers) that do not correctly %nn encode URI paths and query strings + as required by RFC 7230 and RFC 3986. (markt) +
    • +
    +
    +

    Jasper

    +
      +
    • Fix: + Enable ECJ version 4.7 and later to be used as a drop in replacement for + the ECJ version that ships with Apache Tomcat. (markt) +
    • +
    • Fix: + Enable Java 10 to be specified as a JSP source and/or target if a newer + ECJ version is used. (markt) +
    • +
    • Fix: + 62287: Do not rely on hash codes to test instances of + ValueExpressionImpl for equality. Patch provided by Mark + Struberg. (markt) +
    • +
    +
    +

    WebSocket

    +
      +
    • Fix: + 62301: Correct a regression in the fix for 61491 + that didn't correctly handle a final empty message part in all + circumstances when using PerMessageDeflate. (markt) +
    • +
    • Fix: + 62332: Ensure WebSocket connections are closed after an I/O + error is experienced reading from the client. (markt) +
    • +
    +
    +

    Other

    +
      +
    • Fix: + Avoid warning when running under Cygwin when the + JAVA_ENDORSED_DIRS environment variable is not set. Patch + provided by Zemian Deng. (markt) +
    • +
    +
    +

    2018-04-07 Tomcat 8.5.30 (markt)

    +

    Catalina

    +
      +
    • Fix: + 51195: Avoid a false positive report of a web application + memory leak by clearing ObjectStreamClass$Caches of classes + loaded by the web application when the web application is stopped. + (markt) +
    • +
    • Fix: + 52688: Add support for the maxDays attribute to + the AccessLogValve and ExtendedAccessLogValve. + This allows the maximum number of days for which rotated access logs + should be retained before deletion to be defined. (markt) +
    • +
    • Fix: + Ensure the MBean names for the SSLHostConfig and + SSLHostConfigCertificate are correctly formed when the + Connector is bound to a specific IP address. (markt) +
    • +
    • Fix: + 62168: When using the PersistentManager honor a + value of -1 for minIdleSwap and do not swap + out sessions to keep the number of active sessions under + maxActive. Patch provided by Holger Sunke. (markt) +
    • +
    • Fix: + 62172: Improve Javadoc for + org.apache.catalina.startup.Constants and ensure that the + constants are correctly used. (markt) +
    • +
    • Fix: + 62175: Avoid infinite recursion, when trying to validate + a session while loading it with PersistentManager. + (fschumacher) +
    • +
    • Fix: + Ensure that NamingContextListener instances are only + notified once of property changes on the associated naming resources. + (markt) +
    • +
    • Add: + Add LoadBalancerDrainingValve, a Valve designed to reduce the amount of + time required for a node to drain its authenticated users. (schultz) +
    • +
    • Add: + 62224: Disable the forkJoinCommonPoolProtection + of the JreMemoryLeakPreventionListener when running on Java + 9 and above since the underlying JRE bug has been fixed. (markt) +
    • +
    +
    +

    Coyote

    +
      +
    • Fix: + Avoid potential loop in APR/Native poller. (markt) +
    • +
    • Fix: + Ensure streams that are received but not processed are excluded from the + tracking of maximum ID of processed streams. (markt) +
    • +
    • Fix: + Refactor the check for a paused connector to consistently prevent new + streams from being created after the connector has been paused. (markt) +
    • +
    • Fix: + Improve debug logging for HTTP/2 pushed streams. (markt) +
    • +
    • Fix: + The OpenSSL engine SSL session will now ignore invalid accesses. (remm) +
    • +
    • Fix: + 62177: Correct two protocol errors with HTTP/2 + PUSH_PROMISE frames. Firstly, the HTTP/2 protocol only + permits pushes to be sent on peer initiated requests. Secondly, pushes + must be sent in order of increasing stream ID. These restriction were + not being enforced leading to protocol errors at the client. (markt) +
    • +
    +
    +

    Web applications

    +
      +
    • Add: + Add document for FragmentationInterceptor. (kfujino) +
    • +
    • Add: + Document how the roles for an authenticated user are determined when the + CombinedRealm is used. (markt) +
    • +
    +
    +

    Tribes

    +
      +
    • Fix: + Add JMX support for FragmentationInterceptor in order to + prevent warning of startup. (kfujino) +
    • +
    +
    +

    jdbc-pool

    +
      +
    • Fix: + Ensure that SQLWarning has been cleared when connection + returns to the pool. (kfujino) +
    • +
    • Add: + Enable clearing of SQLWarning via JMX. (kfujino) +
    • +
    • Fix: + Ensure that parameters have been cleared when + PreparedStatement and/or CallableStatement are + cached. (kfujino) +
    • +
    • Fix: + Enable PoolCleaner to be started even if validationQuery + is not set. (kfujino) +
    • +
    +
    +

    Other

    +
      +
    • Fix: + 62164: Switch the build script to use TLS for downloads from + SourceForge and Maven Central to avoid failures due to HTTP to HTTPS + redirects. (markt) +
    • +
    • Add: + Always report the OS's umask when launching the JVM. (schultz) +
    • +
    +
    +

    2018-03-08 Tomcat 8.5.29 (markt)

    +

    Catalina

    +
      +
    • Fix: + Minor optimization when calling class transformers. (rjung) +
    • +
    • Fix: + Prevent Tomcat from applying gzip compression to content that is already + compressed with brotli compression. Based on a patch provided by burka. + (markt) +
    • +
    • Fix: + 62090: Null container names are not allowed. (remm) +
    • +
    • Fix: + 62104: Fix programmatic login regression as the + NonLoginAuthenticator has to be set for it to work (if no login method + is specified). (remm) +
    • +
    • Fix: + 62117: Improve error message in catalina.sh when + calling kill -0 <pid> fails. Based on a suggestion + from Mark Morschhaeuser. (markt) +
    • +
    • Fix: + 62118: Correctly create a JNDI ServiceRef using + the specified interface rather than the concrete type. Based on a + suggestion by Ángel Álvarez Páscua. (markt) +
    • +
    • Fix: + Fix for RequestDumperFilter log attribute. Patch provided + by Kirill Romanov via Github. (violetagg) +
    • +
    • Fix: + 62123: Avoid ConcurrentModificationException + when attempting to clean up application triggered RMI memory leaks on + web application stop. (markt) +
    • +
    • Fix: + Correct a regression in the fix for 60276 that meant that + compression was applied to all MIME types. Patch provided by Stefan + Knoblich. (markt) +
    • +
    +
    +

    Coyote

    +
      +
    • Fix: + Add minor HPACK fixes, based on fixes by Stuart Douglas. (remm) +
    • +
    • Fix: + 61751: Follow up fix so that OpenSSL engine returns + underflow when unwrapping if no bytes were produced and the input is + empty. (remm) +
    • +
    • Fix: + Minor OpenSSL engine cleanups. (remm) +
    • +
    • Fix: + NIO SSL handshake should throw an exception on overflow status, like + NIO2 SSL. (remm) +
    • +
    +
    +

    Web applications

    +
      +
    • Add: + 48672: Add documentation for the Host Manager web + application. Patch provided by Marek Czernek. (markt) +
    • +
    • Add: + Work-around a known, non-specification compliant behaviour in some + versions of IE that can allow XSS when the Manager application generates + a plain text response. Based on a suggestion from Muthukumar Marikani. + (markt) +
    • +
    +
    +

    Other

    +
      +
    • Update: + Update the build script so MD5 hashes are no longer generated for + releases as per the change in the ASF distribution policy. (markt) +
    • +
    +
    +

    2018-02-11 Tomcat 8.5.28 (markt)

    +

    Catalina

    +
      +
    • Fix: + Prevent a stack trace being written to standard out when running on Java + 10 due to changes in the LogManager implementation. (markt) +
    • +
    • Fix: + 62000: When a JNDI reference cannot be resolved, ensure that + the root cause exception is reported rather than swallowed. (markt) +
    • +
    • Fix: + 62036: When caching an authenticated user Principal in the + session when the web application is configured with the + NonLoginAuthenticator, cache the internal Principal object + rather than the user facing Principal object as Tomcat requires the + internal object to correctly process later authorization checks. (markt) +
    • +
    • Fix: + Avoid duplicate load attempts if one has been made already. (remm) +
    • +
    • Fix: + Avoid NPE in ThreadLocalLeakPreventionListener if there is no Engine. + (remm) +
    • +
    • Fix: + 62067: Correctly apply security constraints mapped to the + context root using a URL pattern of "". (markt) +
    • +
    • Fix: + When using Tomcat embedded, only perform Authenticator configuration + once during web application start. (markt) +
    • +
    • Fix: + Process all ServletSecurity annotations at web application + start rather than at servlet load time to ensure constraints are applied + consistently. (markt) +
    • +
    +
    +

    Coyote

    +
      +
    • Fix: + 61751: Fix truncated request input streams when using NIO2 + with TLS. (markt) +
    • +
    • Fix: + 62023: Log error reporting multiple SSLHostConfig elements + when using the APR Connector instead of crashing Tomcat. (csutherl) +
    • +
    • Fix: + 62032: Fix NullPointerException when certificateFile is not + defined on an SSLHostConfig and unify the behavior when a + certificateFile is defined but the file does not exist for both + JKS and PEM file types. (csutherl) +
    • +
    +
    +

    WebSocket

    +
      +
    • Fix: + 62024: When closing a connection with an abnormal close, + close the socket immediately rather than waiting for a close message + from the client that may never arrive. (markt) +
    • +
    +
    +

    Webapps

    +
      +
    • Fix: + 62049: Fix missing class from manager 404 JSP error page. + (remm) +
    • +
    +
    +

    jdbc-pool

    +
      +
    • Add: + Enhance the JMX support for jdbc-pool in order to expose + PooledConnection and JdbcInterceptors. + (kfujino) +
    • +
    • Add: + Add MBean for PooledConnection. (kfujino) +
    • +
    • Add: + 62011: Add MBean for StatementCache. (kfujino) +
    • +
    • Add: + Expose the cache size for each connection via JMX in + StatementCache. (kfujino) +
    • +
    • Add: + Add MBean for ResetAbandonedTimer. (kfujino) +
    • +
    +
    +

    Other

    +
      +
    • Update: + Update the NSIS Installer used to build the Windows installer to version + 3.03. (kkolinko) +
    • +
    +
    +

    2018-01-22 Tomcat 8.5.27 (markt)

    +

    Catalina

    +
      +
    • Fix: + Correct a regression in the previous fix for 61916 that meant + that any call to addHeader() would have been replaced with + a call to setHeader() for all requests mapped to the + AddDefaultCharsetFilter. (markt) +
    • +
    +
    +

    Coyote

    +
      +
    • Fix: + 61993: Improve handling for ByteChunk and + CharChunk instances that grow close to the maximum size + allowed by the JRE. (markt) +
    • +
    +
    +

    Jasper

    +
      +
    • Add: + 43925: Add a new system property + (org.apache.jasper.runtime.BodyContentImpl.BUFFER_SIZE) to + control the size of the buffer used by Jasper when buffering tag bodies. + (markt) +
    • +
    +
    +

    Web applications

    +
      +
    • Fix: + 62006: Document the new JvmOptions9 command line + parameter for tomcat8.exe. (markt) +
    • +
    +
    +

    not released Tomcat 8.5.26 (markt)

    +

    Catalina

    +
      +
    • Fix: + Correct Javadoc errors in release build. +
    • +
    +
    +

    not released Tomcat 8.5.25 (markt)

    +

    Catalina

    +
      +
    • Fix: + 47214: Use a loop to preload anonymous inner classes + when running under a SecurityManager, to be safe for + future changes in the code or using a different compiler. (kkolinko) +
    • +
    • Add: + 57619: Implement a small optimisation to how JAR URLs are + processed to reduce the storage of duplicate String objects in memory. + Patch provided by Dmitri Blinov. (markt) +
    • +
    • Fix: + Add some missing NPEs to ServletContext. (remm) +
    • +
    • Fix: + 61916: Extend the AddDefaultCharsetFilter to add + a character set when the content type is set via + setHeader() or addHeader() as well as when it + is set via setContentType(). (markt) +
    • +
    • Fix: + 61999: maxSavePostSize set to 0 should disable saving POST + data during authentication. (remm) +
    • +
    +
    +

    Coyote

    +
      +
    • Add: + 60276: Implement GZIP compression support for responses + served over HTTP/2. (markt) +
    • +
    • Fix: + Do not call onDataAvailable without any data to read. (remm) +
    • +
    • Fix: + 61886: Log errors on non-container threads at + DEBUG rather than INFO. The exception will be + made available to the application via the asynchronous error handling + mechanism. (markt) +
    • +
    • Fix: + 61914: Possible NPE with Java 9 when creating a SSL engine. + Patch submitted by Evgenij Ryazanov. (remm) +
    • +
    • Fix: + 61918: Fix connectionLimitLatch counting when closing an + already closed socket. Based on a patch by Ryan Fong. (remm) +
    • +
    • Add: + Add support for the OpenSSL ARIA ciphers to the OpenSSL to JSSE + cipher mapping. (markt) +
    • +
    • Fix: + 61932: Allow a call to AsyncContext.dispatch() + to terminate non-blocking I/O. (markt) +
    • +
    • Fix: + 61948: Improve the handling of malformed ClientHello messages + in the code that extracts the SNI information from a TLS handshake for + the JSSE based NIO and NIO2 connectors. (markt) +
    • +
    • Fix: + Fix NIO2 handshaking with a full input buffer. (remm) +
    • +
    • Add: + Return a simple, plain text error message if a client attempts to make a + plain text HTTP connection to a TLS enabled NIO or NIO2 Connector. + (markt) +
    • +
    • Fix: + Correctly handle EOF when ServletInputStream.isReady() is + called. (markt) +
    • +
    +
    +

    Jasper

    +
      +
    • Fix: + 61854: When using sets and/or maps in EL expressions, ensure + that Jasper correctly parses the expression. Patch provided by Ricardo + Martin Camarero. (markt) +
    • +
    • Fix: + Improve the handling of methods with varargs in EL expressions. In + particular, the calling of a varargs method with no parameters now works + correctly. Based on a patch by Nitkalya (Ing) Wiriyanuparb. (markt) +
    • +
    +
    +

    Web applications

    +
      +
    • Fix: + Remove the Servlet 4.0 early preview example from the examples web + application as the early preview is now deprecated in favour of Tomcat + 9 which provides a full Servlet 4.0 implementation. (markt) +
    • +
    • Add: + 61223: Add the mbeans-descriptors.dtd file to the custom + MBean documentation so users have a reference to use when constructing + mbeans-descriptors.xml files for custom components. (markt) +
    • +
    • Add: + 61566: Expose the currently in use certificate chain and list + of trusted certificates for all virtual hosts configured using the JSSE + style (keystore) TLS configuration via the Manager web application. + (markt) +
    • +
    • Fix: + Partial fix for 61886. Ensure that multiple threads do not + attempt to complete the AsyncContext if an I/O error occurs + in the stock ticker example Servlet. (markt) +
    • +
    • Fix: + 61886: Prevent ConcurrentModificationException + when running the asynchronous stock ticker in the examples web + application. (markt) +
    • +
    • Fix: + 61886: Prevent NullPointerException and other + errors if the stock ticker example is running when the examples web + application is stopped. (markt) +
    • +
    • Fix: + 61910: Clarify the meaning of the allowLinking + option in the documentation web application. (markt) +
    • +
    • Add: + Add OCSP configuration information to the SSL How-To. Patch provided by + Marek Czernek. (markt) +
    • +
    +
    +

    jdbc-pool

    +
      +
    • Fix: + 61312: Prevent NullPointerException when using + the statement cache of connection that has been closed. (kfujino) +
    • +
    +
    +

    Other

    +
      +
    • Fix: + Add an additional system property for the system property replacement. + (remm) +
    • +
    • Fix: + Add missing SHA-512 hash for release artifacts to the build script. + (markt) +
    • +
    • Update: + Update the internal fork of Commons Pool 2 to 2.4.3. (markt) +
    • +
    • Update: + Update the internal fork of Commons DBCP 2 to 8a71764 (2017-10-18) to + pick up some bug fixes and enhancements. (markt) +
    • +
    • Update: + Update the internal fork of Commons FileUpload to 6c00d57 (2017-11-23) + to pick up some code clean-up. (markt) +
    • +
    • Update: + Update the internal fork of Commons Codec to r1817136 to pick up some + code clean-up. (markt) +
    • +
    • Fix: + The native source bundles (for Commons Daemon and Tomcat Native) are no + longer copied to the bin directory for the deploy target. They are now + only copied to the bin directory for the release target. (markt) +
    • +
    +
    +

    2017-11-30 Tomcat 8.5.24 (markt)

    +

    Catalina

    +
      +
    • Add: + When running under Java 9 or later, and the + urlCacheProtection option of the + JreMemoryLeakPreventionListener is enabled, use the API + added in Java 9 to only disable the caching for JAR URL connections. + (markt) +
    • +
    • Fix: + Fix possible SecurityException when using TLS related + request attributes. (markt) +
    • +
    • Fix: + 61597: Extend the StandardJarScanner to scan + JARs on the module path when running on Java 9 and class path scanning + is enabled. (markt) +
    • +
    • Fix: + 61601: Add support for multi-release JARs in JAR scanning and + web application class loading. (markt) +
    • +
    • Fix: + 61681: Allow HTTP/2 push when using request wrapping. (remm) +
    • +
    • Add: + Provide the SessionInitializerFilter that can be used to + ensure that an HTTP session exists when initiating a WebSocket + connection. Patch provided by isapir. (markt) +
    • +
    • Fix: + 61682: When re-prioritising HTTP/2 streams, ensure that both + parent and children fields are correctly updated to avoid a possible + StackOverflowError. (markt) +
    • +
    • Fix: + Improve concurrency by reducing the scope of the synchronisation for + javax.security.auth.message.config.AuthConfigFactory in the + JASPIC API implementation. Based on a patch by Pavan Kumar. (markt) +
    • +
    • Fix: + Avoid a possible NullPointerException when timing out + AsyncContext instances during shut down. (markt) +
    • +
    • Fix: + 61777: Avoid a NullPointerException when + detaching a JASPIC RegistrationListener. Patch provided by + Lazar. (markt) +
    • +
    • Fix: + 61778: Correct the return value when detaching a JASPIC + RegistrationListener. Patch provided by Lazar. (markt) +
    • +
    • Fix: + 61779: Avoid a NullPointerException when a + null RegistrationListener is passed to + AuthConfigFactory.getConfigProvider(). Patch provided by + Lazar. (markt) +
    • +
    • Fix: + 61780: Only include the default JASPIC registration ID in the + return value for a call to + AuthConfigFactory.getRegistrationIDs() if a + RegistrationContext has been registered using the default + registration ID. Patch provided by Lazar. (markt) +
    • +
    • Fix: + 61781: Enable JASPIC provider registrations to be persisted + when the layer and/or application context are null. Patch + provided by Lazar. (markt) +
    • +
    • Fix: + 61782: When calling + AuthConfigFactory.doRegisterConfigProvider() and the + requested JASPIC config provider class is found by the web application + class loader, do not attempt to load the class with the class loader + that loaded the JASPIC API. Patch provided by Lazar. (markt) +
    • +
    • Fix: + 61783: When calling + AuthConfigFactory.removeRegistration() and the registration + is persistent, it should be removed from the persistent store. Patch + provided by Lazar. (markt) +
    • +
    • Fix: + 61784: Correctly handle the case when + AuthConfigFactoryImpl.registerConfigProvider() is called + with a provider name of null. Patch provided by Lazar. + (markt) +
    • +
    • Add: + 61795: Add a property to the Authenticator + implementations to enable a custom JASPIC CallbackHandler + to be specified. Patch provided by Lazar. (markt) +
    • +
    +
    +

    Coyote

    +
      +
    • Add: + Enable ALPN and also, therefore, HTTP/2 for the NIO and NIO2 HTTP + connectors when using the JSSE implementation for TLS when running on + Java 9. (markt) +
    • +
    • Add: + 60762: Add the ability to make changes to the TLS + configuration of a connector at runtime without having to restart the + Connector. (markt) +
    • +
    • Fix: + 61568: Avoid a potential SecurityException when + using the NIO2 connector and a new thread is added to the pool. (markt) +
    • +
    • Fix: + 61583: Correct a further regression in the fix to enable the + use of Java key stores that contained multiple keys that did not all + have the same password. This fixes PKCS11 key store handling with + multiple keys selected with an alias. (markt) +
    • +
    • Fix: + Reduce default HTTP/2 stream concurrent execution within a connection + from 200 to 20. (remm) +
    • +
    • Fix: + 61668: Avoid a possible NPE when calling + AbstractHttp11Protocol.getSSLProtocol(). (markt) +
    • +
    • Fix: + 61673: Avoid a possible + ConcurrentModificationException when working with the + streams associated with a connection. (markt) +
    • +
    • Fix: + 61719: Avoid possible NPE calling + InputStream.setReadListener with HTTP/2. (remm) +
    • +
    • Fix: + 61736: Improve performance of NIO connector when clients + leave large time gaps between network packets. Patch provided by Zilong + Song. (markt) +
    • +
    • Fix: + 61740: Correct an off-by-one error in the Hpack header index + validation that caused intermittent request failures when using HTTP/2. + (markt) +
    • +
    +
    +

    Jasper

    +
      +
    • Fix: + 61816: Invalid expressions in attribute values or template + text should trigger a translation (compile time) error, not a run time + error. (markt) +
    • +
    +
    +

    WebSocket

    +
      +
    • Fix: + 61604: Add support for authentication in the websocket + client. Patch submitted by J Fernandez. (remm) +
    • +
    +
    +

    Web applications

    +
      +
    • Fix: + Enable Javadoc to be built with Java 9. (markt) +
    • +
    • Fix: + 61603: Add XML filtering for the status servlet output where + needed. (remm) +
    • +
    • Fix: + Correct the description of how the CGI servlet maps a request to a + script in the CGI How-To. (markt) +
    • +
    +
    +

    Tribes

    +
      +
    • Fix: + Fix incorrect behavior that attempts to resend channel messages more + than the actual setting value of maxRetryAttempts. + (kfujino) +
    • +
    • Fix: + Ensure that the remaining Sender can send channel messages by avoiding + unintended ChannelException caused by comparing the number + of failed members and the number of remaining Senders. (kfujino) +
    • +
    • Fix: + Ensure that remaining SelectionKeys that were not handled by throwing a + ChannelException during SelectionKey processing are + handled. (kfujino) +
    • +
    +
    +

    Other

    +
      +
    • Fix: + Improve the fix for 61439 and exclude the JPA, JAX-WS and EJB + annotations completely from the Tomcat distributions. (markt) +
    • +
    • Fix: + Improve handling of endorsed directories. The endorsed directory + mechanism will only be used if the JAVA_ENDORSED_DIRS + system property is explicitly set or if + $CATALINA_HOME/endorsed exists. When running on Java 9, any + such attempted use of the endorsed directory mechanism will trigger an + error and Tomcat will fail to start. (rjung) +
    • +
    • Code: + Refactoring in preparation for Java 9. Refactor to avoid using some + methods that will be deprecated in Java 9 onwards. (markt) +
    • +
    • Add: + 51496: When using the Windows installer, check if the + requested service name already exists and, if it does, prompt the user + to select an alternative service name. Patch provided by Ralph + Plawetzki. (markt) +
    • +
    • Fix: + Add necessary Java 9 configuration options to the startup scripts to + prevent warnings being generated on web application stop. (markt) +
    • +
    • Fix: + 61590: Enable service.bat to recognise when + JAVA_HOME is configured for a Java 9 JDK. (markt) +
    • +
    • Fix: + 61598: Update the Windows installer to search the new (as of + Java 9) registry locations when looking for a JRE. (markt) +
    • +
    • Add: + Add generation of a SHA-512 hash for release artifacts to the build + script. (markt) +
    • +
    • Fix: + 61658: Update MIME mappings for fonts to use + font/* as per RFC8081. (markt) +
    • +
    • Update: + Update the packaged version of the Tomcat Native Library to 1.2.16 to + pick up the latest Windows binaries built with APR 1.6.3 and OpenSSL + 1.0.2m. (markt) +
    • +
    • Update: + Update the NSIS Installer used to build the Windows installer to version + 3.02.1. (kkolinko) +
    • +
    • Update: + Update the Windows installer to use "The Apache Software Foundation" as + the Publisher when Tomcat is displayed in the list of installed + applications in Microsoft Windows. (kkolinko) +
    • +
    • Fix: + 61803: Remove outdated SSL information from the Security + documentation. (remm) +
    • +
    +
    +

    2017-10-01 Tomcat 8.5.23 (markt)

    +

    Catalina

    +
      +
    • Fix: + Use the correct path when loading the JVM logging.properties + file for Java 9. (rjung) +
    • +
    • Fix: + Add additional validation to the resource handling required to fix + CVE-2017-12617 on Windows. The checks were being performed elsewhere but + adding them to the resource handling ensures that the checks are always + performed. (markt) +
    • +
    • Fix: + 61554: Exclude test files in unusual encodings and markdown + files intended for display in GitHub from RAT analysis. Patch provided + by Chris Thistlethwaite. (markt) +
    • +
    +
    +

    Other

    +
      +
    • Fix: + 61563: Correct typos in Spanish translation. Patch provided by + Gonzalo Vásquez. (csutherl) +
    • +
    +
    +

    not released Tomcat 8.5.22 (markt)

    +

    Catalina

    +
      +
    • Fix: + 60963: Add ExtractingRoot, a new + WebResourceRoot implementation that extracts JARs to the + work directory for improved performance when deploying packed WAR files. + (markt) +
    • +
    • Add: + Add an option to reject requests that contain HTTP headers with invalid + (non-token) header names with a 400 response. (markt) +
    • +
    • Fix: + 61542: Fix CVE-2017-12617 and prevent JSPs from being + uploaded via a specially crafted request when HTTP PUT was enabled. + (markt) +
    • +
    • Fix: + Implement the requirements of RFC 7230 (and RFC 2616) that HTTP/1.1 + requests must include a Host header and any request that + does not must be rejected with a 400 response. (markt) +
    • +
    • Fix: + Implement the requirements of RFC 7230 that any HTTP/1.1 request that + specifies a host in the request line, must specify the same host in the + Host header and that any such request that does not, must + be rejected with a 400 response. This check is optional but disabled by + default. It may be enabled with the + allowHostHeaderMismatch attribute of the Connector. (markt) +
    • +
    • Fix: + Implement the requirements of RFC 7230 that any HTTP/1.1 request that + contains multiple Host headers is rejected with a 400 + response. (markt) +
    • +
    +
    +

    Coyote

    +
      +
    • Update: + Add a way to set the property source in embedded mode. (remm) +
    • +
    • Fix: + 61557: Correct a further regression in the fix to enable the + use of Java key stores that contain multiple keys that do not all have + the same password. The regression broke support for some FIPS compliant + key stores. (markt) +
    • +
    +
    +

    jdbc-pool

    +
      +
    • Fix: + 61545: Correctly handle invocations of methods defined in the + PooledConnection interface when using pooled XA + connections. Patch provided by Nils Winkler. (markt) +
    • +
    +
    +

    Other

    +
      +
    • Fix: + Update fix for 59904 so that values less than zero are accepted + instead of throwing a NegativeArraySizeException. (remm) +
    • +
    +
    +

    2017-09-19 Tomcat 8.5.21 (markt)

    +

    Catalina

    +
      +
    • Fix: + Before generating an error page in the ErrorReportValve, + check to see if I/O is still permitted for the associated connection + before generating the error page so that the page generation can be + skipped if the page is never going to be sent. (markt) +
    • +
    • Add: + 61189: Add the ability to set environment variables for + individual CGI scripts. Based on a patch by jm009. (markt) +
    • +
    • Fix: + 61210: When running under a SecurityManager, do not print a + warning about not being able to read a logging configuration file when + that file does not exist. (markt) +
    • +
    • Add: + 61280: Add RFC 7617 support to the + BasicAuthenticator. Note that the default configuration + does not change the existing behaviour. (markt) +
    • +
    • Fix: + 61424: Avoid a possible StackOverflowError when + running under a SecurityManager and using + Subject.doAs(). (markt) +
    • +
    +
    +

    Coyote

    +
      +
    • Update: + The minimum required Tomcat Native version has been increased to 1.2.14. + This version includes a new API needed for correct client certificate + support when using a Java connector with OpenSSL TLS implementation and + support for the SSL_CONF OpenSSL API. (rjung) +
    • +
    • Add: + Add support for the OpenSSL SSL_CONF API when using + TLS with OpenSSL implementation. It can be used by adding + OpenSSLConf elements underneath SSLHostConfig. + The new element contains a list of OpenSSLConfCmd elements, + each with the attributes name and value. + (rjung) +
    • +
    • Fix: + When using a Java connector in combination with the OpenSSL TLS + implementation, do not configure each SSL connection object via + the OpenSSLEngine. For OpenSSL the SSL object inherits its + settings from the SSL_CTX which we have already configured. + (rjung) +
    • +
    • Fix: + When using JSSE TLS configuration with the OpenSSL implementation and + client certificates: include client CA subjects in the TLS handshake + so that the client can choose an appropriate client certificate to + present. (rjung) +
    • +
    • Fix: + If an invalid option is specified for the + certificateVerification attribute of an + SSLHostConfig element, treat it as required + which is the most secure / restrictive option in addition to reporting + the configuration error. (markt) +
    • +
    • Fix: + Improve the handling of client disconnections during the TLS + renegotiation handshake. (markt) +
    • +
    • Fix: + Prevent exceptions being thrown during normal shutdown of NIO + connections. This enables TLS connections to close cleanly. (markt) +
    • +
    • Fix: + Fix possible race condition when setting IO listeners on an upgraded + connection. (remm) +
    • +
    • Fix: + 48655: Enable Tomcat to shutdown cleanly when using sendfile, + the APR/native connector and a multi-part download is in progress. + (markt) +
    • +
    • Fix: + 58244: Handle the case when OpenSSL resumes a TLS session + using a ticket and the full client certificate chain is not available. + In this case the client certificate without the chain will be presented + to the application. (markt) +
    • +
    • Fix: + Improve the warning message when JSSE and OpenSSL configuration styles + are mixed on the same SSLHostConfig. (markt) +
    • +
    • Fix: + 61415: Fix TLS renegotiation with OpenSSL based connections + and session caching. (markt) +
    • +
    • Fix: + Delay checking that the configured attributes for an + SSLHostConfig instance are consistent with the configured + SSL implementation until Connector start to avoid incorrect + warnings when the SSL implementation changes during initialisation. + (markt) +
    • +
    • Fix: + 61450: Fix default key alias algorithm. (remm) +
    • +
    • Fix: + 61451: Correct a regression in the fix to enable the use of + Java key stores that contained multiple keys that did not all have the + same password. The regression broke support for any key store that did + not store keys in PKCS #8 format such as hardware key stores and Windows + key stores. (markt) +
    • +
    +
    +

    WebSocket

    +
      +
    • Fix: + 60523: Reduce the number of packets used to send WebSocket + messages by not flushing between the header and the payload when the + two are written together. (markt) +
    • +
    • Fix: + 61491: When using the permessage-deflate + extension, correctly handle the sending of empty messages after + non-empty messages to avoid the IllegalArgumentException. + (markt) +
    • +
    +
    +

    Web applications

    +
      +
    • Fix: + Show connector cipher list in the manager web application in the + correct cipher order. (rjung) +
    • +
    +
    +

    Tribes

    +
      +
    • Fix: + To avoid unexpected session timeout notification from backup session, + update the access time when receiving the map member notification + message. (kfujino) +
    • +
    • Fix: + Add member info to the log message when the failure detection check + fails in TcpFailureDetector. (kfujino) +
    • +
    • Fix: + Avoid Ping timeout until the added map member by receiving + MSG_START message is completely started. (kfujino) +
    • +
    • Fix: + When sending a channel message, make sure that the Sender has connected. + (kfujino) +
    • +
    • Fix: + Correct the backup node selection logic that node 0 is returned twice + consecutively. (kfujino) +
    • +
    • Fix: + Fix race condition of responseMap in + RpcChannel. (kfujino) +
    • +
    +
    +

    jdbc-pool

    +
      +
    • Fix: + 61391: Ensure that failed queries are logged if the + SlowQueryReport interceptor is configured to do so and the + connection has been abandoned. Patch provided by Craig Webb. (markt) +
    • +
    • Fix: + 61425: Ensure that transaction of idle connection has + terminated when the testWhileIdle is set to + true and defaultAutoCommit is set to + false. Patch provided by WangZheng. (kfujino) +
    • +
    +
    +

    Other

    +
      +
    • Fix: + 61439: Remove the Java Annotation API classes from + tomcat-embed-core.jar and package them in a separate JAR in the + embedded distribution to provide end users with greater flexibility to + handle potential conflicts with the JRE and/or other JARs. (markt) +
    • +
    • Fix: + 61441: Improve the detection of JAVA_HOME by the + daemon.sh script when running on a platform where Java has + been installed from an RPM. (rjung) +
    • +
    • Update: + Update the packaged version of the Tomcat Native Library to 1.2.14 to + pick up the latest Windows binaries built with APR 1.6.2 and OpenSSL + 1.0.2l. (markt) +
    • +
    • Update: + 61599: Update to Commons Daemon 1.1.0 for improved Java 9 + support. (markt) +
    • +
    +
    +

    2017-08-08 Tomcat 8.5.20 (markt)

    +

    Catalina

    +
      +
    • Fix: + Revert the fix for 49464 since it continued to trigger + regressions. (markt) +
    • +
    • Fix: + Correct a bug in the PushBuilder implementation that + meant push URLs containing %nn sequences were not correctly + decoded. Identified by FindBugs. (markt) +
    • +
    • Add: + 61164: Add support for the %X pattern in the + AccessLogValve that reports the connection status at the + end of the request. Patch provided by Zemian Deng. (markt) +
    • +
    • Fix: + 61351: Correctly handle %nn decoding of URL patterns in + web.xml and similar locations that may legitimately contain characters + that are not permitted by RFC 3986. (markt) +
    • +
    • Add: + 61366: Add a new attribute, localDataSource, to + the JDBCStore that allows the Store to be configured to use + a DataSource defined by the web application rather than the default of + using a globally defined DataSource. Patch provided by Jonathan + Horowitz. (markt) +
    • +
    +
    +

    Coyote

    +
      +
    • Fix: + 61086: Ensure to explicitly signal an empty request body for + HTTP 205 responses. Additional fix to r1795278. Based on a patch + provided by Alexandr Saperov. (violetagg) +
    • +
    • Update: + 61345: Add a server listener that can be used to do system + property replacement from the property source configured in the + digester. (remm) +
    • +
    • Add: + Add additional logging to record problems that occur while waiting for + the NIO pollers to stop during the Connector stop process. (markt) +
    • +
    +
    +

    Jasper

    +
      +
    • Fix: + 61364: Ensure that files are closed after detecting encoding + of JSPs so that files do not remain locked by the file system. (markt) +
    • +
    +
    +

    WebSocket

    +
      +
    • Add: + 57767: Add support to the WebSocket client for following + redirects when attempting to establish a WebSocket connection. Patch + provided by J Fernandez. (markt) +
    • +
    +
    +

    2017-07-28 Tomcat 8.5.19 (markt)

    +

    Catalina

    +
      +
    • Fix: + Performance improvements for service loader look-ups (and look-ups of + other class loader resources) when the web application is deployed in a + packed WAR file. (markt) +
    • +
    • Fix: + 61253: Add warn message when Digester.updateAttributes + throws an exception instead of ignoring it. (csutherl) +
    • +
    • Fix: + Correct a further regression in the fix for 49464 that could + cause an byte order mark character to appear at the start of content + included by the DefaultServlet. (markt) +
    • +
    • Fix: + 61313: Make the read timeout configurable in the + JNDIRealm and ensure that a read timeout will result in an + attempt to fail over to the alternateURL. Based on patches by Peter + Maloney and Felix Schumacher. (markt) +
    • +
    +
    +

    Web applications

    +
      +
    • Fix: + Correct the documentation for how StandardRoot is + configured. (markt) +
    • +
    +
    +

    Other

    +
      +
    • Fix: + 61316: Fix corruption of UTF-16 encoded source files in + released source distributions. (markt) +
    • +
    +
    +

    not released Tomcat 8.5.18 (markt)

    +

    Catalina

    +
      +
    • Fix: + 61232: When log rotation is disabled only one separator will + be used when generating the log file name. For example if the prefix is + catalina. and the suffix is .log then the log + file name will be catalina.log instead of + catalina..log. Patch provided by Katya Stoycheva. + (violetagg) +
    • +
    • Fix: + 61264: Correct a regression in the refactoring to use + Charset rather than String to store request + character encoding that prevented getReader() throwing an + UnsupportedEncodingException if the user agent specifies + an unsupported character encoding. (markt) +
    • +
    • Fix: + Correct a regression in the fix for 49464 that could cause an + incorrect Content-Length header to be sent by the + DefaultServlet if the encoding of a static is not + consistent with the encoding of the response. (markt) +
    • +
    +
    +

    Coyote

    +
      +
    • Fix: + Enable TLS connectors to use Java key stores that contain multiple keys + where each key has a separate password. Based on a patch by Frank + Taffelt. (markt) +
    • +
    • Fix: + Improve the handling of HTTP/2 stream resets due to excessive headers + when a continuation frame is used. (markt) +
    • +
    +
    +

    Jasper

    +
      +
    • Add: + 53031: Add support for the fork option when + compiling JSPs with the Jasper Ant task and javac. (markt) +
    • +
    +
    +

    Other

    +
      +
    • Add: + 52791: Add the ability to set the defaults used by the + Windows installer from a configuration file. Patch provided by Sandra + Madden. (markt) +
    • +
    +
    +

    not released Tomcat 8.5.17 (markt)

    +

    Catalina

    +
      +
    • Fix: + 49464: Improve the Default Servlet's handling of static files + when the file encoding is not compatible with the required response + encoding. (markt) +
    • +
    • Fix: + 61214: Remove deleted attribute servlets from + the Context MBean description. Patch provided by Alexis Hassler. (markt) +
    • +
    • Fix: + 61215: Correctly define addConnectorPort and + invalidAuthenticationWhenDeny in the + mbean-descriptors.xml file for the + org.apache.catalina.valves package so that the attributes + are accessible via JMX. (markt) +
    • +
    • Fix: + Make asynchronous error handling more robust. In particular ensure that + onError() is called for any registered + AsyncListeners after an I/O error on a non-container + thread. (markt) +
    • +
    • Fix: + Additional permission for deleting files is granted to JULI as it is + required by FileHandler when running under a Security Manager. The + thread that cleans the log files is marked as daemon thread. + (violetagg) +
    • +
    • Fix: + 61229: Correct a regression in 8.5.15 that broke WebDAV + handling for resources with names that included a & + character. (markt) +
    • +
    +
    +

    Coyote

    +
      +
    • Fix: + Restore the ability to configure support for SSLv3. Enabling this + protocol will trigger a warning in the logs since it is known to be + insecure. (markt) +
    • +
    • Fix: + Do not log a warning when a null session is returned for an + OpenSSL based TLS session since this is expected when session tickets + are enabled. (markt) +
    • +
    • Fix: + When the access log valve logs a TLS related request attribute and the + NIO2 connector is used with OpenSSL, ensure that the TLS attributes are + available to the access log valve when the connection is closing. + (markt) +
    • +
    • Fix: + 60461: Sync SSL session access for the APR connector. (remm) +
    • +
    • Add: + To ease migration from 8.0.x to 8.5.x, if the HTTP or AJP BIO connector + is explicitly configured, rather than failing to start the connector + because BIO has been removed, automatically switch to NIO and continue. + A warning will be logged to alert the user to the switch. (markt) +
    • +
    +
    +

    Web applications

    +
      +
    • Fix: + Remove references to the Loader attribute + searchExternalFirst from the documentation since the + attribute is no longer supported. (markt) +
    • +
    +
    +

    2017-06-26 Tomcat 8.5.16 (markt)

    +

    Catalina

    +
      +
    • Fix: + 61072: Respect the documentation statements that allow + using the platform default secure random for session id generation. + (remm) +
    • +
    • Fix: + Correct the javadoc for + o.a.c.connector.CoyoteAdapter#parseSessionCookiesId. + Patch provided by John Andrew (XUZHOUWANG) via Github. (violetagg) +
    • +
    • Fix: + 61101: CORS filter should set Vary header in response. + Submitted by Rick Riemer. (remm) +
    • +
    • Add: + 61105: Add a new JULI FileHandler configuration for + specifying the maximum number of days to keep the log files. + (violetagg) +
    • +
    • Fix: + 61125: Ensure that WarURLConnection returns the + correct value for calls to getLastModified() as this is + required for the correct detection of JSP modifications when the JSP is + packaged in a WAR file. (markt) +
    • +
    • Fix: + Improve the SSLValve so it is able to handle client + certificate headers from Nginx. Based on a patch by Lucas Ventura Carro. + (markt) +
    • +
    • Fix: + 61134: Do not use '[' and ']' symbols around substituted + text fragments when generating the default error pages. Patch provided + by Katya Todorova. (violetagg) +
    • +
    • Fix: + 61154: Allow the Manager and Host Manager web applications to + start by default when running under a security manager. This was + accomplished by adding a custom permission, + org.apache.catalina.security.DeployXmlPermission, that + permits an application to use a META-INF/context.xml file + and then granting that permission to the Manager and Host Manager. + (markt) +
    • +
    • Fix: + 61173: Polish the javadoc for + o.a.catalina.startup.Tomcat. Patch provided by + peterhansson_se. (violetagg) +
    • +
    • Add: + A new configuration property crawlerIps is added to the + o.a.catalina.valves.CrawlerSessionManagerValve. Using this + property one can specify a regular expression that will be used to + identify crawlers based on their IP address. Based on a patch provided + by Tetradeus. (violetagg) +
    • +
    • Fix: + 61180: Log a warning message rather than an information + message if it takes more than 100ms to initialised a + SecureRandom instance for a web application to use to + generate session identifiers. Patch provided by Piotr Chlebda. (markt) +
    • +
    • Fix: + 61185: When an asynchronous request is dispatched via + AsyncContext.dispatch() ensure that + getRequestURI() for the dispatched request matches that of + the original request. (markt) +
    • +
    • Fix: + 61197: Ensure that the charset name used in the + Content-Type header has exactly the same form as that + provided by the application. This reverts a behavioural change in + 8.5.15 that caused problems for some clients. (markt) +
    • +
    • Fix: + 61201: Ensure that the SCRIPT_NAME environment + variable for CGI executables is populated in a consistent way regardless + of how the CGI servlet is mapped to a request. (markt) +
    • +
    +
    +

    Coyote

    +
      +
    • Fix: + 61086: Explicitly signal an empty request body for HTTP 205 + responses. (markt) +
    • +
    • Fix: + 61120: Do not ignore path parameters when processing HTTP/2 + requests. (markt) +
    • +
    • Fix: + Revert a change introduced in the fix for bug 60718 that + changed the status code recorded in the access log when the client + dropped the connection from 200 to 500. (markt) +
    • +
    • Fix: + Add additional syncs to the SSL session object provided by the OpenSSL + engine so that a concurrent destruction cannot cause a JVM crash. + (remm) +
    • +
    • Fix: + 61195: Backport, with deprecation where appropriate, the + endpoint and protocol property changes from 9.0.x to ease migration from + 8.5.x to 9.0.x. (markt) +
    • +
    +
    +

    Jasper

    +
      +
    • Fix: + 44787: Improve error message when JSP compiler configuration + options are not valid. (markt) +
    • +
    • Fix: + 61137: j.s.jsp.tagext.TagLibraryInfo#uri and + j.s.jsp.tagext.TagLibraryInfo#prefix fields should not be + final. Patch provided by Katya Todorova. (violetagg) +
    • +
    +
    +

    WebSocket

    +
      +
    • Fix: + Correct the log message when a MessageHandler for + PongMessage does not implement + MessageHandler.Whole. (rjung) +
    • +
    • Add: + Introduce new API o.a.tomcat.websocket.WsSession#suspend/ + o.a.tomcat.websocket.WsSession#resume that can be used to + suspend/resume reading of the incoming messages. (violetagg) +
    • +
    • Fix: + Improve thread-safety of Futures used to report the result + of sending WebSocket messages. (markt) +
    • +
    • Fix: + 61183: Correct a regression in the previous fix for + 58624 that could trigger a deadlock depending on the locking + strategy employed by the client code. (markt) +
    • +
    +
    +

    Web applications

    +
      +
    • Fix: + Better document the meaning of the trimSpaces option for Jasper. (markt) +
    • +
    • Fix: + 61150: Configure the Manager and Host-Manager web + applications to permit serialization and deserialization of + CRSFPreventionFilter related session objects to avoid warning messages + and/or stack traces on web application stop and/or start when running + under a security manager. (markt) +
    • +
    • Fix: + Correct the TLS configuration documentation to remove SSLv2 and SSLv3 + from the list of supported protocols. (markt) +
    • +
    +
    +

    Tribes

    +
      +
    • Add: + Add JMX support for Tribes components. (kfujino) +
    • +
    +
    +

    Other

    +
      +
    • Add: + 45832: Add HTTP DIGEST authentication support to the Catalina + Ant tasks used to communicate with the Manager application. (markt) +
    • +
    • Fix: + 45879: Add the RELEASE-NOTES file to the root of + the installation created by the Tomcat installer for Windows to make it + easier for users to identify the installed Tomcat version. (markt) +
    • +
    • Fix: + 61055: Clarify the code comments in the rewrite valve to make + clear that there are no plans to provide proxy support for this valve + since Tomcat does not have proxy capabilities. (markt) +
    • +
    • Fix: + 61076: Document the altDDName attribute for the + Context element. (markt) +
    • +
    • Fix: + Correct typo in Jar Scan Filter Configuration Reference. + Issue reported via comments.apache.org. (violetagg) +
    • +
    • Fix: + 61145: Add missing @Documented annotation to + annotations in the annotations API. Patch provided by Katya Todorova. + (markt) +
    • +
    • Fix: + 61146: Add missing lookup() method to + @EJB annotation in the annotations API. Patch provided by + Katya Todorova. (markt) +
    • +
    • Fix: + Correct typo in Context Container Configuration Reference. + Patch provided by Katya Todorova. (violetagg) +
    • +
    +
    +

    2017-05-10 Tomcat 8.5.15 (markt)

    +

    General

    +
      +
    • Add: + Allow to exclude JUnit test classes using the build property + test.exclude and document the property in + BUILDING.txt. (rjung) +
    • +
    +
    +

    Catalina

    +
      +
    • Fix: + Review those places where Tomcat re-encodes a URI or URI component and + ensure that the correct encoding (path differs from query string) is + applied and that the encoding is applied consistently. (markt) +
    • +
    • Fix: + Avoid a NullPointerException when reading attributes for a + initialised HTTP connector where TLS is enabled. (markt) +
    • +
    • Fix: + Always quote the hostName of an SSLHostConfig + element when using it as part of the JMX object name to avoid errors that + prevent the associated TLS connector from starting if a wild card + hostName is configured (because * is a + reserved character for JMX object names). (markt) +
    • +
    • Code: + Switch to using Charset rather than String to + store encoding settings (including for configuration and for the + Content-Type header) to reduce the number of places the + associated Charset needs to be looked up. (markt) +
    • +
    • Fix: + Use a more reliable mechanism for the DefaultServlet when + determining if the current request is for custom error page or not. + (markt) +
    • +
    • Fix: + Ensure that when the Default or WebDAV servlets process an error + dispatch that the error resource is processed via the + doGet() method irrespective of the method used for the + original request that triggered the error. (markt) +
    • +
    • Fix: + If a static custom error page is specified that does not exist or cannot + be read, ensure that the intended error status is returned rather than a + 404 or 403. (markt) +
    • +
    • Fix: + When the WebDAV servlet is configured and an error dispatch is made to a + custom error page located below WEB-INF, ensure that the + target error page is displayed rather than a 404 response. (markt) +
    • +
    • Add: + 61047: Add MIME mapping for woff2 fonts in the default + web.xml. Patch provided by Justin Williamson. (violetagg) +
    • +
    • Fix: + Correct the logic that selects the encoding to use to decode the query + string in the SSIServletExternalResolver so that the + useBodyEncodingForURI attribute of the + Connector is correctly taken into account. (markt) +
    • +
    • Fix: + Within the Expires filter, make the content type value specified with the + ExpiresByType parameter, case insensitive. (markt) +
    • +
    +
    +

    Coyote

    +
      +
    • Fix: + When a TrustManager is configured that does not support + certificateVerificationDepth only log a warning about that + lack of support when certificateVerificationDepth has been + explicitly set. (markt) +
    • +
    • Fix: + 60970: Extend the fix for large headers to push requests. + (markt) +
    • +
    • Fix: + Do not include a Date header in HTTP/2 responses with + status codes less than 200. (markt) +
    • +
    +
    +

    Jasper

    +
      +
    • Fix: + When no BOM is present and an encoding is detected, do not skip the + bytes used to detect the encoding since they are not part of a BOM. + (markt) +
    • +
    • Update: + 61057: Update to Eclipse JDT Compiler 4.6.3. (violetagg) +
    • +
    • Fix: + 61065: Ensure that once the class is resolved by + javax.el.ImportHandler#resolveClass it will be cached with + the proper name. (violetagg) +
    • +
    +
    +

    WebSocket

    +
      +
    • Fix: + 61003: Ensure the flags for reading/writing in + o.a.t.websocket.AsyncChannelWrapperSecure are correctly + reset even if some exceptions occurred during processing. (markt/violetagg) +
    • +
    +
    +

    Web Applications

    +
      +
    • Add: + Add documents for maxIdleTime attribute to Channel Receiver + docs. (kfujino) +
    • +
    +
    +

    Other

    +
      +
    • Add: + Modify the Ant build script used to publish to a Maven repository so + that it no longer requires artifacts to be GPG signed. This is make it + possible for the CI system to upload snapshot builds to the ASF Maven + repository. (markt) +
    • +
    • Code: + Review i18n property files, remove unnecessary escaping and consistently + use [...] to delimit inserted values. (markt) +
    • +
    +
    +

    2017-04-18 Tomcat 8.5.14 (markt)

    +

    Catalina

    +
      +
    • Fix: + 59825: Log a message that lists the components in the + processing chain that do not support async processing when a call to + ServletRequest.startAsync() fails. (markt) +
    • +
    • Fix: + 60926: Ensure + o.a.c.core.ApplicationContextFacade#setSessionTimeout will + invoke the correct method when running Tomcat with security manager. + (markt) +
    • +
    • Update: + Update the early access Servlet 4.0 API implementation to reflect the + change in method name from getPushBuilder() to + newPushBuilder(). (markt) +
    • +
    • Fix: + Correct a regression in the X to comma refactoring that broke JMX + operations that take parameters. (markt) +
    • +
    • Fix: + Avoid a NullPointerException when reading attributes for a + running HTTP connector where TLS is not enabled. (markt) +
    • +
    • Fix: + 60940: Improve the handling of the META-INF/ and + META-INF/MANIFEST.MF entries for Jar files located in + /WEB-INF/lib when running a web application from a packed + WAR file. (markt) +
    • +
    • Fix: + Pre-load the ExceptionUtils class. Since the class is used + extensively in error handling, it is prudent to pre-load it to avoid any + failure to load this class masking the true problem during error + handling. (markt) +
    • +
    • Fix: + Avoid potential NullPointerExceptions related to access + logging during shutdown, some of which have been observed when running + the unit tests. (markt) +
    • +
    • Fix: + When there is no javax.servlet.WriteListener registered + then a call to javax.servlet.ServletOutputStream#isReady + will return false instead of throwing + IllegalStateException. (violetagg) +
    • +
    • Fix: + When there is no javax.servlet.ReadListener registered + then a call to javax.servlet.ServletInputStream#isReady + will return false instead of throwing + IllegalStateException. (violetagg) +
    • +
    +
    +

    Coyote

    +
      +
    • Fix: + Align cipher configuration parsing with current OpenSSL master. (markt) +
    • +
    • Fix: + 60970: Fix infinite loop if application tries to write a + large header to the response when using HTTP/2. (markt) +
    • +
    +
    +

    Jasper

    +
      +
    • Fix: + 60925: Improve the handling of access to properties defined + by interfaces when a BeanELResolver is used under a + SecurityManager. (markt) +
    • +
    +
    +

    jdbc-pool

    +
      +
    • Code: + Refactor the creating a constructor for a proxy class to reduce + duplicate code. (kfujino) +
    • +
    • Fix: + In StatementFacade, the method call on the statements that + have been closed throw SQLException rather than + NullPointerException. (kfujino) +
    • +
    +
    +

    Other

    +
      +
    • Fix: + Correct comments about Java 8 in Jre8Compat. + Patch provided by fibbers via Github. (violetagg) +
    • +
    • Fix: + 60932: Correctly escape single quotes when used in i18n + messages. Based on a patch by Michael Osipov. (markt) +
    • +
    • Fix: + Update the custom Ant task that integrates with the Symantec code + signing service to use the now mandatory 2-factor authentication. + (markt) +
    • +
    +
    +

    2017-03-30 Tomcat 8.5.13 (markt)

    +

    Catalina

    +
      +
    • Add: + 54618: Add support to the + HttpHeaderSecurityFilter for the HSTS preload parameter. + (markt) +
    • +
    • Fix: + 60853: Expose the SSLHostConfig and + SSLHostConfigCertificate objects via JMX. (markt) +
    • +
    • Fix: + 60876: Ensure that Set-Cookie headers generated + by the Rfc6265CookieProcessor are aligned with the + specification. Patch provided by Jim Griswold. (markt) +
    • +
    • Fix: + 60882: Fix a NullPointerException when obtaining + a RequestDispatcher for a request that will not have any + pathInfo associated with it. This was a regression in the changes in + 8.5.12 for the Servlet 4.0 API early preview changes. (markt) +
    • +
    • Update: + Align PushBuilder API with changes from Servlet expert + group. (markt) +
    • +
    • Code: + Refactor the various implementations of X to comma separated list to a + single utility class and update the code to use the new utility class. + (markt) +
    • +
    • Fix: + 60911: Ensure NPE will not be thrown when looking for SSL + session ID. Based on a patch by Didier Gutacker. (violetagg) +
    • +
    +
    +

    Coyote

    +
      +
    • Add: + 60362: Add a new Connector configuration + sendReasonPhrase. When this attribute is set to + true, a reason phrase will be sent with the response. + By default a reason phrase will not be sent. This option is deprecated + and is not available in Tomcat 9. (violetagg) +
    • +
    • Fix: + Fix HTTP/2 incorrect input unblocking on EOF. (remm) +
    • +
    • Fix: + Close the connection sooner if an event occurs for a current connection + that is not consistent with the current state of that connection. + (markt) +
    • +
    • Fix: + Speed up shutdown when using multiple acceptor threads by ensuring that + the code that unlocks the acceptor threads correctly handles the case + where there are multiple threads. (markt) +
    • +
    • Fix: + 60852: Correctly spell compressible when used in + configuration attributes and internal code. Based on a patch by Michael + Osipov. (markt) +
    • +
    • Fix: + 60900: Avoid a NullPointerException in the APR + Poller if a connection is closed at the same time as new data arrives on + that connection. (markt) +
    • +
    • Fix: + Improve HPACK specification compliance by fixing some test failures + reported by the h2spec tool written by Moto Ishizawa. (markt) +
    • +
    • Fix: + Improve HTTP/2 specification compliance by fixing some test failures + reported by the h2spec tool written by Moto Ishizawa. (markt) +
    • +
    • Fix: + 60918: Fix sendfile processing error that could lead to + subsequent requests experiencing an IllegalStateException. + (markt) +
    • +
    • Fix: + Improve sendfile handling when requests are pipelined. (markt) +
    • +
    +
    +

    Jasper

    +
      +
    • Fix: + Improve the error handling for simple tags to ensure that the tag is + released and destroyed once used. (remm, violetagg) +
    • +
    • Fix: + 60844: Correctly handle the error when fewer parameter values + than required by the method are used to invoke an EL method expression. + Patch provided by Daniel Gray. (markt) +
    • +
    +
    +

    jdbc-pool

    +
      +
    • Fix: + 60764: Implement equals() and + hashCode() in the StatementFacade in order to + enable these methods to be called on the closed statements if any + statement proxy is set. This behavior can be changed with + useStatementFacade attribute. (kfujino) +
    • +
    +
    +

    Other

    +
      +
    • Fix: + Refactor the build script and the NSIS installer script so that either + NSIS 2.x or NSIS 3.x can be used to build the installer. This is + primarily to re-enable building the installer on the Linux based CI + system where the combination of NSIS 3.x and wine leads to failed + installer builds. (markt) +
    • +
    +
    +

    2017-03-13 Tomcat 8.5.12 (markt)

    +

    Catalina

    +
      +
    • Fix: + 60469: Refactor RealmBase for better code re-use + when implementing Realms that use a custom Principal. + (markt) +
    • +
    • Fix: + 60490: Various formatting and layout improvements for the + ErrorReportValve. Patch provided by Michael Osipov. (markt) +
    • +
    • Update: + 60596: Improve performance of DefaultServlet when sendfile + feature is disabled on connector. (kkolinko) +
    • +
    • Code: + Make it easier for sub-classes of Tomcat to modify the + default web.xml settings by over-riding + getDefaultWebXmlListener(). Patch provided by Aaron + Anderson. (markt) +
    • +
    • Fix: + Reduce the contention in the default InstanceManager + implementation when multiple threads are managing objects and need to + reference the annotation cache. (markt) +
    • +
    • Code: + 60674: Remove final marker from + CorsFilter to enable sub-classing. (markt) +
    • +
    • Fix: + 60683: Security manager failure causing NPEs when doing IO + on some JVMs. (csutherl) +
    • +
    • Fix: + 60688: Update the internal fork of Apache Commons BCEL to + r1782855 to add early access Java 9 support to the annotation scanning + code. (markt) +
    • +
    • Fix: + 60694: Prevent NPE during authentication when no JASPIC + AuthConfigFactory is available. (markt) +
    • +
    • Fix: + 60697: When HTTP TRACE requests are disabled on the + Connector, ensure that the HTTP OPTIONS response from custom servlets + does not include TRACE in the returned Allow header. (markt) +
    • +
    • Fix: + 60718: Improve error handling for asynchronous processing and + correct a number of cases where the requestDestroyed() + event was not being fired and an entry wasn't being made in the access + logs. (markt) +
    • +
    • Fix: + 60720: Replace "WWW-Authenticate" literal with static final + AUTH_HEADER_NAME in SpnegoAuthenticator. Patch provided by Michael + Osipov. (violetagg) +
    • +
    • Fix: + The default JASPIC AuthConfigFactory now correctly notifies + registered RegistrationListeners when a new + AuthConfigProvider is registered. (markt) +
    • +
    • Code: + Improve the performance of AuthenticatorBase when there is + no JASPIC configuration available. (violetagg) +
    • +
    • Fix: + When HTTP TRACE requests are disabled on the Connector, ensure that the + HTTP OPTIONS response from the WebDAV servlet does not include + TRACE in the returned Allow header. (markt) +
    • +
    • Fix: + 60722: Take account of the + dispatchersUseEncodedPaths setting on the current + Context when generating paths for dispatches triggered + by AsyncContext.dispatch(). (markt) +
    • +
    • Fix: + 60728: Make the separator Tomcat uses in the Tomcat specific + war:file:... URL protocol customizable via a system + property. The separator is equivalent to the use of the ! + character in jar:file:... URLs. The default separator of + * remains unchanged. (markt) +
    • +
    • Update: + Update the org.apache.catalina.servlet4preview package that + can be used to gain early access to Servlet 4.0 features to align with + the latest proposals from the Servlet 4.0 expert group. This includes + updates to the new Servlet mapping API, new methods on the + ServletContext to make the available API more equivalent to + the deployment descriptor, updates to the HTTP push API and the ability + to set default request and response character encoding per web + application. Note that the Servlet 4.0 API is still a work in progress + and further changes are likely. (markt) +
    • +
    • Fix: + 60798: Correct a bug in the handling of JARs in unpacked WARs + that meant multiple attempts to read the same entry from a JAR in + succession would fail for the second and subsequent attempts. (markt) +
    • +
    • Fix: + 60808: Ensure that the Map returned by + ServletRequest.getParameterMap() is fully immutable. Based + on a patch provided by woosan. (markt) +
    • +
    • Fix: + 60824: Correctly cache the Subject in the + session - if there is a session - when running under a + SecurityManager. Patch provided by Jan Engehausen. (markt) +
    • +
    • Fix: + Ensure request and response facades are used when firing application + listeners. (markt/remm) +
    • +
    +
    +

    Coyote

    +
      +
    • Fix: + Improve handling of case when an HTTP/2 client sends more data that is + subject to flow control than the current window size allows. (markt) +
    • +
    • Fix: + Improve NIO2 look-ahead parsing of TLS client hello for SNI with large + client hello messages. (markt) +
    • +
    • Fix: + 59807: Provide a better error message when there is no + SSLHostConfig defined with a hostName that + matches the defaultSSLHostConfigName for the associated + Connector. (markt) +
    • +
    • Fix: + Include the value of SslHostConfig.truststoreAlgorithm when + warning that the algorithm does not support the + certificateVerificationDepth configuration option. (markt) +
    • +
    • Fix: + Ensure that executor thread pools used with connectors pre-start the + configured minimum number of idle threads. (markt) +
    • +
    • Add: + 60594: Allow some invalid characters that were recently + restricted to be processed in requests by using the system property + tomcat.util.http.parser.HttpParser.requestTargetAllow. + (csutherl) +
    • +
    • Fix: + 60627: Modify the Rfc6265CookieProcessor so that + in addition to cookie headers that start with an explicit RFC 2109 + $Version=1, cookies that start with $Version=0 + are also parsed as RFC 2109 cookies. (markt) +
    • +
    • Fix: + 60716: Add a new JSSE specific attribute, + revocationEnabled, to SSLHostConfig to permit + JSSE provider revocation checks to be enabled when no + certificateRevocationListFile has been configured. The + expectation is that configuration will be performed via a JSSE provider + specific mechanisms. (markt) +
    • +
    • Fix: + Modify the cookie header generated by the + Rfc6265CookieProcessor so it always sends an + Expires attribute as well as a Max-Age + attribute to avoid problems with Microsoft browsers that do not support + the Max-Age attribute. (markt) +
    • +
    • Fix: + 60761: Expose a protected getter and setter for + NioEndpoint.stopLatch to make the class easier to extend. + (markt) +
    • +
    • Fix: + Prevent blocking reads after a stream exception occurs with HTTP/2. + (remm) +
    • +
    +
    +

    Jasper

    +
      +
    • Fix: + Follow up to the fix for 58178. When creating the + ELContext for a tag file, ensure that any registered + ELContextListeners are fired. (markt) +
    • +
    • Fix: + Refactor code generated for JSPs to reduce the size of the code required + for tags. (markt) +
    • +
    • Fix: + 60769: Correct a regression in the XML encoding detection + refactoring carried out for 8.5.10 that incorrectly always used the + detected BOM encoding in preference to any encoding specified in the + prolog. (markt) +
    • +
    • Update: + Update to the Eclipse JDT Compiler 4.6.1. (markt) +
    • +
    +
    +

    Cluster

    +
      +
    • Add: + Make the accessTimeout configurable in + BackupManager and ClusterSingleSignOn. The + accessTimeout is used as a timeout period for PING in + replication map. (kfujino) +
    • +
    • Fix: + 60806: To avoid ClassNotFoundException, make + sure that the web application class loader is passed to + ReplicatedContext. (kfujino) +
    • +
    +
    +

    WebSocket

    +
      +
    • Fix: + 60617: Correctly create a CONNECT request when + establishing a WebSocket connection via a proxy. Patch provided by + Svetlin Zarev. (markt) +
    • +
    +
    +

    Tribes

    +
      +
    • Add: + Add log message that PING message has received beyond the timeout + period. (kfujino) +
    • +
    • Fix: + When a PING message that beyond the time-out period has been received, + make sure that valid member is added to the map membership. (kfujino) +
    • +
    • Fix: + Ensure that NoRpcChannelReply messages are not received on + RpcCallback. (kfujino) +
    • +
    +
    +

    Web Applications

    +
      +
    • Fix: + Add Specification and Javadoc references for JASPIC to the Docs + application. (csutherl) +
    • +
    +
    +

    Other

    +
      +
    • Fix: + Spelling corrections provided by Josh Soref. (violetagg) +
    • +
    • Update: + Update the packaged version of the Tomcat Native Library to 1.2.12 to + pick up the latest Windows binaries built with OpenSSL 1.0.2k. (violetagg) +
    • +
    • Add: + 60784: Update all unit tests that test the HTTP status line + to check for the required space after the status code. Patch provided by + Michael Osipov. (markt) +
    • +
    • Update: + Update the NSIS Installer used to build the Windows installer to version + 3.01. (markt) +
    • +
    +
    +

    2017-01-16 Tomcat 8.5.11 (markt)

    +

    Catalina

    +
      +
    • Add: + 60620: + Extend the JreMemoryLeakPreventionListener to provide + protection against ForkJoinPool.commonPool() related memory + leaks. (markt) +
    • +
    +
    +

    Coyote

    +
      +
    • Fix: + Ensure UpgradeProcessor instances associated with closed connections are + removed from the map of current connections to Processors. (markt) +
    • +
    • Fix: + Remove a workaround for a problem previously reported with WebSocket, + TLS and APR that treated some error conditions as not errors. The + original problem cannot be reproduced with the current code and the + work-around is now causing problems. (markt) +
    • +
    +
    +

    Jasper

    +
      +
    • Fix: + 60497: Follow up fix using a better variable name for the + tag reuse flag. (remm) +
    • +
    • Fix: + Revert use of try/finally for simple tags. (remm) +
    • +
    +
    +

    WebSocket

    +
      +
    • Fix: + Prevent potential processing loop on unexpected WebSocket connection + closure. (markt) +
    • +
    +
    +

    jdbc-pool

    +
      +
    • Add: + Enable reset the statistics without restarting the pool. (kfujino) +
    • +
    +
    +

    Other

    +
      +
    • Fix: + Spelling corrections provided by Josh Soref. (violetagg) +
    • +
    +
    +

    not released Tomcat 8.5.10 (markt)

    +

    Catalina

    +
      +
    • Add: + 53602: Add HTTP status code 451 (RFC 7725) to the list of + HTTP status codes recognised by the ErrorReportValve. (markt) +
    • +
    • Fix: + 60446: Handle the case where the stored user credential uses + a different key length than the length currently configured for the + CredentialHandler. Based on a patch by Niklas Holm. (markt) +
    • +
    • Update: + Update the warnings that reference required options for running on Java + 9 to use the latest syntax for those options. (markt) +
    • +
    • Fix: + 60513: Fix thread safety issue with RMI cleanup code. (remm) +
    • +
    +
    +

    Coyote

    +
      +
    • Fix: + Expand the search process for a server certificate when OpenSSL is used + with a JSSE connector and an explicit alias has not been configured. + (markt) +
    • +
    • Fix: + 60450: Improve the selection algorithm for the default trust + store type for a TLS Virtual Host. In particular, don't use + PKCS12 as a default trust store type. Better document how + the default trust store type is selected for a TLS virtual host. (markt) +
    • +
    • Fix: + 60451: Correctly handle HTTP/2 header values that contain + characters with unicode code points in the range 128 to 255. Reject + with a clear error message HTTP/2 header values that contain characters + with unicode code points above 255. (markt) +
    • +
    • Fix: + Improve the logic that selects an address to use to unlock the Acceptor + to take account of platforms what do not listen on all local addresses + when configured with an address of 0.0.0.0 or + ::. (markt) +
    • +
    • Fix: + Correct a regression in the refactoring to make wider use of + ByteBuffer that caused an intermittent failure in the unit + tests. (markt) +
    • +
    • Fix: + 60482: HTTP/2 shouldn't do URL decoding on the query string. + (remm) +
    • +
    • Fix: + Fix an HTTP/2 compression error. Once a new size has been agreed for the + dynamic HPACK table, the next header block must begin with a dynamic + table update. (markt) +
    • +
    • Fix: + 60508: Set request start time for HTTP/2. (remm) +
    • +
    +
    +

    Jasper

    +
      +
    • Update: + Implement a simpler JSP file encoding detector that delegates XML prolog + encoding detection to the JRE rather than using a custom XML parser. + (markt) +
    • +
    • Fix: + 60497: Restore previous tag reuse behavior following the use + of try/finally. (remm) +
    • +
    • Fix: + Improve the error handling for simple tags to ensure that the tag is + released and destroyed once used. (remm) +
    • +
    +
    +

    WebSocket

    +
      +
    • Fix: + Correctly handle blocking WebSocket writes when the write times out just + before the write is attempted. (markt) +
    • +
    +
    +

    Web Applications

    +
      +
    • Add: + In the documentation web application, be explicit that clustering + requires a secure network for all of the cluster network traffic. + (markt) +
    • +
    • Update: + Update the ASF logos to the new versions. +
    • +
    • Fix: + 60344: Add a note to BUILDING.txt regarding using the source + bundle with the correct line endings. (markt) +
    • +
    • Fix: + 60468: Correct the format of the sample ISO-8601 date used + to report the build date for the documentation. Patch provided by + Michael Osipov. (markt) +
    • +
    +
    +

    Other

    +
      +
    • Update: + Update the ASF logos used in the Apache Tomcat installer for Windows to + use the new versions. +
    • +
    +
    +

    2016-12-08 Tomcat 8.5.9 (markt)

    +

    Catalina

    +
      +
    • Update: + 60202: Add an available flag to realms, to indicate the + state, or the realm backend. Update lockout realm to only register + auth failures if the realm is available. (remm) +
    • +
    • Fix: + 60340: Readability improvements for CSS used in + DefaultServlet and ErrorReportValve. Patch provided by Michael + Osipov. (violetagg) +
    • +
    • Fix: + 60351: Delay creating META-INF/war-tracker file + until after the WAR has been expanded to address the case where the + Tomcat process terminates during the expansion. (markt) +
    • +
    • Fix: + Correctly generate URLs for resources located inside JARs that are + themselves located inside a packed WAR file. (markt) +
    • +
    • Fix: + Correctly handle the configClass attribute of a Host when + embedding Tomcat. (markt) +
    • +
    • Fix: + 60368: Restore egde case for embedded allowing the connector + to be removed. (remm) +
    • +
    • Fix: + 60379: Dispose of the GSS credential once it is no longer + required. Patch provided by Michael Osipov. (markt) +
    • +
    • Fix: + 60380: Ensure that a call to + HttpServletRequest#logout() triggers a call to + TomcatPrincipal#logout(). Based on a patch by Michael + Osipov. (markt) +
    • +
    • Fix: + 60387: Correct the javadoc for + o.a.catalina.AccessLog.setRequestAttributesEnabled. + The default value is different for the different implementations. + (violetagg) +
    • +
    • Code: + 60393: Use consistent parameter naming in implementations of + Realm#authenticate(GSSContext, boolean). (markt) +
    • +
    • Fix: + 60395: Log when an Authenticator passes an + incomplete GSSContext to a Realm since it indicates a bug + in the Authenticator. Patch provided by Michael Osipov. + (markt) +
    • +
    • Fix: + 60400: When expanding the buffer used for reading the + request body, ensure the read position will be restored to the + original one. (violetagg) +
    • +
    • Fix: + 60410: Ensure that multiple calls to + JarInputStreamWrapper#close() do not incorrectly trigger + the closure of the underlying JAR or WAR file. (markt) +
    • +
    • Fix: + 60411: Implement support in the RewriteValve for + symbolic names to specify the redirect code to use when returning a + redirect response to the user agent. Patch provided by Michael Osipov. + (markt) +
    • +
    • Fix: + 60413: In the RewriteValve write empty capture + groups as the empty string rather than as "null" + when generating the re-written URL. Based on a patch by Michael Osipov. + (markt) +
    • +
    +
    +

    Coyote

    +
      +
    • Fix: + 60372: Ensure the response headers' buffer limit is reset to + the capacity of this buffer when IOException occurs while writing the + headers to the socket. (violetagg) +
    • +
    • Fix: + Ensure that the availability of configured upgrade protocols that + require ALPN is correctly reported during Tomcat start. (markt) +
    • +
    • Fix: + 60386: Implement a more sophisticated pruning algorithm for + removing closed streams from the priority tree to ensure that the tree + does not grow too large. (markt) +
    • +
    • Fix: + 60409: When unable to complete sendfile request, ensure the + Processor will be added to the cache only once. (markt/violetagg) +
    • +
    • Fix: + Ensure that the endpoint is able to unlock the acceptor thread during + shutdown if the endpoint is configured to listen to any local address + of a specific type such as 0.0.0.0 or ::. + (markt) +
    • +
    • Add: + Add a new configuration option, ipv6v6only to the APR + connectors that allows them to be configure to only accept IPv6 + connections when configured with an IPv6 address rather than the + default which is to accept IPv4 connections as well if the operating + system uses a dual network stack. (markt) +
    • +
    • Fix: + Improve the logic that unlocks the acceptor thread so a better choice is + made for the address to connect to when a connector is configured for + any local port. This reduces the likelihood of the unlock failing. + (markt) +
    • +
    • Fix: + 60436: Avoid a potential NPE when processing async timeouts. + (markt) +
    • +
    • Fix: + Reduce the window in which an async request that has just started + processing on a container thread remains eligible for an async timeout. + (markt) +
    • +
    +
    +

    Jasper

    +
      +
    • Fix: + 60431: Improve handling of varargs in UEL expressions. Based + on a patch by Ben Wolfe. (markt) +
    • +
    +
    +

    Web applications

    +
      +
    • Fix: + Fix JDK version number documented in BUILDING.txt. (rjung) +
    • +
    • Fix: + Correct a typo in Host Configuration Reference. + Issue reported via comments.apache.org. (violetagg) +
    • +
    • Fix: + 60412: Add information on the comment syntax for the + RewriteValve configuration. (markt) +
    • +
    • Fix: + 60467: remove problematic characters from XML documentation. + Based upon a patch by Michael Osipov. (schultz) +
    • +
    +
    +

    Tribes

    +
      +
    • Fix: + Reduce the warning logs for a message received from a different domain + in order to avoid excessive log outputs. (kfujino) +
    • +
    +
    +

    WebSocket

    +
      +
    • Fix: + 60437: Avoid possible handshake overflows in the websocket + client. (remm) +
    • +
    +
    +

    jdbc-pool

    +
      +
    • Add: + 58816: Implement the statistics of jdbc-pool. The stats infos + are borrowedCount, returnedCount, + createdCount, releasedCount, + reconnectedCount, releasedIdleCount and + removeAbandonedCount. (kfujino) +
    • +
    • Fix: + 60194: If validationQuery is not specified, + connection validation is done by calling the isValid() + method. (kfujino) +
    • +
    • Fix: + 60398: Fix testcase of TestSlowQueryReport. + (kfujino) +
    • +
    +
    +

    Other

    +
      +
    • Fix: + Allow customization of service.bat, such as heap memory size, service + startup mode and JVM args. Patch provided by isapir via Github. + (violetagg) +
    • +
    • Fix: + 60366: Change catalina.bat to use directly + LOGGING_MANAGER and LOGGING_CONFIG variables + in order to configure logging, instead of modifying + JAVA_OPTS. Patch provided by Petter Isberg. (violetagg) +
    • +
    • Fix: + 60383: JASPIC API is added as a dependency to the + org.apache.tomcat:tomcat-catalina maven artifact. + (violetagg) +
    • +
    • Fix: + Update the comments associated with the TLS Connector examples in + server.xml. (markt) +
    • +
    • Add: + New property is added test.verbose in order to control + whether the output of the tests is displayed on the console or not. + Patch provided by Emmanuel Bourg. (violetagg) +
    • +
    • Code: + TestOpenSSLCipherConfigurationParser.testSpecification + - if there are test failures, provide more detailed information. Patch + provided by Emmanuel Bourg. (violetagg) +
    • +
    +
    +

    2016-11-08 Tomcat 8.5.8 (markt)

    +

    Coyote

    +
      +
    • Fix: + Check that threadPriority values used in AbstractProtocol are valid. + (fschumacher) +
    • +
    +
    +

    not released Tomcat 8.5.7 (markt)

    +

    Catalina

    +
      +
    • Fix: + When creating a new Connector via JMX, ensure that both HTTP/1.1 and + AJP/1.3 connectors can be created. (markt) +
    • +
    • Fix: + Include the Context name in the log message when an item cannot be + added to the cache. (markt) +
    • +
    • Fix: + Exclude JAR files in /WEB-INF/lib from the static resource + cache. (markt) +
    • +
    • Fix: + When calling getResourceAsStream() on a directory, ensure + that null is returned. (markt) +
    • +
    • Fix: + 60161: Allow creating subcategories of the container logger, + and use it for the rewrite valve. (remm) +
    • +
    • Fix: + Correctly test for control characters when reading the provided shutdown + password. (markt) +
    • +
    • Fix: + 60297: Simplify connector creation in embedded mode. (remm) +
    • +
    • Fix: + Refactor creation of containers in embedded mode for more consistency + and flexibility. (remm) +
    • +
    • Add: + Introduce new methods read(ByteBuffer)/ + write(ByteBuffer) in + o.a.catalina.connector.CoyoteInputStream/ + o.a.catalina.connector.CoyoteOutputStream. (violetagg) +
    • +
    • Fix: + When configuring the JMX remote listener, specify the allowed types for + the credentials. (markt) +
    • +
    +
    +

    Coyote

    +
      +
    • Fix: + Correct the HPACK header table size configuration that transposed the + client and server table sizes when creating the encoder and decoder. + (markt) +
    • +
    • Fix: + Don't continue to process an HTTP/2 stream if it is reset during header + parsing. (markt) +
    • +
    • Fix: + HTTP/2 uses separate headers for each Cookie. As required by RFC 7540, + merge these into a single Cookie header before processing continues. + (markt) +
    • +
    • Fix: + Align the HTTP/2 implementation with the HTTP/1.1 implementation and + return a 500 response when an unhandled exception occurs during request + processing. (markt) +
    • +
    • Fix: + Correct the HTTP header parser so that DEL is not treated as a valid + token character. (markt) +
    • +
    • Add: + Add checks around the handling of HTTP/2 pseudo headers. (markt) +
    • +
    • Add: + Add support for trailer headers to the HTTP/2 implementation. (markt) +
    • +
    • Fix: + 60232: When processing headers for an HTTP/2 stream, ensure + that the read buffer is large enough for the header being processed. + (markt) +
    • +
    • Add: + Add configuration options to the HTTP/2 implementation to control the + maximum number of headers allowed, the maximum size of headers allowed, + the maximum number of trailer headers allowed, the maximum size of + trailer headers allowed and the maximum number of cookies allowed. + (markt) +
    • +
    • Fix: + Correctly differentiate between sending and receiving a reset frame when + tracking the state of an HTTP/2 stream. (markt) +
    • +
    • Fix: + 60319: When using an Executor, disconnect it from the + Connector attributes maxThreads, + minSpareThreads and threadPriority to enable + the configuration settings to be consistently reported. These Connector + attributes will be reported as -1 when an Executor is in + use. The values used by the executor may be set and obtained via the + Executor. (markt) +
    • +
    • Fix: + If an I/O error occurs during async processing on a non-container + thread, ensure that the onError() event is triggered. + (markt) +
    • +
    • Fix: + Improve detection of I/O errors during async processing on non-container + threads and trigger async error handling when they are detected. (markt) +
    • +
    • Add: + Add additional checks for valid characters to the HTTP request line + parsing so invalid request lines are rejected sooner. (markt) +
    • +
    +
    +

    Web applications

    +
      +
    • Add: + Add HTTP/2 configuration information to the documentation web + application. (markt) +
    • +
    • Fix: + Fix default value of validationInterval attribute in + jdbc-pool. (kfujino) +
    • +
    • Fix: + Correct a typo in CGI How-To. + Issue reported via comments.apache.org. (violetagg) +
    • +
    +
    +

    Tribes

    +
      +
    • Fix: + When the proxy node sends a backup retrieve message, ensure that using + the channelSendOptions that has been set rather than the + default channelSendOptions. (kfujino) +
    • +
    +
    +

    Other

    +
      +
    • Add: + Add the JASPIC API jar to the Maven Central publication script. (markt) +
    • +
    • Fix: + Remove classes from tomcat-util-scan.jar that are duplicates of those in + tomcat-util.jar. (markt) +
    • +
    +
    +

    2016-10-10 Tomcat 8.5.6 (markt)

    +

    Catalina

    +
      +
    • Add: + 59961: Add an option to the StandardJarScanner + to control whether or not JAR Manifests are scanned for additional + class path entries. (markt) +
    • +
    • Fix: + 60013: Refactor the previous fix to align the behaviour of + the Rewrite Valve with mod_rewrite. As part of this, provide an + implementation for the B and NE flags and + improve the handling for the QSA flag. Includes multiple + test cases by Santhana Preethiand a patch by Tiago Oliveira. (markt) +
    • +
    • Fix: + 60087: Refactor the web resources handling to use the Tomcat + specific war:file:... URL protocol to refer to WAR files + and their contents rather than the standard jar:file:... + form since some components of the JRE, such as JAR verification, give + unexpected results when the standard form is used. A side-effect of the + refactoring is that when using packed WARs, it is now possible to + reference a WAR and/or specific JARs within a WAR in the security policy + file used when running under a SecurityManager. (markt) +
    • +
    • Fix: + 60116: Fix a problem with the rewrite valve that caused back + references evaluated in conditions to be forced to lower case when using + the NC flag. (markt) +
    • +
    • Fix: + Ensure Digester.useContextClassLoader is considered in + case the class loader is used. (violetagg) +
    • +
    • Fix: + 60117: Ensure that the name of LogLevel is + localized when using OneLineFormatter. Patch provided by + Tatsuya Bessho. (kfujino) +
    • +
    • Fix: + 60138: Fix the SSLHostConfig so that the + protocols attribute is limited to the protocols supported + by the current JSSE implementation rather than the default protocols + used by the implementation. (markt) +
    • +
    • Fix: + 60146: Improve performance for resource retrieval by making + calls to WebResource.getInputStream() trigger caching if the resource is + small enough. Patch provided by mohitchugh. (markt) +
    • +
    • Add: + 60151: Improve the exception error messages when a + ResourceLink fails to specify the type, specifies an + unknown type or specifies the wrong type. (markt) +
    • +
    • Fix: + 60167: Ignore empty lines in /etc/passwd files + when using the PasswdUserDatabase. (markt) +
    • +
    • Fix: + 60170: Exclude the compressed test file + index.html.br from RAT analysis. Patch provided by Gavin + McDonald. (markt) +
    • +
    • Fix: + When starting web resources, ensure that class resources are only + started once. (markt) +
    • +
    • Fix: + Improve the access checks for linked global resources to handle the case + where the current class loader is a child of the web application class + loader. (markt) +
    • +
    • Fix: + 60196: Ensure that the isMandatory flag is + correctly set when using JASPIC authentication. (markt) +
    • +
    • Fix: + 60199: Log a warning if deserialization issues prevent a + session attribute from being loaded. (markt) +
    • +
    • Fix: + 60208: When using RFC6265 compliant cookies, the + / character should not be allowed in a cookie name since + the RFC6265 will drop such cookies as invalid. (markt) +
    • +
    +
    +

    Coyote

    +
      +
    • Add: + Refactor the code that implements the requirement that a call to + complete() or dispatch() made from a + non-container thread before the container initiated thread that called + startAsync() completes must be delayed until the container + initiated thread has completed. Rather than implementing this by + blocking the non-container thread, extend the internal state machine to + track this. This removes the possibility that blocking the non-container + thread could trigger a deadlock. (markt) +
    • +
    • Fix: + Fail earlier if the client closes the connection during SNI processing. + (markt) +
    • +
    • Fix: + 60123: Avoid potential threading issues that could cause + excessively large vales to be returned for the processing time of + a current request. (markt) +
    • +
    • Fix: + 60174: Log instances of HeadersTooLargeException + during request processing. (markt) +
    • +
    • Fix: + 60173: Allow up to 64kB HTTP/2 header table size limit. (remm) +
    • +
    • Fix: + Java 9 compatibility of direct ByteBuffer cleaner. (remm) +
    • +
    +
    +

    Jasper

    +
      +
    • Fix: + 60101: Remove preloading of the class that was deleted. + (violetagg) +
    • +
    +
    +

    Web applications

    +
      +
    • Add: + Expand the documentation for the nested elements within a + Resources element to clarify the behaviour of different + configuration options with respect to the order in which resources are + searched. (markt) +
    • +
    • Add: + Add an example of using the classesToInitialize attribute + of the JreMemoryLeakPreventionListener to the documentation + web application. Based on a patch by Cris Berneburg. (markt) +
    • +
    • Fix: + 60192: Correct a typo in the status output of the Manager + application. Patch provided by Radhakrishna Pemmasani. (markt) +
    • +
    +
    +

    jdbc-pool

    +
      +
    • Fix: + Notify jmx when returning the connection that has been marked suspect. + (kfujino) +
    • +
    • Fix: + Ensure that the POOL_EMPTY notification has been added to + the jmx notification types. (kfujino) +
    • +
    • Fix: + 60099: Ensure that use all method arguments as a cache key + when using StatementCache. (kfujino) +
    • +
    • Fix: + 60139: Correct Javadocs for + PoolConfiguration.getValidationInterval and + setValidationInterval. Reported by Phillip Webb. (kfujino) +
    • +
    +
    +

    Other

    +
      +
    • Fix: + Update the download location for Objenesis. (violetagg) +
    • +
    • Fix: + 60164: Replace log4j-core*.jar with + log4j-web*.jar since it is log4j-web*.jar that + contains the ServletContainerInitializer. (markt) +
    • +
    • Add: + Add documentation to the bin/catalina.bat script to remind users that + environment variables don't affect the configuration of Tomcat when + run as a Windows Service. Based upon a documentation patch by + James H.H. Lampert. (schultz) +
    • +
    • Update: + Update the packaged version of the Tomcat Native Library to 1.2.10 to + pick up the latest Windows binaries built with OpenSSL 1.0.2j. (markt) +
    • +
    +
    +

    2016-09-05 Tomcat 8.5.5 (markt)

    +

    Catalina

    +
      +
    • Fix: + 18500: Add limited support for wildcard host names and host + aliases. Names of the form *.domainname are now permitted. + Note that an exact host name match takes precedence over a wild card + host name match. (markt) +
    • +
    • Fix: + 59813: Ensure that circular relations of the Class-Path + attribute from JAR manifests will be processed correctly. (violetagg) +
    • +
    • Fix: + Ensure that reading the singleThreadModel attribute of a + StandardWrapper via JMX does not trigger initialisation of + the associated servlet. With some frameworks this can trigger an + unexpected initialisation thread and if initialisation is not thread-safe + the initialisation can then fail. (markt) +
    • +
    • Fix: + Compatibility with rewrite from httpd for non existing headers. + (jfclere) +
    • +
    • Fix: + By default, treat paths used to obtain a request dispatcher as encoded. + This behaviour can be changed per web application via the + dispatchersUseEncodedPaths attribute of the Context. + (markt) +
    • +
    • Fix: + 59839: Apply roleSearchAsUser to all nested searches + in JNDIRealm. (fschumacher) +
    • +
    • Fix: + 59859: Fix resource leak in WebDAV servlet. Based on patch by + Coty Sutherland. (fschumacher) +
    • +
    • Add: + Provide a mechanism that enables the container to check if a component + (typically a web application) has been granted a given permission when + running under a SecurityManager without the current execution stack + having to have passed through the component. Use this new mechanism to + extend SecurityManager protection to the system property replacement + feature of the digester. (markt) +
    • +
    • Add: + When retrieving an object via a ResourceLink, ensure that + the object obtained is of the expected type. (markt) +
    • +
    • Fix: + 59823: Ensure that JASPIC configuration is taken into account + when calling HttpServletRequest.authenticate(). (markt) +
    • +
    • Fix: + 59824: Mark the RewriteValve as supporting async + processing by default. (markt) +
    • +
    • Fix: + 59862: Allow nested jar files scanning to be filtered with + the system property + tomcat.util.scan.StandardJarScanFilter.jarsToSkip. Patch + is provided by Terence Bandoian. (violetagg) +
    • +
    • Fix: + 59866: When scanning WEB-INF/classes for + annotations, don't scan the contents of + WEB-INF/classes/META-INF (if present) since classes will + never be loaded from that location. (markt) +
    • +
    • Fix: + 59888: Correctly handle tabs and spaces in quoted version one + cookies when using the Rfc6265CookieProcessor. (markt) +
    • +
    • Fix: + 59912: Fix an edge case in input stream handling where an + IOException could be thrown when reading a POST body. + (markt) +
    • +
    • Fix: + 59913: Correct a regression introduced with the support for + the Servlet 4 HttpServletRequest.getMapping() API that + caused the attributes for forwarded requests to be lost if requested + from within a subsequent include. (markt) +
    • +
    • Fix: + 59966: Do not start the web application if the error page + configuration in web.xml is invalid. (markt) +
    • +
    • Fix: + Switch the CGI servlet to the standard logging mechanism and remove + support for the debug attribute. (markt) +
    • +
    • Fix: + 60012: Improvements in the log messages. Based on + suggestions by Nemo Chen. (violetagg) +
    • +
    • Fix: + Changes to the allowLinking attribute of a + StandardRoot instance now invalidate the cache if caching + is enabled. (markt) +
    • +
    • Add: + Add a new initialisation parameter, envHttpHeaders, to + the CGI Servlet to mitigate httpoxy + (CVE-2016-5388) by default and to provide a mechanism that can be + used to mitigate any future, similar issues. (markt) +
    • +
    • Add: + When adding and removing ResourceLinks dynamically, ensure + that the global resource is only visible via the + ResourceLinkFactory when it is meant to be. (markt) +
    • +
    • Fix: + 60008: When processing CORs requests, treat any origin with a + URI scheme of file as a valid origin. (markt) +
    • +
    • Fix: + Improve handling of exceptions during a Lifecycle events triggered by a + state transition. The exception is now caught and the component is now + placed into the FAILED state. (markt) +
    • +
    • Fix: + 60013: Fix encoding issues when using the RewriteValve with + UTF-8 query strings or UTF-8 redirect URLs. (markt) +
    • +
    • Fix: + 60022: Improve handling when a WAR file and/or the associated + exploded directory are symlinked into the appBase. (markt) +
    • +
    • Fix: + Fix a file descriptor leak when reading the global web.xml. (markt) +
    • +
    • Fix: + Consistently decode URL patterns provided via web.xml using the encoding + of the web.xml file where specified or UTF-8 where no explicit encoding + is specified. (markt) +
    • +
    • Fix: + Make timing attacks against the Realm implementations harder. (schultz) +
    • +
    • Fix: + A number of the JRE memory leaks addressed by the + JreMemoryLeakPreventionListener have been fixed in Java 9 + so the associated protection is now disabled when running on Java 9 + onwards. (markt) +
    • +
    +
    +

    Coyote

    +
      +
    • Fix: + Correct a regression in refactoring to enable injection of custom + keystores that broke the automatic conversion of OpenSSL style PEM + key and certificate files for use with JSSE TLS connectors. (markt) +
    • +
    • Fix: + 59910: Don't hardcode key alias value to "tomcat" for JSSE. + When using a keystore, OpenSSL will still default to it. (remm) +
    • +
    • Fix: + 59904: Add a limit (default 200) for the number of cookies + allowed per request. Based on a patch by gehui. (markt) +
    • +
    • Fix: + 59925: Correct regression in r1628368 and ensure that HTTP + separators are handled as configured in the + LegacyCookieProcessor. Patch provided by Kyohei Nakamura. + (markt) +
    • +
    • Fix: + 59950: Correct log message when reporting that the current + number of HTTP/2 streams for a connection could not be pruned to below + the limit. (markt) +
    • +
    • Fix: + Ensure that Semaphore.release is called in all cases. Even + when there is an exception. (violetagg) +
    • +
    • Fix: + 60030: Correct a potential infinite loop in the SNI parsing + code triggered by failing to handle an end of stream condition. (markt) +
    • +
    • Fix: + Small logging optimization in the Rfc6265CookieProcessor. + Patch provided by Svetlin Zarev. (markt) +
    • +
    • Fix: + OpenSSL now disables 3DES by default so reflect this when using OpenSSL + syntax to select ciphers. (markt) +
    • +
    • Fix: + Use the proper ERROR socket status code for async errors with NIO2. + (remm) +
    • +
    • Fix: + 60035: Fix a potential connection leak if the client drops a + TLS connection before the handshake completes. (markt) +
    • +
    • Fix: + Refactor the JSSE client certificate validation so that the + effectiveness of the certificateVerificationDepth + configuration attribute does not depend on the presence of a certificate + revocation list. (markt) +
    • +
    • Add: + Log a warning at start up if a JSSE TLS connector is configured with + a trusted certificate that is either not yet valid or has expired. + (markt) +
    • +
    +
    +

    Jasper

    +
      +
    • Fix: + When writing out a full web.xml file with JspC ensure that the encoding + used in the XML prolog matches the encoding used to write the contents + of the file. (markt) +
    • +
    • Fix: + Improve the error handling for custom tags to ensure that the tag is + returned to the pool or released and destroyed once used. (markt) +
    • +
    • Fix: + 60032: Fix handling of method calls that use varargs within + EL value expressions. (markt) +
    • +
    • Fix: + Ignore engineOptionsClass and scratchdir when + running under a security manager. (markt) +
    • +
    • Fix: + Fixed StringIndexOutOfBoundsException. Based on a patch provided by + wuwen via Github. (violetagg) +
    • +
    +
    +

    WebSocket

    +
      +
    • Fix: + 59908: Ensure that a reason phrase is included in the close + message if a session is closed due to a timeout. (markt) +
    • +
    +
    +

    Web applications

    +
      +
    • Fix: + 59867: Correct the documentation provided by Manager's + 403.jsp. (violetagg) +
    • +
    • Fix: + 59868: Clarify the documentation for the Manager web + application to make clearer that the host name and IP address in the + server section are the primary host name and IP address. (markt) +
    • +
    • Fix: + 59940: Correct the name of the + truststorePassword attribute of the + SSLHostConfig element in the configuration documentation. + (markt) +
    • +
    • Fix: + MBeans Descriptors How-To is moved to + mbeans-descriptors-howto.html. Patch provided by Radoslav + Husar. (violetagg) +
    • +
    • Fix: + Update NIO Connector configuration documentation with an information + about socket.directSslBuffer. (violetagg) +
    • +
    • Fix: + 60034: Correct a typo in the Manager How-To page of the + documentation web application. (markt) +
    • +
    +
    +

    jdbc-pool

    +
      +
    • Fix: + In order to avoid the unintended skip of PoolCleaner, + remove the check code of the execution interval in the task that has + been scheduled. (kfujino) +
    • +
    • Fix: + 59850: Ensure that the ResultSet is closed when + enabling the StatementCache interceptor. (kfujino) +
    • +
    • Fix: + 59923: Reduce the default value of + validationInterval in order to avoid the potential issue + that continues to return an invalid connection after database restart. + (kfujino) +
    • +
    • Fix: + Ensure that the ResultSet is returned as Proxy object when + enabling the StatementDecoratorInterceptor. (kfujino) +
    • +
    • Fix: + 60043: Ensure that the suspectTimeout works + without removing connection when the removeAbandoned is + disabled. (kfujino) +
    • +
    • Fix: + Add log message of when returning the connection that has been marked + suspect. (kfujino) +
    • +
    • Fix: + Correct Javadoc for ConnectionPool.suspect(). Based on a + patch by Yahya Cahyadi. (markt) +
    • +
    +
    +

    Other

    +
      +
    • Add: + 59871: Add a property (timeFormat) to + JULI's OneLineFormatter to enable the format of the + time stamp used in log messages to be configured. (markt) +
    • +
    • Fix: + 59899: Update Tomcat's copy of the Java Persistence + annotations to include the changes made in 2.1 / JavaEE 7. (markt) +
    • +
    • Fix: + Fixed typos in mbeans-descriptors.xml files. (violetagg) +
    • +
    • Update: + Update the internal fork of Commons BCEL to r1757132 to align with the + BCEL 6 release. (markt) +
    • +
    • Update: + Update the internal fork of Commons DBCP 2 to r1757164 to pick up a + couple of bug fixes. (markt) +
    • +
    • Update: + Update the internal fork of Commons Codec to r1757174. Code formatting + changes only. (markt) +
    • +
    • Update: + Update the internal fork of Commons FileUpload to afdedc9. This pulls in + a fix to improve the performance with large multipart boundaries. + (markt) +
    • +
    +
    +

    2016-07-12 Tomcat 8.5.4 (markt)

    +

    Catalina

    +
      +
    • Fix: + 57705: Add debug logging for requests denied by the remote + host and remote address valves and filters. Based on a patch by Graham + Leggett. (markt) +
    • +
    • Fix: + Correct a regression in the fix for 58588 that removed the + entire org.apache.juli package from the embedded JARs + rendering them unusable. (markt) +
    • +
    • Add: + 59399: Add a new option to the Realm implementations that + ship with Tomcat that allows the HTTP status code used for HTTP -> HTTPS + redirects to be controlled per Realm. (markt) +
    • +
    • Update: + Change the default of the + sessionCookiePathUsesTrailingSlash attribute of the + Context element to false since the problems + caused when a Servlet is mapped to /* are more significant + than the security risk of not enabling this option by default. (markt) +
    • +
    • Fix: + Follow-up to 59655. Improve the documentation for configuring + permitted cookie names. Patch provided by Kyohei Nakamura. (markt) +
    • +
    • Fix: + Do not attempt to start web resources during a web application's + initialisation phase since the web application is not fully configured + at that point and the web resources may not be correctly configured. + (markt) +
    • +
    • Fix: + 59708: Modify the LockOutRealm logic. Valid authentication + attempts during the lock out period will no longer reset the lock out + timer to zero. (markt) +
    • +
    • Fix: + Improve error handling around user code prior to calling + InstanceManager.destroy() to ensure that the method is + executed. (markt) +
    • +
    +
    +

    Coyote

    +
      +
    • Code: + Refactor the certificate keystore and trust store generation to make it + easier for embedded users to inject their own key stores. (markt) +
    • +
    • Add: + 59233: Add the ability to add TLS virtual hosts dynamically. + (markt) +
    • +
    • Update: + Add a maxConcurrentStreamExecution on the HTTP/2 + protocol handler to allow restricting the amount of concurrent stream + that are being executed in a single connection. The default is to + not limit it. (remm) +
    • +
    • Fix: + Correct a problem with ServletRequest.getServerPort() for + secure HTTP/2 connections that meant an incorrect value was returned when + using the default port. (markt) +
    • +
    • Fix: + Improve error handling around user code prior to calling + InstanceManager.destroy() to ensure that the method is + executed. (markt) +
    • +
    • Fix: + Document the default for the HTTP/2 configuration parameter + maxConcurrentStreamExecution as 20. (markt) +
    • +
    +
    +

    Jasper

    +
      +
    • Fix: + Improve error handling around user code prior to calling + InstanceManager.destroy() to ensure that the method is + executed. (markt) +
    • +
    +
    +

    WebSocket

    +
      +
    • Code: + Now the WebSocket implementation is not built directly on top of the + Servlet API and can use Tomcat internals, there is no need for the + dedicated WebSocket Executor. It has been replaced by the use of the + Connector/Endpoint provided Executor. (markt) +
    • +
    • Fix: + Improve error handling around user code prior to calling + InstanceManager.destroy() to ensure that the method is + executed. (markt) +
    • +
    +
    +

    Web Applications

    +
      +
    • Fix: + Do not log an additional case of IOExceptions in the + error handler for the Drawboard WebSocket example when the root cause is + the client disconnecting since the logs add no value. (markt) +
    • +
    • Fix: + 59642: Mention the localDataSource in the + DataSourceRealm section of the Realm How-To. (markt) +
    • +
    • Fix: + 59672: Update the security considerations page of the + documentation web application to take account of the fact that the + Manager and HostManager applications now have a + RemoteAddrValve configured by default. (markt) +
    • +
    • Fix: + Follow-up to the fix for 59399. Ensure that the new attribute + transportGuaranteeRedirectStatus is documented for all + Realms. Also document the NullRealm and + when it is automatically created for an Engine. (markt) +
    • +
    • Fix: + Fix the description of maxAge attribute in jdbc-pool doc. + This attribute works both when a connection is returned and when a + connection is borrowed. (kfujino) +
    • +
    • Fix: + 59774: Correct the prefix values in the + documented examples for configuring the AccessLogValve. + Patch provided by Mike Noordermeer. (markt) +
    • +
    +
    +

    Extras

    +
      +
    • Code: + 58588: Remove the JULI extras package from the distribution. + It was only useful for switching Tomcat's internal logging to log4j + 1.2.x and that version of log4j is no longer supported. No additional + Tomcat code is required if switching Tomcat's internal logging to log + via log4j 2.x. (markt) +
    • +
    +
    +

    Tribes

    +
      +
    • Add: + Add log message when the ping has timed-out. (kfujino) +
    • +
    • Fix: + If the ping message has been received at the + AbstractReplicatedMap#leftOver method, ensure that notify + the member is alive than ignore it. (kfujino) +
    • +
    +
    +

    jdbc-pool

    +
      +
    • Fix: + Fix the duplicated connection release when connection verification + failed. (kfujino) +
    • +
    • Fix: + Ensure that do not remove the abandoned connection that has been already + released. (kfujino) +
    • +
    +
    +

    Other

    +
      +
    • Update: + 59276: Update optional Checkstyle library to 6.17. (kkolinko) +
    • +
    • Add: + Use the mirror network rather than the ASF master site to download the + current ASF dependencies. (markt) +
    • +
    • Update: + Update the packaged version of the Tomcat Native Library to 1.2.8 to + pick up the latest fixes and make 1.2.8 the minimum recommended version. + (markt) +
    • +
    • Code: + Use UTF-8 with a standard prolog for all XML files. (markt) +
    • +
    +
    +

    2016-06-13 Tomcat 8.5.3 (markt)

    +

    Catalina

    +
      +
    • Fix: + RMI Target related memory leaks are avoidable which makes them an + application bug that needs to be fixed rather than a JRE bug to work + around. Therefore, start logging RMI Target related memory leaks on web + application stop. Add an option that controls if the check for these + leaks is made. Log a warning if running on Java 9 with this check + enabled but without the command line option it requires. (markt) +
    • +
    • Fix: + Ensure NPE will not be thrown during deployment when scanning jar files + without MANIFEST.MF file. (violetagg) +
    • +
    • Code: + Remove the clearReferencesStatic option from + StandardContext. It was known to cause problems with some + libraries (such as log4j) and was only linked to suspected memory leaks + rather than known memory leaks. It had been disabled by default with no + increase in the reports of memory leaks for some time. (markt) +
    • +
    • Fix: + 59604: Correct the assumption made in the URL decoding that + the default platform encoding is always compatible with ISO-8859-1. This + assumption is not always valid, e.g. on z/OS. (markt) +
    • +
    • Fix: + 59608: Skip over any invalid Class-Path attribute + from JAR manifests. Log errors at debug level due to many bad libraries. + (remm) +
    • +
    • Fix: + Fix error message when failed to register MBean. (kfujino) +
    • +
    • Fix: + 59655: Configure the cookie name validation to use RFC6265 rules by default to + align it with the default cookie parser. Document the impact system properties have on + cookie name validation. (mark) +
    • +
    +
    +

    Coyote

    +
      +
    • Fix: + Ensure that requests with HTTP method names that are not tokens (as + required by RFC 7231) are rejected with a 400 response. (markt) +
    • +
    • Fix: + When an asynchronous request is processed by the AJP connector, ensure + that request processing has fully completed before starting the next + request. (markt) +
    • +
    • Fix: + Improve handling of HTTP/2 stream resets. (markt) +
    • +
    • Add: + 58750: The HTTP Server header is no longer set by default. A + Server header may be configured by setting the server + attribute on the Connector. A new Connector + attribute, serverRemoveAppProvidedValues may be used to + remove any Server header set by a web application. (markt) +
    • +
    • Fix: + 59564: Correct offset when reading into HTTP/2 input buffer + that could cause problems reading request bodies. (violetagg/markt) +
    • +
    • Fix: + Modify the handling of read/write timeouts so that the appropriate error + handling (ReadListener.onError(), + WriteListener.onError() or + AsyncListener.onError()) is called. (markt) +
    • +
    • Fix: + If an async dispatch results in the completion of request processing, + ensure that any remaining request body is swallowed before starting the + processing of the next request else the remaining body may be read as the + start of the next request leading to a 400 response. (markt) +
    • +
    • Fix: + Fix a cause of multiple attempts to close the same socket. (markt) +
    • +
    +
    +

    Jasper

    +
      +
    • Fix: + 59567: Fix NPE scanning webapps for TLDs when an exploded + JAR has an empty WEB-INF/classes/META-INF folder. (remm) +
    • +
    • Fix: + Fix a memory leak in the expression language implementation that caused + the class loader of the first web application to use expressions to be + pinned in memory. (markt) +
    • +
    • Fix: + 59654: Improve error message when attempting to use a TLD + file from an invalid location. Patch provided by Huxing Zhang. (markt) +
    • +
    +
    +

    WebSocket

    +
      +
    • Fix: + 59659: Fix possible memory leak in WebSocket handling of + unexpected client disconnects. (markt) +
    • +
    +
    +

    Web applications

    +
      +
    • Fix: + 58891: Update the SSL how-to. Based on a suggestion by + Alexander Kjäll. (markt) +
    • +
    +
    +

    jdbc-pool

    +
      +
    • Fix: + Fix a memory leak with the pool cleaner thread that retained a reference + to the web application class loader for the first web application to use + a connection pool. (markt) +
    • +
    +
    +

    Other

    +
      +
    • Update: + Update the internal fork of Commons DBCP 2 to r1743696 (2.1.1 plus + additional fixes). (markt) +
    • +
    • Update: + Update the internal fork of Commons Pool 2 to r1743697 (2.4.2 plus + additional fixes). (markt) +
    • +
    • Update: + Update the internal fork of Commons File Upload to r1743698 (1.3.1 plus + additional fixes). (markt) +
    • +
    • Fix: + 58626: Add support for a new environment variable + (USE_NOHUP) that causes nohup to be used when + starting Tomcat. It is disabled by default except on HP-UX where it is + enabled by default since it is required when starting Tomcat at boot on + HP-UX. (markt) +
    • +
    +
    +

    2016-05-16 Tomcat 8.5.2 (markt)

    +

    Catalina

    +
      +
    • Fix: + Ensure that annotated web components packed in web fragments will be + processed when unpackWARs is enabled. (violetagg) +
    • +
    +
    +

    not released Tomcat 8.5.1 (markt)

    +

    Catalina

    +
      +
    • Fix: + 59206: Ensure NPE will not be thrown by + o.a.tomcat.util.file.ConfigFileLoader when + catalina.base is not specified. (violetagg) +
    • +
    • Fix: + 59217: Remove duplication in the recycling of the path in + o.a.tomcat.util.http.ServerCookie. Patch is provided by + Kyohei Nakamura. (violetagg) +
    • +
    • Fix: + Fixed possible NPE in + o.a.catalina.loader.WebappClassLoaderBase.getResourceAsStream + (violetagg) +
    • +
    • Fix: + 59213: Async dispatches should be based off a wrapped request. + (remm) +
    • +
    • Fix: + Ensure that javax.servlet.ServletRequest and + javax.servlet.ServletResponse provided during + javax.servlet.AsyncListener registration are made + available via javax.servlet.AsyncEvent.getSuppliedRequest + and javax.servlet.AsyncEvent.getSuppliedResponse + (violetagg) +
    • +
    • Fix: + 59219: Ensure AsyncListener.onError() is called + if an Exception is thrown during async processing. (markt) +
    • +
    • Fix: + 59220: Ensure that AsyncListener.onComplete() is + called if the async request times out and the response is already + committed. (markt) +
    • +
    • Fix: + 59226: Process the Class-Path attribute from + JAR manifests for JARs on the class path excluding JARs packaged in + WEB-INF/lib. (markt) +
    • +
    • Fix: + 59255: Fix possible NPE in mapper. (kkolinko/remm) +
    • +
    • Fix: + 59256: slf4j-taglib*.jar should not be excluded + from the standard JAR scanning by default. (violetagg) +
    • +
    • Fix: + Clarify in the log message that specifying both urlPatterns and value + attributes in WebServlet and WebFilter annotations is not allowed. + (violetagg) +
    • +
    • Fix: + Ensure the exceptions caused by Valves will be available in the log + files so that they can be evaluated when + o.a.catalina.valves.ErrorReportValve.showReport is + disabled. Patch is provided by Svetlin Zarev. (violetagg) +
    • +
    • Fix: + Remove unused distributable attribute that is defined as + TransientAttribute of Manager in StoreConfig. + (kfujino) +
    • +
    • Fix: + Fix handling of Cluster Receiver in StoreConfig. The bind + and host attributes define as + TransientAttribute. (kfujino) +
    • +
    • Fix: + 59261: ServletRequest.getAsyncContext() now + throws an IllegalStateException as required by the Servlet + specification if the request is not in asynchronous mode when called. + (markt) +
    • +
    • Fix: + 59269: Correct the implementation of + PersistentManagerBase so that minIdleSwap + functions as designed and sessions are swapped out to keep the active + session count below maxActiveSessions. (markt) +
    • +
    • Add: + Add the org.apache.catalina.servlet4preview package that + can be used to gain early access to Servlet 4.0 features. Note that this + package will not be present in Tomcat 9. (markt) +
    • +
    • Fix: + Correctly configure the base path for a resources directory provided by + an expanded JAR file. Patch provided by hengyunabc. (markt) +
    • +
    • Add: + When multiple compressed formats are available and the client does not + express a preference, use the server order to determine the preferred + format. Based on a patch by gmokki. (markt) +
    • +
    • Fix: + 59284: Allow the Tomcat provided JASPIC + SimpleServerAuthConfig to pick up module configuration + properties from either the property set passed to its constructor or + from the properties passed in the call to getAuthContext. + Based on a patch by Thomas Maslen. (markt) +
    • +
    • Fix: + 59310: Do not add a Content-Length: 0 header for + custom responses to HEAD requests that do not set a + Content-Length value. (markt) +
    • +
    • Fix: + When normalizing paths, improve the handling when paths end with + /. or /.. and ensure that input and output are + consistent with respect to whether or not they end with /. + (markt) +
    • +
    • Fix: + 59317: Ensure that + HttpServletRequest.getRequestURI() returns an encoded URI + rather than a decoded URI after a dispatch. (markt) +
    • +
    • Fix: + Use the correct URL for the fragment when reporting errors processing + a web-fragment.xml file from a JAR located in an unpacked + WAR. (markt) +
    • +
    • Fix: + Ensure that JarScanner only uses the explicit call-back to + process WEB-INF/classes and only when configured to treat + the contents of WEB-INF/classes as a possible exploded JAR. + (markt) +
    • +
    • Code: + Remove the java2DDisposerProtection option from the + JreMemoryLeakPreventionListener. The leak is fixed in Java + 7 onwards and Tomcat 8 requires Java 7 so the option is unnecessary. + (markt) +
    • +
    • Fix: + Ensure that the value for the header X-Frame-Options is + constructed correctly according to the specification when + ALLOW-FROM option is used. (violetagg) +
    • +
    • Fix: + Fix an IllegalArgumentException if the first use of an + internal Response object requires JASPIC authentication. + (markt) +
    • +
    • Fix: + Do not trigger unnecessary session ID changes when using JASPIC and the + user is authenticated using cached credentials. (markt) +
    • +
    • Fix: + 59437: Ensure that the JASPIC CallbackHandler is + thread-safe. (markt) +
    • +
    • Fix: + 59449: In ContainerBase, ensure that the process + to remove a child container is the reverse of the process to add one. + Patch provided by Huxing Zhang. (markt) +
    • +
    +
    +

    Coyote

    +
      +
    • Fix: + Align cipher configuration parsing with current OpenSSL master. (markt) +
    • +
    • Update: + Change the default for honorCipherOrder to + false. With the current default TLS configuration, it is no + longer necessary for this to be true for a reasonably + secure configuration. (markt) +
    • +
    • Add: + Add a new environment variable JSSE_OPTS that is intended + to be used to pass JVM wide configuration to the JSSE implementation. + The default value is -Djdk.tls.ephemeralDHKeySize=2048 + which protects against weak Diffie-Hellman keys. (markt) +
    • +
    • Fix: + When running on Java 7, exclude DHE ciphers from the default cipher list + for JSSE connectors since they use weak 768 bit DH keys and cannot be + configured to use more secure keys. (markt) +
    • +
    • Fix: + 58970: Fix a connection counting bug in the NIO connector + that meant some dropped connections were not removed from the current + connection count. (markt) +
    • +
    • Fix: + 59289: Do not recycle upgrade processors in unexpected close + situations. (remm) +
    • +
    • Fix: + 59295: Use Locale.toLanguageTag() to construct + the Content-Language HTTP header to ensure the locale is + correctly represented. Patch provided by zikfat. (markt) +
    • +
    • Update: + 59295: Add support for using pem encoded certificates with + JSSE SSL. Submitted by Emmanuel Bourg with additional tweaks. (remm) +
    • +
    • Fix: + Make the TLS certificate chain available to clients when using + JSSE+OpenSSL with the certificate chain stored in a Java KeyStore. + (markt) +
    • +
    • Fix: + Work around a + known issue in OpenSSL that does not permit the TLS handshake to be + failed if the ALPN negotiation fails. (markt) +
    • +
    • Update: + 59421: Add direct HTTP/2 connection support. (remm) +
    • +
    • Fix: + Correctly handle a call to AsyncContext.complete() from a + non-container thread when non-blocking I/O is being used. (markt) +
    • +
    • Fix: + 59451: Correct Javadoc for MessageBytes. Patch + provided by Kyohei Nakamura. (markt) +
    • +
    • Fix: + 59450: Correctly handle the case where the + LegacyCookieProcessor is configured with + allowHttpSepsInV0 set to false and + forwardSlashIsSeparator set to true. Patch + provided by Kyohei Nakamura. (markt) +
    • +
    +
    +

    Jasper

    +
      +
    • Fix: + When scanning JARs for TLDs, correctly handle the (rare) case where a + JAR has been exploded into WEB-INF/classes and the web + application is deployed as a packed WAR. (markt) +
    • +
    • Fix: + 59640: NPEs with not found TLDs. (remm) +
    • +
    +
    +

    WebSocket

    +
      +
    • Fix: + 59189: Explicitly release the native memory held by the + Inflater and Deflater when using + PerMessageDeflate and the WebSocket session ends. Based on a patch by + Henrik Olsson. (markt) +
    • +
    • Fix: + Return back a container specific extension to the WsServerContainer + to allow frameworks to more easily dispatch requests to WebSocket + endpoints. (violetagg) +
    • +
    • Fix: + Fix a regression caused by the connector refactoring and ensure that the + thread context class loader is set to the web application + classloader when processing WebSocket messages on the server. (markt) +
    • +
    • Fix: + Ensure that a client disconnection triggers the error handling for the + associated WebSocket end point. (markt) +
    • +
    • Add: + Make WebSocket client more robust when handling errors during the close + of a WebSocket session. (markt) +
    • +
    +
    +

    Web applications

    +
      +
    • Fix: + 59210: Server push example has to use + o.a.catalina.connector.RequestFacade when obtaining + o.a.catalina.core.ApplicationPushBuilder. Patch is + provided by Huxing Zhang. (violetagg) +
    • +
    • Fix: + 59218: Correct the path to jaspic-providers.xml + in Jaspic How-To. Patch is provided by Tatsuya Bessho. (violetagg) +
    • +
    • Fix: + Remove button that has accidentally been added to the host manager. + Submitted by Coty Sutherland. (remm) +
    • +
    • Fix: + Update in the documentation the link to the maven repository where + Tomcat snapshot artifacts are deployed. (markt/violetagg) +
    • +
    • Fix: + Clarify in the documentation that calls to + ServletContext.log(String, Throwable) or + GenericServlet.log(String, Throwable) are logged at the + SEVERE level. (violetagg) +
    • +
    • Fix: + Correct a typo in SSL/TLS Configuration How-To. + Issue reported via comments.apache.org. (violetagg) +
    • +
    +
    +

    Tribes

    +
      +
    • Fix: + Avoid NPE when a proxy node failed to retrieve a backup entry. (kfujino) +
    • +
    • Add: + Add log of when received an unexpected messages. (kfujino) +
    • +
    • Add: + Add the flag indicating that member is a localMember. (kfujino) +
    • +
    • Fix: + Fix potential NPE that depends on the setting order of attributes of + static member when using the static cluster. (kfujino) +
    • +
    • Add: + Add get/set method for the channel that is related to + ChannelInterceptor. (kfujino) +
    • +
    • Fix: + As with the multicast cluster environment, in the static cluster + environment, the local member inherits properties from the cluster + receiver. (kfujino) +
    • +
    • Add: + Add get/set method for the channel that is related to each Channel + services. (kfujino) +
    • +
    • Add: + Add name to channel in order to identify channels. In tomcat cluster + environment, it is set the cluster name + "-Channel" as default value. + (kfujino) +
    • +
    • Add: + Add the channel name to the thread which is invoked by channel services + in order to identify the associated channel. (kfujino) +
    • +
    • Fix: + Ensure that clear the channel instance from channel services when + stopping channel. (kfujino) +
    • +
    • Add: + Implement map state in the replication map. (kfujino) +
    • +
    • Fix: + Ensure that the ping is not executed during the start/stop of the + replication map. (kfujino) +
    • +
    • Fix: + In ping processing in the replication map, send not the + INIT message but the newly introduced PING + message. (kfujino) +
    • +
    +
    +

    Other

    +
      +
    • Fix: + 59209: Remove honorCipherOrder=false attribute + from the connector example in server.xml. When the block is uncommented + the connector will use the default value for this attribute which is + false. If one needs to enable it, one can add it + explicitly to the connector definition. Use of this feature requires + Java 8 or later. Patch is provided by Huxing Zhang. (violetagg) +
    • +
    • Fix: + 59211: Add hamcrest to Eclipse classpath. Patch is provided + by Huxing Zhang. (violetagg) +
    • +
    • Update: + 59280: Update the NSIS Installer used to build the + Windows Installers to version 2.51. (kkolinko) +
    • +
    • Update: + Update the packaged version of the Tomcat Native Library to 1.2.7 to + pick up the Windows binaries that are based on OpenSSL 1.0.2h and APR + 1.5.2. (markt) +
    • +
    +
    +

    2016-03-24 Tomcat 8.5.0 (markt)

    +

    General

    +
      +
    • Update: + Remove support for Comet. (markt) +
    • +
    • Update: + Tighten up the default file permissions for the .tar.gz + distribution so no files or directories are world readable by default. + Configure Tomcat to run with a default umask of 0027 which + may be overridden by setting UMASK in + setenv.sh. (markt) +
    • +
    • Update: + Remove native code (Windows Service Wrapper, APR/native connector) + support for Windows Itanium. (markt) +
    • +
    +
    +

    Catalina

    +
      +
    • Update: + The default HTTP cookie parser has been changed to + org.apache.tomcat.util.http.Rfc6265CookieProcessor. (markt) +
    • +
    • Code: + Refactor creation of MapperListener to ensure that the + Mapper used is the Mapper associated with the + Service for which the listener was created. (markt) +
    • +
    • Add: + Move the functionality that provides redirects for context roots and + directories where a trailing / is added from the Mapper to + the DefaultServlet. This enables such requests to be + processed by any configured Valves and Filters before the redirect is + made. This behaviour is configurable via the + mapperContextRootRedirectEnabled and + mapperDirectoryRedirectEnabled attributes of the Context + which may be used to restore the previous behaviour. (markt) +
    • +
    • Code: + Refactor Service.getContainer() to return an + Engine rather than a Container. (markt) +
    • +
    • Fix: + 34319: Only load those keys in + StoreBase.processExpire from JDBCStore that are old enough + to be expired. Based on a patch by Tom Anderson. (fschumacher) +
    • +
    • Add: + 58351: Make the server build date and server version number + accessible via JMX. Patch provided by Huxing Zhang. (markt) +
    • +
    • Add: + 56917: As per RFC7231 (HTTP/1.1), allow HTTP/1.1 and later + redirects to use relative URIs. This is controlled by a new attribute + useRelativeRedirects on the Context and + defaults to true. (markt) +
    • +
    • Fix: + 58629: Allow an embedded Tomcat instance to start when the + Service has no Engine configured. (markt) +
    • +
    • Fix: + Correctly notify the MapperListener associated with a Service if the + Engine for that Service is changed. (markt) +
    • +
    • Add: + Make a web application's CredentialHandler available through a context + attribute. This allows a web application to use the same algorithm + for validating or generating new stored credentials from cleartext + ones. (schultz) +
    • +
    • Fix: + 58635: Enable break points to be set within agent code when + running Tomcat with a Java agent. Based on a patch by Huxing Zhang. + (markt) +
    • +
    • Fix: + Fixed potential NPE in HostConfig while deploying an + application. Issue reported by coverity scan. (violetagg) +
    • +
    • Fix: + 58655: Fix an IllegalStateException when + calling HttpServletResponse.sendRedirect() with the + RemoteIpFilter. This was caused by trying to correctly + generate the absolute URI for the redirect. With the fix for + 56917, redirects may now be relative making the + sendRedirect() implementation for the + RemoteIpFilter much simpler. This also addresses issues + where the redirect may not have behaved as expected when redirecting + from http to https to from https to http. (markt) +
    • +
    • Fix: + 58657: Exceptions in a Servlet 3.1 ReadListener + or WriteListener do not need to be immediately fatal to the + connection. Allow an error response to be written. (markt) +
    • +
    • Fix: + Correct implementation of + validateClientProvidedNewSessionId so client provided + session IDs may be rejected if validation is enabled. (markt) +
    • +
    • Fix: + 58701: Reset the instanceInitialized field in + StandardWrapper when unloading a Servlet so that a new + instance may be correctly initialized. (markt) +
    • +
    • Update: + Add a new flag aprPreferred to the Apr listener. if set to + false, when using the connector defaults, it will use + NIO + OpenSSL if tomcat-native is available, rather than the APR + connector. (remm) +
    • +
    • Fix: + Add path parameter handling to + HttpServletRequest.getContextPath(). This is a follow-up to + the fix for 57215. (markt) +
    • +
    • Fix: + 58692: Make StandardJarScanner more robust. Log + a warning if a class path entry cannot be scanned rather than triggering + the failure of the web application. Includes a test case written by + Derek Abdine. (markt) +
    • +
    • Fix: + 58702: Ensure an access log entry is generated if the client + aborts the connection. (markt) +
    • +
    • Fix: + Fixed various issues reported by Findbugs. (violetagg) +
    • +
    • Fix: + 58735: Add support for the X-XSS-Protection + header to the HttpHeaderSecurityFilter. Patch provided by + Jacopo Cappellato. (markt) +
    • +
    • Fix: + Add the StatusManagerServlet to the list of Servlets that + can only be loaded by privileged applications. (markt) +
    • +
    • Fix: + Simplify code and fix messages in + org.apache.catalina.core.DefaultInstanceManager class. + (kkolinko) +
    • +
    • Fix: + 58751: Correctly handle the case where an + AsyncListener dispatches to a Servlet on an asynchronous + timeout and the Servlet uses sendError() to trigger an + error page. Includes a test case based on code provided by Andy + Wilkinson.(markt) +
    • +
    • Fix: + Ensure that the proper file encoding, if specified, will be used when + a readme file is served by DefaultServlet. (violetagg) +
    • +
    • Fix: + Fix declaration of localPort attribute of Connector MBean: + it is read-only. (kkolinko) +
    • +
    • Fix: + 58766: Make skipping non-class files during annotation + scanning faster by checking the file name first. Improve debug logging. + (kkolinko) +
    • +
    • Fix: + 58768: Log a warning if a redirect fails because of an + invalid location. (markt) +
    • +
    • Code: + 58827: Remove remains of JSR-77 implementation. (markt) +
    • +
    • Fix: + 58836: Correctly merge query string parameters when + processing a forwarded request where the target includes a query string + that contains a parameter with no value. (markt/kkolinko) +
    • +
    • Fix: + Make sure that shared Digester is reset in an unlikely error case + in HostConfig.deployWAR(). (kkolinko) +
    • +
    • Add: + Extend the feature available in the cluster session manager + implementations that enables session attribute replication to be + filtered based on attribute name to all session manager implementations. + Note that configuration attribute name has changed from + sessionAttributeFilter to + sessionAttributeNameFilter. Apply the filter on load as + well as unload to ensure that configuration changes made while the web + application is stopped are applied to any persisted data. (markt) +
    • +
    • Add: + Extend the session attribute filtering options to include filtering + based on the implementation class of the value and optional + WARN level logging if an attribute is filtered. These + options are available for all of the Manager implementations that ship + with Tomcat. When a SecurityManager is used filtering will + be enabled by default. (markt) +
    • +
    • Code: + Remove distributable and maxInactiveInterval + from the Manager interface because the attributes are never + used. The equivalent attributes from the Context always + take precedence. (markt) +
    • +
    • Fix: + 58867: Improve checking on Host start for WAR files that have + been modified while Tomcat has stopped and re-expand them if + unpackWARs is true. (markt) +
    • +
    • Fix: + 58900: Correctly undeploy symlinked resources and prevent an + infinite cycle of deploy / undeploy. (markt) +
    • +
    • Fix: + Protect initialization of ResourceLinkFactory when + running with a SecurityManager. (kkolinko) +
    • +
    • Fix: + Correct a thread safety issue in the filtering of session attributes + based on the implementing class name of the value object. (markt) +
    • +
    • Fix: + Fix class loader decision on the delegation for class loading and + resource lookup and make it faster too. (rjung) +
    • +
    • Fix: + 58905: Ensure that Tomcat.silence() silences the + correct logger and respects the current setting. (markt) +
    • +
    • Fix: + 58946: Ensure that the request parameter map remains + immutable when processing via a RequestDispatcher. (markt) +
    • +
    • Fix: + Ensure that /WEB-INF/classes is never processed as a web + fragment. (markt) +
    • +
    • Update: + Switch default connector when native is installed. Unless configured + otherwise, the NIO endpoint will be used by default. If SSL is + configured, OpenSSL will be used rather than JSSE. (remm) +
    • +
    • Fix: + Correct a regression in the fix for 58867. When configuring a + Context to use an external directory for the docBase, and + that directory happens to be located along side the original WAR, use + the directory as the docBase rather than expanding the + WAR into the appBase and using the newly created expanded + directory as the docBase. (markt) +
    • +
    • Add: + 58988: Special characters in the substitutions for the + RewriteValve can now be quoted with a backslash. (fschumacher) +
    • +
    • Fix: + 58999: Fix class and resource name filtering in + WebappClassLoader. It throws a StringIndexOutOfBoundsException if the + name is exactly "org" or "javax". (rjung) +
    • +
    • Add: + Add JASPIC (JSR-196) support. (markt) +
    • +
    • Add: + Make checking for var and map replacement in RewriteValve a bit stricter + and correct detection of colon in var replacement. (fschumacher) +
    • +
    • Fix: + Refactor the web application class loader to reduce the impact of JAR + scanning on the memory footprint of the web application. (markt) +
    • +
    • Fix: + Fix some resource leaks in the error handling for accessing files from + JARs and WARs. (markt) +
    • +
    • Fix: + Refactor the JAR and JAR-in-WAR resource handling to reduce the memory + footprint of the web application. (markt) +
    • +
    • Fix: + Refactor the web.xml parsing so a new parser is created every time the + web application starts rather than creating and caching the parser when + the Context is created. This enables the parser to take account of + modified Context configuration parameters and reduces (slightly) the + memory footprint of a running Tomcat instance. (markt) +
    • +
    • Update: + Switch the web application class loader to the + ParallelWebappClassLoader by default. (markt) +
    • +
    • Fix: + 57809: Remove the custom context attribute that held the + effective web.xml. Components needing access to configuration + information may access it via the Servlet API. (markt) +
    • +
    • Fix: + Refactor JAR scanning to reduce memory footprint. (markt) +
    • +
    • Fix: + 59001: Correctly handle the case when Tomcat is installed on + a path where one of the segments ends in an exclamation mark. (markt) +
    • +
    • Fix: + Expand the fix for 59001 to cover the special sequences used + in Tomcat's custom jar:war: URLs. (markt) +
    • +
    • Fix: + 59043: Avoid warning while expiring sessions associated with + a single sign on if HttpServletRequest.logout() is used. + (markt) +
    • +
    • Fix: + 59054: Ensure that using the + CrawlerSessionManagerValve in a distributed environment + does not trigger an error when the Valve registers itself in the + session. (markt) +
    • +
    • Fix: + Add socket properties support to storeconfig. (remm) +
    • +
    • Fix: + Fix incorrect parsing of the NE and NC flags in rewrite rules. (remm) +
    • +
    • Fix: + 59065: Correct the timing of the check for colons in paths + on non-Windows systems implemented in catalina.sh so it + works correctly with Cygwin. Patch provided by Ed Randall. (markt) +
    • +
    • Fix: + When a Host is configured with an appBase that does not exist, create + the appBase before trying to expand an external WAR file into it. + (markt) +
    • +
    • Fix: + 59115: When using the Servlet 3.0 file upload, the submitted + file name may be provided as a token or a quoted-string. If a + quoted-string, unquote the string before returning it to the user. + (markt) +
    • +
    • Fix: + 59123: Close NamingEnumeration objects used by + the JNDIRealm once they are no longer required. + (fschumacher/markt) +
    • +
    • Add: + Implement the proposed Servlet 4.0 API to provide mapping type + information for the current request. (markt) +
    • +
    • Fix: + 59138: Correct a false positive warning for ThreadLocal + related memory leaks when the key class but not the value class has been + loaded by the web application class loader. (markt) +
    • +
    • Add: + 59017: Make the pre-compressed file support in the Default + Servlet generic so any compression may be used rather than just gzip. + Patch provided by Mikko Tiihonen. (markt) +
    • +
    • Fix: + 59145: Don't log an invalid warning when a user logs out of + a session associated with SSO. (markt) +
    • +
    • Fix: + 59150: Add an additional flag on APR listener to allow + disabling automatic use of OpenSSL. (remm) +
    • +
    • Fix: + 59151: Fix a regression in the fix for 56917 that + added additional (and arguably unnecessary) validation to the provided + redirect location. (markt) +
    • +
    • Fix: + 59154: Fix a NullPointerException in the + JAASMemoryLoginModule resulting from the introduction of + the CredentialHandler to Realms. + (schultz/markt) +
    • +
    +
    +

    Coyote

    +
      +
    • Update: + Remove support for the HTTP BIO and AJP BIO connectors. (markt) +
    • +
    • Code: + Refactor HTTP upgrade and AJP implementations to reduce duplication. + (markt) +
    • +
    • Add: + Add support for HPACK header encoding and decoding, contributed + by Stuart Douglas. (remm) +
    • +
    • Add: + 57108: Add support for Server Name Indication (SNI). There + has been significant changes to the SSL configuration in server.xml to + support this. (markt) +
    • +
    • Add: + Add SSL engine for JSSE backed by OpenSSL. Includes ALPN support. + Based on code contributed by Numa de Montmollin and derived from code + developed by Twitter and Netty. (remm) +
    • +
    • Fix: + RFC 7230 states that clients should ignore reason phrases in HTTP/1.1 + response messages. Since the reason phrase is optional, Tomcat no longer + sends it. As a result the system property + org.apache.coyote.USE_CUSTOM_STATUS_MSG_IN_HEADER is no + longer used and has been removed. (markt) +
    • +
    • Update: + The minimum required Tomcat Native version has been increased to 1.2.2. + The 1.2.x branch includes ALPN and SNI support which are required for + HTTP/2. (markt) +
    • +
    • Add: + Add support for HTTP/2 including server push. (markt) +
    • +
    • Fix: + 58621: The certificate chain cannot be set using the main + certificate attribute, so restore the certificate chain property. (remm) +
    • +
    • Fix: + Allow a new SSL config type where a connector can use either JSSE or + OpenSSL. Both could be allowed, but it would likely create support + issues. This type is used by the OpenSSL implementation for NIOx. (remm) +
    • +
    • Fix: + Improve upgrade context classloader handling by using Context.bind and + unbind. (remm) +
    • +
    • Add: + Improve OpenSSL keystore/truststore configuration by using the code + from the JSSE implementation. (remm, jfclere) +
    • +
    • Fix: + Fix a potential loop when a client drops the connection unexpectedly. + (markt) +
    • +
    • Add: + OpenSSL renegotiation support for client certificate authentication. + (remm) +
    • +
    • Fix: + Fix NIO connector renegotiation. (remm) +
    • +
    • Fix: + 58659: Fix a potential deadlock during HTTP/2 processing when + the connection window size is limited. (markt) +
    • +
    • Fix: + Correct an NPE when listing the enabled ciphers (e.g. via the Manager + web application) for a TLS enabled APR/native connector. (markt) +
    • +
    • Add: + New configuration option ajpFlush for the AJP connectors + to disable the sending of AJP flush packets. (rjung) +
    • +
    • Fix: + Handle the case in the NIO connector where the required TLS buffer sizes + increase after the connection has been initiated. (markt) +
    • +
    • Fix: + Handle the case in the NIO2 connector where the required TLS buffer + sizes increase after the connection has been initiated. (markt/remm) +
    • +
    • Fix: + Bad processing of handshake errors in NIO2. (remm) +
    • +
    • Fix: + Use JSSE session configuration options with OpenSSL. (remm) +
    • +
    • Fix: + 59015: Fix potential cause of endless APR Poller loop during + shutdown if the Poller experiences an error during the shutdown process. + (markt) +
    • +
    • Fix: + Align cipher aliases for kECDHE and ECDHE with + the current OpenSSL implementation. (markt) +
    • +
    • Fix: + 59081: Retain the user defined cipher order when defining + ciphers. (markt) +
    • +
    • Fix: + 59089: Correctly ignore HTTP headers that include non-token + characters in the header name. (markt) +
    • +
    +
    +

    Jasper

    +
      +
    • Fix: + 57136#c25: Change default value of + quoteAttributeEL setting in Jasper to be true + for better compatibility with other implementations and older versions + of Tomcat. Add command line option -no-quoteAttributeEL in + JspC. (kkolinko) +
    • +
    • Fix: + Fix handling of missing messages in + org.apache.el.util.MessageFactory. (violetagg) +
    • +
    • Update: + Update to the Eclipse JDT Compiler 4.5.1. (markt) +
    • +
    • Fix: + 57583: Improve the performance of + javax.servlet.jsp.el.ScopedAttributeELResolver when + resolving attributes that do not exist. This improvement only works when + Jasper is used with Tomcat's EL implementation. (markt) +
    • +
    +
    +

    Cluster

    +
      +
    • Fix: + Enable an explicit configuration of local member in the static cluster + membership. (kfujino) +
    • +
    • Fix: + Fix potential integer overflow in DeltaSession. + Reported by coverity scan. (fschumacher) +
    • +
    • Fix: + In order to avoid that the heartbeat thread and the background thread to + run Channel.heartbeat simultaneously, if + heartbeatBackgroundEnabled of SimpleTcpCluster + set to true, ensure that the heartbeat thread does not + start. (kfujino) +
    • +
    +
    +

    WebSocket

    +
      +
    • Add: + 55006: The WebSocket client now honors the + java.net.java.net.ProxySelector configuration (using the + HTTP type) when establishing WebSocket connections to servers. Based on + a patch by Niki Dokovski. (markt) +
    • +
    • Fix: + 57489: Ensure onClose() is called when a + WebSocket connection is closed even if the sending of the close message + fails. Includes test cases by Barry Coughlan. (markt) +
    • +
    • Fix: + 58624: Correct a potential deadlock if the WebSocket + connection is closed when a message write is in progress. (markt) +
    • +
    • Fix: + Fix a timing issue on session close that could result in an exception + being thrown for an incomplete message even through the message was + completed. (markt) +
    • +
    • Fix: + Correctly handle compression of partial messages when the final message + fragment has a zero length payload. (markt) +
    • +
    • Fix: + 59119: Correct read logic for WebSocket client when using + secure connections. (markt) +
    • +
    • Fix: + 59134: Correct client connect logic for secure connections + made through a proxy. (markt) +
    • +
    +
    +

    Web applications

    +
      +
    • Fix: + 48674: Implement an option within the Host Manager web + application to persist the current configuration. Based on a patch by + Coty Sutherland. (markt) +
    • +
    • Fix: + 58631: Correct the continuation character use in the Windows + Service How-To page of the documentation web application. (markt) +
    • +
    • Fix: + Correct the SSL documentation for deprecated attributes to point to the + correct, new location for attributes related to individual certificates. + (markt) +
    • +
    • Fix: + Correct some typos in the JNDI resources How-To. (markt) +
    • +
    • Fix: + Don't create session unnecessarily in the Manager application. (markt) +
    • +
    • Fix: + Don't create session unnecessarily in the Host Manager application. + (markt) +
    • +
    • Fix: + 58723: Clarify documentation and error messages for the text + interface of the manager to make clear that version must be used with + path when referencing contexts deployed using parallel deployment. + (markt) +
    • +
    • Add: + Document test.threads option in BUILDING.txt. (kkolinko) +
    • +
    • Fix: + Correct an error in the documentation of the expected behaviour for + automatic deployment. If a WAR is updated and an expanded directory is + present, the directory will always be deleted and recreated by expanding + the WAR if unpackWARs is true. (markt) +
    • +
    • Fix: + 58935: Remove incorrect references in the documentation to + using jar:file: URLs with the Manager application. (markt) +
    • +
    • Fix: + Correct the description of the + ServletRequest.getServerPort() in Proxy How-To. + Issue reported via comments.apache.org. (violetagg) +
    • +
    • Add: + The Manager and Host Manager applications are now only accessible via + localhost by default. (markt) +
    • +
    +
    +

    Tribes

    +
      +
    • Fix: + Clarify the handling of Copy message and Copy nodes. (kfujino) +
    • +
    • Fix: + Ensure that the static member is registered to the add suspect list even + if the static member that is registered to the remove suspect list has + disappeared. (kfujino) +
    • +
    • Fix: + When using a static cluster, add the members that have been cached in + the membership service to the map members list in order to ensure that + the map member is a static member. (kfujino) +
    • +
    • Fix: + Add support for the startup notification of local members in the static + cluster. (kfujino) +
    • +
    • Fix: + Ignore the unnecessary member remove operation from different domain. + (kfujino) +
    • +
    • Fix: + Add support for the shutdown notification of local members in the static + cluster. (kfujino) +
    • +
    • Fix: + If promoting a proxy node to a primary node when getting a session, + notify the change of the new primary node to the original backup node. + (kfujino) +
    • +
    +
    +

    jdbc-pool

    +
      +
    • Fix: + Correct evaluation of system property + org.apache.tomcat.jdbc.pool.onlyAttemptCurrentClassLoader. + It was basically ignored before. Reported by coverity scan. (fschumacher) +
    • +
    • Fix: + Fix potential integer overflow in ConnectionPool and + PooledConnection. Reported by coverity scan. (fschumacher) +
    • +
    +
    +

    Other

    +
      +
    • Add: + Allow to configure multiple JUnit test class patterns with the build + property test.name and document the property in + BUILDING.txt. (rjung) +
    • +
    • Add: + Support the use of the threads attribute on Ant's + junit task. Note that using this with a value of greater than one will + disable Cobertura code coverage. (markt) +
    • +
    • Update: + Update optional Checkstyle library to 6.14.1. (kkolinko) +
    • +
    • Update: + Update the packaged version of the Tomcat Native Library to 1.2.4 to + pick up the Windows binaries that are based on OpenSSL 1.0.2e and APR + 1.5.1. (markt) +
    • +
    • Update: + Update the NSIS Installer used to build the Windows Installers to + version 2.50. (markt/kkolinko) +
    • +
    • Update: + Update the internal fork of Commons BCEL to r1725718 to align with the + refactoring for BCEL 6, the next major BCEL release. (markt) +
    • +
    • Update: + Update the internal fork of Commons DBCP 2 to r1725730 (2.1.1 plus + additional fixes). (markt) +
    • +
    • Update: + Update the internal fork of Commons Pool 2 to r1725738 (2.4.2 plus + additional fixes). (markt) +
    • +
    • Update: + Update the internal fork of Commons Codec to r1725746 (1.9 plus + additional fixes). (markt) +
    • +
    • Fix: + 58283: Change the default download location for libraries + during the build process from /usr/share/java to + ${user.home}/temp. Patch provided by Ahmed Hosni. (markt) +
    • +
    • Fix: + 59031: When using the Windows uninstaller, do not remove the + contents of any directories that have been symlinked into the Tomcat + directory structure. (markt) +
    • +
    • Update: + Update the packaged version of the Tomcat Native Library to 1.2.5 to + pick up the Windows binaries that are based on OpenSSL 1.0.2g and APR + 1.5.1. (markt) +
    • +
    • Update: + Modify the default tomcat-users.xml file to make it harder + for users to configure the entries intended for use with the examples + web application for the Manager application. (markt) +
    • +
    +
    +
    \ No newline at end of file diff --git a/tomcat/docs/class-loader-howto.html b/tomcat/docs/class-loader-howto.html new file mode 100644 index 0000000..b4a75e5 --- /dev/null +++ b/tomcat/docs/class-loader-howto.html @@ -0,0 +1,291 @@ + +Apache Tomcat 8 (8.5.43) - Class Loader How-To

    Class Loader How-To

    Table of Contents

    Overview

    + +

    Like many server applications, Tomcat installs a variety of class loaders +(that is, classes that implement java.lang.ClassLoader) to allow +different portions of the container, and the web applications running on the +container, to have access to different repositories of available classes and +resources. This mechanism is used to provide the functionality defined in the +Servlet Specification, version 2.4 — in particular, Sections 9.4 +and 9.6.

    + +

    In a Java environment, class loaders are +arranged in a parent-child tree. Normally, when a class loader is asked to +load a particular class or resource, it delegates the request to a parent +class loader first, and then looks in its own repositories only if the parent +class loader(s) cannot find the requested class or resource. Note, that the +model for web application class loaders differs slightly from this, +as discussed below, but the main principles are the same.

    + +

    When Tomcat is started, it creates a set of class loaders that are +organized into the following parent-child relationships, where the parent +class loader is above the child class loader:

    + +
          Bootstrap
    +          |
    +       System
    +          |
    +       Common
    +       /     \
    +  Webapp1   Webapp2 ...
    + +

    The characteristics of each of these class loaders, including the source +of classes and resources that they make visible, are discussed in detail in +the following section.

    + +

    Class Loader Definitions

    + +

    As indicated in the diagram above, Tomcat creates the following class +loaders as it is initialized:

    +
      +
    • Bootstrap — This class loader contains the basic + runtime classes provided by the Java Virtual Machine, plus any classes from + JAR files present in the System Extensions directory + ($JAVA_HOME/jre/lib/ext). Note: some JVMs may + implement this as more than one class loader, or it may not be visible + (as a class loader) at all.

    • +
    • System — This class loader is normally initialized + from the contents of the CLASSPATH environment variable. All + such classes are visible to both Tomcat internal classes, and to web + applications. However, the standard Tomcat startup scripts + ($CATALINA_HOME/bin/catalina.sh or + %CATALINA_HOME%\bin\catalina.bat) totally ignore the contents + of the CLASSPATH environment variable itself, and instead + build the System class loader from the following repositories: +

      +
        +
      • $CATALINA_HOME/bin/bootstrap.jar — Contains the + main() method that is used to initialize the Tomcat server, and the + class loader implementation classes it depends on.

      • +
      • $CATALINA_BASE/bin/tomcat-juli.jar or + $CATALINA_HOME/bin/tomcat-juli.jar — Logging + implementation classes. These include enhancement classes to + java.util.logging API, known as Tomcat JULI, + and a package-renamed copy of Apache Commons Logging library + used internally by Tomcat. + See logging documentation for more + details.

        +

        If tomcat-juli.jar is present in + $CATALINA_BASE/bin, it is used instead of the one in + $CATALINA_HOME/bin. It is useful in certain logging + configurations

      • +
      • $CATALINA_HOME/bin/commons-daemon.jar — The classes + from Apache Commons + Daemon project. + This JAR file is not present in the CLASSPATH built by + catalina.bat|.sh scripts, but is referenced + from the manifest file of bootstrap.jar.

      • +
      +
    • +
    • Common — This class loader contains additional + classes that are made visible to both Tomcat internal classes and to all + web applications.

      +

      Normally, application classes should NOT + be placed here. The locations searched by this class loader are defined by + the common.loader property in + $CATALINA_BASE/conf/catalina.properties. The default setting will search the + following locations in the order they are listed:

      +
        +
      • unpacked classes and resources in $CATALINA_BASE/lib
      • +
      • JAR files in $CATALINA_BASE/lib
      • +
      • unpacked classes and resources in $CATALINA_HOME/lib
      • +
      • JAR files in $CATALINA_HOME/lib
      • +
      +

      By default, this includes the following:

      +
        +
      • annotations-api.jar — JavaEE annotations classes.
      • +
      • catalina.jar — Implementation of the Catalina servlet + container portion of Tomcat.
      • +
      • catalina-ant.jar — Tomcat Catalina Ant tasks.
      • +
      • catalina-ha.jar — High availability package.
      • +
      • catalina-storeconfig.jar — Generation of XML + configuration files from current state
      • +
      • catalina-tribes.jar — Group communication package.
      • +
      • ecj-*.jar — Eclipse JDT Java compiler.
      • +
      • el-api.jar — EL 3.0 API.
      • +
      • jasper.jar — Tomcat Jasper JSP Compiler and Runtime.
      • +
      • jasper-el.jar — Tomcat Jasper EL implementation.
      • +
      • jsp-api.jar — JSP 2.3 API.
      • +
      • servlet-api.jar — Servlet 3.1 API.
      • +
      • tomcat-api.jar — Several interfaces defined by Tomcat.
      • +
      • tomcat-coyote.jar — Tomcat connectors and utility classes.
      • +
      • tomcat-dbcp.jar — Database connection pool + implementation based on package-renamed copy of Apache Commons Pool 2 + and Apache Commons DBCP 2.
      • +
      • tomcat-i18n-**.jar — Optional JARs containing resource bundles + for other languages. As default bundles are also included in each + individual JAR, they can be safely removed if no internationalization + of messages is needed.
      • +
      • tomcat-jdbc.jar — An alternative database connection pool + implementation, known as Tomcat JDBC pool. See + documentation for more details.
      • +
      • tomcat-util.jar — Common classes used by various components of + Apache Tomcat.
      • +
      • tomcat-websocket.jar — WebSocket 1.1 implementation
      • +
      • websocket-api.jar — WebSocket 1.1 API
      • +
    • +
    • WebappX — A class loader is created for each web + application that is deployed in a single Tomcat instance. All unpacked + classes and resources in the /WEB-INF/classes directory of + your web application, plus classes and resources in JAR files + under the /WEB-INF/lib directory of your web application, + are made visible to this web application, but not to other ones.

    • +
    + +

    As mentioned above, the web application class loader diverges from the +default Java delegation model (in accordance with the recommendations in the +Servlet Specification, version 2.4, section 9.7.2 Web Application Classloader). +When a request to load a +class from the web application's WebappX class loader is processed, +this class loader will look in the local repositories first, +instead of delegating before looking. There are exceptions. Classes which are +part of the JRE base classes cannot be overridden. There are some exceptions +such as the XML parser components which can be overridden using the appropriate +JVM feature which is the endorsed standards override feature for Java <= 8 +and the upgradeable modules feature for Java 9+. +Lastly, the web application class loader will always delegate first for JavaEE +API classes for the specifications implemented by Tomcat +(Servlet, JSP, EL, WebSocket). All other class loaders in Tomcat follow the +usual delegation pattern.

    + +

    Therefore, from the perspective of a web application, class or resource +loading looks in the following repositories, in this order:

    +
      +
    • Bootstrap classes of your JVM
    • +
    • /WEB-INF/classes of your web application
    • +
    • /WEB-INF/lib/*.jar of your web application
    • +
    • System class loader classes (described above)
    • +
    • Common class loader classes (described above)
    • +
    + +

    If the web application class loader is +configured with +<Loader delegate="true"/> +then the order becomes:

    +
      +
    • Bootstrap classes of your JVM
    • +
    • System class loader classes (described above)
    • +
    • Common class loader classes (described above)
    • +
    • /WEB-INF/classes of your web application
    • +
    • /WEB-INF/lib/*.jar of your web application
    • +
    + +

    XML Parsers and Java

    + +

    Starting with Java 1.4 a copy of JAXP APIs and an XML parser are packed +inside the JRE. This has impacts on applications that wish to use their own +XML parser.

    + +

    In old versions of Tomcat, you could simply replace the XML parser +in the Tomcat libraries directory to change the parser +used by all web applications. However, this technique will not be effective +when you are running modern versions of Java, because the usual class loader +delegation process will always choose the implementation inside the JDK in +preference to this one.

    + +

    Java <= 8 supports a mechanism called the "Endorsed Standards Override +Mechanism" to allow replacement of APIs created outside of the JCP +(i.e. DOM and SAX from W3C). It can also be used to update the XML parser +implementation. For more information, see: + +http://docs.oracle.com/javase/1.5.0/docs/guide/standards/index.html. For +Java 9+, use the upgradeable modules feature.

    + +

    Tomcat utilizes the endorsed mechanism by including the system property setting +-Djava.endorsed.dirs=$JAVA_ENDORSED_DIRS in the +command line that starts the container. The default value of this option is +$CATALINA_HOME/endorsed. This endorsed directory is not +created by default. Note that the endorsed feature is no longer supported +with Java 9 and the above system property will only be set if either the +directory $CATALINA_HOME/endorsed exists, or the variable +JAVA_ENDORSED_DIRS has been set. +

    + +

    Note that overriding any JRE component carries risk. If the overriding +component does not provide a 100% compatible API (e.g. the API provided by +Xerces is not 100% compatible with the XML API provided by the JRE) then there +is a risk that Tomcat and/or the deployed application will experience errors.

    + +

    Running under a security manager

    + +

    When running under a security manager the locations from which classes +are permitted to be loaded will also depend on the contents of your policy +file. See Security Manager How-To +for further information.

    + +

    Advanced configuration

    + +

    A more complex class loader hierarchy may also be configured. See the diagram +below. By default, the Server and Shared +class loaders are not defined and the simplifed hierarchy shown above is used. +This more complex hierarchy may be use by defining values for the +server.loader and/or shared.loader properties in +conf/catalina.properties.

    + +
    
    +  Bootstrap
    +      |
    +    System
    +      |
    +    Common
    +     /  \
    +Server  Shared
    +         /  \
    +   Webapp1  Webapp2 ...
    + +

    The Server class loader is only visible to Tomcat internals +and is completely invisible to web applications.

    + +

    The Shared class loader is visible to all web applications +and may be used to shared code across all web applications. However, any updates +to this shared code will require a Tomcat restart.

    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/cluster-howto.html b/tomcat/docs/cluster-howto.html new file mode 100644 index 0000000..d38d69e --- /dev/null +++ b/tomcat/docs/cluster-howto.html @@ -0,0 +1,676 @@ + +Apache Tomcat 8 (8.5.43) - Clustering/Session Replication How-To

    Clustering/Session Replication How-To

    Important Note

    +

    You can also check the configuration reference documentation. +

    +

    Table of Contents

    For the impatient

    +

    + Simply add +

    +
    <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
    +

    + to your <Engine> or your <Host> element to enable clustering. +

    +

    + Using the above configuration will enable all-to-all session replication + using the DeltaManager to replicate session deltas. By all-to-all, we mean that every + session gets replicated to all the other nodes in the cluster. + This works great for smaller clusters, but we don't recommend it for larger clusters — more than 4 nodes or so. + Also, when using the DeltaManager, Tomcat will replicate sessions to all nodes, + even nodes that don't have the application deployed.
    + To get around these problem, you'll want to use the BackupManager. The BackupManager + only replicates the session data to one backup node, and only to nodes that have the application deployed. + Once you have a simple cluster running with the DeltaManager, you will probably want to + migrate to the BackupManager as you increase the number of nodes in your cluster. +

    +

    + Here are some of the important default values: +

    +
      +
    1. Multicast address is 228.0.0.4
    2. +
    3. Multicast port is 45564 (the port and the address together determine cluster membership.
    4. +
    5. The IP broadcasted is java.net.InetAddress.getLocalHost().getHostAddress() (make sure you don't broadcast 127.0.0.1, this is a common error)
    6. +
    7. The TCP port listening for replication messages is the first available server socket in range 4000-4100
    8. +
    9. Listener is configured ClusterSessionListener
    10. +
    11. Two interceptors are configured TcpFailureDetector and MessageDispatchInterceptor
    12. +
    +

    + The following is the default cluster configuration: +

    +
            <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"
    +                 channelSendOptions="8">
    +
    +          <Manager className="org.apache.catalina.ha.session.DeltaManager"
    +                   expireSessionsOnShutdown="false"
    +                   notifyListenersOnReplication="true"/>
    +
    +          <Channel className="org.apache.catalina.tribes.group.GroupChannel">
    +            <Membership className="org.apache.catalina.tribes.membership.McastService"
    +                        address="228.0.0.4"
    +                        port="45564"
    +                        frequency="500"
    +                        dropTime="3000"/>
    +            <Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"
    +                      address="auto"
    +                      port="4000"
    +                      autoBind="100"
    +                      selectorTimeout="5000"
    +                      maxThreads="6"/>
    +
    +            <Sender className="org.apache.catalina.tribes.transport.ReplicationTransmitter">
    +              <Transport className="org.apache.catalina.tribes.transport.nio.PooledParallelSender"/>
    +            </Sender>
    +            <Interceptor className="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector"/>
    +            <Interceptor className="org.apache.catalina.tribes.group.interceptors.MessageDispatchInterceptor"/>
    +          </Channel>
    +
    +          <Valve className="org.apache.catalina.ha.tcp.ReplicationValve"
    +                 filter=""/>
    +          <Valve className="org.apache.catalina.ha.session.JvmRouteBinderValve"/>
    +
    +          <Deployer className="org.apache.catalina.ha.deploy.FarmWarDeployer"
    +                    tempDir="/tmp/war-temp/"
    +                    deployDir="/tmp/war-deploy/"
    +                    watchDir="/tmp/war-listen/"
    +                    watchEnabled="false"/>
    +
    +          <ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener"/>
    +        </Cluster>
    +

    We will cover this section in more detail later in this document.

    +

    Security

    + +

    The cluster implementation is written on the basis that a secure, trusted +network is used for all of the cluster related network traffic. It is not safe +to run a cluster on a insecure, untrusted network.

    + +

    There are many options for providing a secure, trusted network for use by a +Tomcat cluster. These include:

    +
      +
    • private LAN
    • +
    • a Virtual Private Network (VPN)
    • +
    • IPSEC
    • +
    • Encrypt cluster traffic using the EncryptInterceptor
    • +
    + +

    Cluster Basics

    + +

    To run session replication in your Tomcat 8 container, the following steps +should be completed:

    +
      +
    • All your session attributes must implement java.io.Serializable
    • +
    • Uncomment the Cluster element in server.xml
    • +
    • If you have defined custom cluster valves, make sure you have the ReplicationValve defined as well under the Cluster element in server.xml
    • +
    • If your Tomcat instances are running on the same machine, make sure the Receiver.port + attribute is unique for each instance, in most cases Tomcat is smart enough to resolve this on it's own by autodetecting available ports in the range 4000-4100
    • +
    • Make sure your web.xml has the + <distributable/> element
    • +
    • If you are using mod_jk, make sure that jvmRoute attribute is set at your Engine <Engine name="Catalina" jvmRoute="node01" > + and that the jvmRoute attribute value matches your worker name in workers.properties
    • +
    • Make sure that all nodes have the same time and sync with NTP service!
    • +
    • Make sure that your loadbalancer is configured for sticky session mode.
    • +
    +

    Load balancing can be achieved through many techniques, as seen in the +Load Balancing chapter.

    +

    Note: Remember that your session state is tracked by a cookie, so your URL must look the same from the out + side otherwise, a new session will be created.

    +

    The Cluster module uses the Tomcat JULI logging framework, so you can configure logging + through the regular logging.properties file. To track messages, you can enable logging on the key: org.apache.catalina.tribes.MESSAGES

    +

    Overview

    + +

    To enable session replication in Tomcat, three different paths can be followed to achieve the exact same thing:

    +
      +
    1. Using session persistence, and saving the session to a shared file system (PersistenceManager + FileStore)
    2. +
    3. Using session persistence, and saving the session to a shared database (PersistenceManager + JDBCStore)
    4. +
    5. Using in-memory-replication, using the SimpleTcpCluster that ships with Tomcat (lib/catalina-tribes.jar + lib/catalina-ha.jar)
    6. +
    + +

    Tomcat can perform an all-to-all replication of session state using the DeltaManager or + perform backup replication to only one node using the BackupManager. + The all-to-all replication is an algorithm that is only efficient when the clusters are small. For larger clusters, you + should use the BackupManager to use a primary-secondary session replication strategy where the session will only be + stored at one backup node.
    + + Currently you can use the domain worker attribute (mod_jk > 1.2.8) to build cluster partitions + with the potential of having a more scalable cluster solution with the DeltaManager + (you'll need to configure the domain interceptor for this). + In order to keep the network traffic down in an all-to-all environment, you can split your cluster + into smaller groups. This can be easily achieved by using different multicast addresses for the different groups. + A very simple setup would look like this: +

    + +
            DNS Round Robin
    +               |
    +         Load Balancer
    +          /           \
    +      Cluster1      Cluster2
    +      /     \        /     \
    +  Tomcat1 Tomcat2  Tomcat3 Tomcat4
    + +

    What is important to mention here, is that session replication is only the beginning of clustering. + Another popular concept used to implement clusters is farming, i.e., you deploy your apps only to one + server, and the cluster will distribute the deployments across the entire cluster. + This is all capabilities that can go into with the FarmWarDeployer (s. cluster example at server.xml)

    +

    In the next section will go deeper into how session replication works and how to configure it.

    + +

    Cluster Information

    +

    Membership is established using multicast heartbeats. + Hence, if you wish to subdivide your clusters, you can do this by + changing the multicast IP address or port in the <Membership> element. +

    +

    + The heartbeat contains the IP address of the Tomcat node and the TCP port that + Tomcat listens to for replication traffic. All data communication happens over TCP. +

    +

    + The ReplicationValve is used to find out when the request has been completed and initiate the + replication, if any. Data is only replicated if the session has changed (by calling setAttribute or removeAttribute + on the session). +

    +

    + One of the most important performance considerations is the synchronous versus asynchronous replication. + In a synchronous replication mode the request doesn't return until the replicated session has been + sent over the wire and reinstantiated on all the other cluster nodes. + Synchronous vs. asynchronous is configured using the channelSendOptions + flag and is an integer value. The default value for the SimpleTcpCluster/DeltaManager combo is + 8, which is asynchronous. You can read more on the send flag(overview) or the + send flag(javadoc). + During async replication, the request is returned before the data has been replicated. async replication yields shorter + request times, and synchronous replication guarantees the session to be replicated before the request returns. +

    +

    Bind session after crash to failover node

    +

    + If you are using mod_jk and not using sticky sessions or for some reasons sticky session don't + work, or you are simply failing over, the session id will need to be modified as it previously contained + the worker id of the previous tomcat (as defined by jvmRoute in the Engine element). + To solve this, we will use the JvmRouteBinderValve. +

    +

    + The JvmRouteBinderValve rewrites the session id to ensure that the next request will remain sticky + (and not fall back to go to random nodes since the worker is no longer available) after a fail over. + The valve rewrites the JSESSIONID value in the cookie with the same name. + Not having this valve in place, will make it harder to ensure stickiness in case of a failure for the mod_jk module. +

    +

    + Remember, if you are adding your own valves in server.xml then the defaults are no longer valid, + make sure that you add in all the appropriate valves as defined by the default. +

    +

    + Hint:
    + With attribute sessionIdAttribute you can change the request attribute name that included the old session id. + Default attribute name is org.apache.catalina.ha.session.JvmRouteOrignalSessionID. +

    +

    + Trick:
    + You can enable this mod_jk turnover mode via JMX before you drop a node to all backup nodes! + Set enable true on all JvmRouteBinderValve backups, disable worker at mod_jk + and then drop node and restart it! Then enable mod_jk Worker and disable JvmRouteBinderValves again. + This use case means that only requested session are migrated. +

    + + +

    Configuration Example

    +
            <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"
    +                 channelSendOptions="6">
    +
    +          <Manager className="org.apache.catalina.ha.session.BackupManager"
    +                   expireSessionsOnShutdown="false"
    +                   notifyListenersOnReplication="true"
    +                   mapSendOptions="6"/>
    +          <!--
    +          <Manager className="org.apache.catalina.ha.session.DeltaManager"
    +                   expireSessionsOnShutdown="false"
    +                   notifyListenersOnReplication="true"/>
    +          -->
    +          <Channel className="org.apache.catalina.tribes.group.GroupChannel">
    +            <Membership className="org.apache.catalina.tribes.membership.McastService"
    +                        address="228.0.0.4"
    +                        port="45564"
    +                        frequency="500"
    +                        dropTime="3000"/>
    +            <Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"
    +                      address="auto"
    +                      port="5000"
    +                      selectorTimeout="100"
    +                      maxThreads="6"/>
    +
    +            <Sender className="org.apache.catalina.tribes.transport.ReplicationTransmitter">
    +              <Transport className="org.apache.catalina.tribes.transport.nio.PooledParallelSender"/>
    +            </Sender>
    +            <Interceptor className="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector"/>
    +            <Interceptor className="org.apache.catalina.tribes.group.interceptors.MessageDispatchInterceptor"/>
    +            <Interceptor className="org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor"/>
    +          </Channel>
    +
    +          <Valve className="org.apache.catalina.ha.tcp.ReplicationValve"
    +                 filter=".*\.gif|.*\.js|.*\.jpeg|.*\.jpg|.*\.png|.*\.htm|.*\.html|.*\.css|.*\.txt"/>
    +
    +          <Deployer className="org.apache.catalina.ha.deploy.FarmWarDeployer"
    +                    tempDir="/tmp/war-temp/"
    +                    deployDir="/tmp/war-deploy/"
    +                    watchDir="/tmp/war-listen/"
    +                    watchEnabled="false"/>
    +
    +          <ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener"/>
    +        </Cluster>
    +

    + Break it down!! +

    +
            <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"
    +                 channelSendOptions="6">
    +

    + The main element, inside this element all cluster details can be configured. + The channelSendOptions is the flag that is attached to each message sent by the + SimpleTcpCluster class or any objects that are invoking the SimpleTcpCluster.send method. + The description of the send flags is available at + our javadoc site + The DeltaManager sends information using the SimpleTcpCluster.send method, while the backup manager + sends it itself directly through the channel. +
    For more info, Please visit the reference documentation +

    +
              <Manager className="org.apache.catalina.ha.session.BackupManager"
    +                   expireSessionsOnShutdown="false"
    +                   notifyListenersOnReplication="true"
    +                   mapSendOptions="6"/>
    +          <!--
    +          <Manager className="org.apache.catalina.ha.session.DeltaManager"
    +                   expireSessionsOnShutdown="false"
    +                   notifyListenersOnReplication="true"/>
    +          -->
    +

    + This is a template for the manager configuration that will be used if no manager is defined in the <Context> + element. In Tomcat 5.x each webapp marked distributable had to use the same manager, this is no longer the case + since Tomcat you can define a manager class for each webapp, so that you can mix managers in your cluster. + Obviously the managers on one node's application has to correspond with the same manager on the same application on the other node. + If no manager has been specified for the webapp, and the webapp is marked <distributable/> Tomcat will take this manager configuration + and create a manager instance cloning this configuration. +
    For more info, Please visit the reference documentation +

    +
              <Channel className="org.apache.catalina.tribes.group.GroupChannel">
    +

    + The channel element is Tribes, the group communication framework + used inside Tomcat. This element encapsulates everything that has to do with communication and membership logic. +
    For more info, Please visit the reference documentation +

    +
                <Membership className="org.apache.catalina.tribes.membership.McastService"
    +                        address="228.0.0.4"
    +                        port="45564"
    +                        frequency="500"
    +                        dropTime="3000"/>
    +

    + Membership is done using multicasting. Please note that Tribes also supports static memberships using the + StaticMembershipInterceptor if you want to extend your membership to points beyond multicasting. + The address attribute is the multicast address used and the port is the multicast port. These two together + create the cluster separation. If you want a QA cluster and a production cluster, the easiest config is to + have the QA cluster be on a separate multicast address/port combination than the production cluster.
    + The membership component broadcasts TCP address/port of itself to the other nodes so that communication between + nodes can be done over TCP. Please note that the address being broadcasted is the one of the + Receiver.address attribute. +
    For more info, Please visit the reference documentation +

    +
                <Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"
    +                      address="auto"
    +                      port="5000"
    +                      selectorTimeout="100"
    +                      maxThreads="6"/>
    +

    + In tribes the logic of sending and receiving data has been broken into two functional components. The Receiver, as the name suggests + is responsible for receiving messages. Since the Tribes stack is thread less, (a popular improvement now adopted by other frameworks as well), + there is a thread pool in this component that has a maxThreads and minThreads setting.
    + The address attribute is the host address that will be broadcasted by the membership component to the other nodes. +
    For more info, Please visit the reference documentation +

    +
                <Sender className="org.apache.catalina.tribes.transport.ReplicationTransmitter">
    +              <Transport className="org.apache.catalina.tribes.transport.nio.PooledParallelSender"/>
    +            </Sender>
    +

    + The sender component, as the name indicates is responsible for sending messages to other nodes. + The sender has a shell component, the ReplicationTransmitter but the real stuff done is done in the + sub component, Transport. + Tribes support having a pool of senders, so that messages can be sent in parallel and if using the NIO sender, + you can send messages concurrently as well.
    + Concurrently means one message to multiple senders at the same time and Parallel means multiple messages to multiple senders + at the same time. +
    For more info, Please visit the reference documentation +

    +
                <Interceptor className="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector"/>
    +            <Interceptor className="org.apache.catalina.tribes.group.interceptors.MessageDispatchInterceptor"/>
    +            <Interceptor className="org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor"/>
    +          </Channel>
    +

    + Tribes uses a stack to send messages through. Each element in the stack is called an interceptor, and works much like the valves do + in the Tomcat servlet container. + Using interceptors, logic can be broken into more manageable pieces of code. The interceptors configured above are:
    + TcpFailureDetector - verifies crashed members through TCP, if multicast packets get dropped, this interceptor protects against false positives, + ie the node marked as crashed even though it still is alive and running.
    + MessageDispatchInterceptor - dispatches messages to a thread (thread pool) to send message asynchronously.
    + ThroughputInterceptor - prints out simple stats on message traffic.
    + Please note that the order of interceptors is important. The way they are defined in server.xml is the way they are represented in the + channel stack. Think of it as a linked list, with the head being the first most interceptor and the tail the last. +
    For more info, Please visit the reference documentation +

    +
              <Valve className="org.apache.catalina.ha.tcp.ReplicationValve"
    +                 filter=".*\.gif|.*\.js|.*\.jpeg|.*\.jpg|.*\.png|.*\.htm|.*\.html|.*\.css|.*\.txt"/>
    +

    + The cluster uses valves to track requests to web applications, we've mentioned the ReplicationValve and the JvmRouteBinderValve above. + The <Cluster> element itself is not part of the pipeline in Tomcat, instead the cluster adds the valve to its parent container. + If the <Cluster> elements is configured in the <Engine> element, the valves get added to the engine and so on. +
    For more info, Please visit the reference documentation +

    +
              <Deployer className="org.apache.catalina.ha.deploy.FarmWarDeployer"
    +                    tempDir="/tmp/war-temp/"
    +                    deployDir="/tmp/war-deploy/"
    +                    watchDir="/tmp/war-listen/"
    +                    watchEnabled="false"/>
    +

    + The default tomcat cluster supports farmed deployment, ie, the cluster can deploy and undeploy applications on the other nodes. + The state of this component is currently in flux but will be addressed soon. There was a change in the deployment algorithm + between Tomcat 5.0 and 5.5 and at that point, the logic of this component changed to where the deploy dir has to match the + webapps directory. +
    For more info, Please visit the reference documentation +

    +
              <ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener"/>
    +        </Cluster>
    +

    + Since the SimpleTcpCluster itself is a sender and receiver of the Channel object, components can register themselves as listeners to + the SimpleTcpCluster. The listener above ClusterSessionListener listens for DeltaManager replication messages + and applies the deltas to the manager that in turn applies it to the session. +
    For more info, Please visit the reference documentation +

    + +

    Cluster Architecture

    + +

    Component Levels:

    +
             Server
    +           |
    +         Service
    +           |
    +         Engine
    +           |  \
    +           |  --- Cluster --*
    +           |
    +         Host
    +           |
    +         ------
    +        /      \
    +     Cluster    Context(1-N)
    +        |             \
    +        |             -- Manager
    +        |                   \
    +        |                   -- DeltaManager
    +        |                   -- BackupManager
    +        |
    +     ---------------------------
    +        |                       \
    +      Channel                    \
    +    ----------------------------- \
    +        |                          \
    +     Interceptor_1 ..               \
    +        |                            \
    +     Interceptor_N                    \
    +    -----------------------------      \
    +     |          |         |             \
    +   Receiver    Sender   Membership       \
    +                                         -- Valve
    +                                         |      \
    +                                         |       -- ReplicationValve
    +                                         |       -- JvmRouteBinderValve
    +                                         |
    +                                         -- LifecycleListener
    +                                         |
    +                                         -- ClusterListener
    +                                         |      \
    +                                         |       -- ClusterSessionListener
    +                                         |
    +                                         -- Deployer
    +                                                \
    +                                                 -- FarmWarDeployer
    +
    +
    + + +

    How it Works

    +

    To make it easy to understand how clustering works, We are gonna take you through a series of scenarios. + In the scenario we only plan to use two tomcat instances TomcatA and TomcatB. + We will cover the following sequence of events:

    + +
      +
    1. TomcatA starts up
    2. +
    3. TomcatB starts up (Wait that TomcatA start is complete)
    4. +
    5. TomcatA receives a request, a session S1 is created.
    6. +
    7. TomcatA crashes
    8. +
    9. TomcatB receives a request for session S1
    10. +
    11. TomcatA starts up
    12. +
    13. TomcatA receives a request, invalidate is called on the session (S1)
    14. +
    15. TomcatB receives a request, for a new session (S2)
    16. +
    17. TomcatA The session S2 expires due to inactivity.
    18. +
    + +

    Ok, now that we have a good sequence, we will take you through exactly what happens in the session replication code

    + +
      +
    1. TomcatA starts up +

      + Tomcat starts up using the standard start up sequence. When the Host object is created, a cluster object is associated with it. + When the contexts are parsed, if the distributable element is in place in web.xml + Tomcat asks the Cluster class (in this case SimpleTcpCluster) to create a manager + for the replicated context. So with clustering enabled, distributable set in web.xml + Tomcat will create a DeltaManager for that context instead of a StandardManager. + The cluster class will start up a membership service (multicast) and a replication service (tcp unicast). + More on the architecture further down in this document. +

      +
    2. +
    3. TomcatB starts up +

      + When TomcatB starts up, it follows the same sequence as TomcatA did with one exception. + The cluster is started and will establish a membership (TomcatA,TomcatB). + TomcatB will now request the session state from a server that already exists in the cluster, + in this case TomcatA. TomcatA responds to the request, and before TomcatB starts listening + for HTTP requests, the state has been transferred from TomcatA to TomcatB. + In case TomcatA doesn't respond, TomcatB will time out after 60 seconds, and issue a log + entry. The session state gets transferred for each web application that has distributable in + its web.xml. Note: To use session replication efficiently, all your tomcat instances should be + configured the same. +

      +
    4. +
    5. TomcatA receives a request, a session S1 is created. +

      + The request coming in to TomcatA is treated exactly the same way as without session replication. + The action happens when the request is completed, the ReplicationValve will intercept + the request before the response is returned to the user. + At this point it finds that the session has been modified, and it uses TCP to replicate the + session to TomcatB. Once the serialized data has been handed off to the operating systems TCP logic, + the request returns to the user, back through the valve pipeline. + For each request the entire session is replicated, this allows code that modifies attributes + in the session without calling setAttribute or removeAttribute to be replicated. + a useDirtyFlag configuration parameter can be used to optimize the number of times + a session is replicated. +

      + +
    6. +
    7. TomcatA crashes +

      + When TomcatA crashes, TomcatB receives a notification that TomcatA has dropped out + of the cluster. TomcatB removes TomcatA from its membership list, and TomcatA will no longer + be notified of any changes that occurs in TomcatB. + The load balancer will redirect the requests from TomcatA to TomcatB and all the sessions + are current. +

      +
    8. +
    9. TomcatB receives a request for session S1 +

      Nothing exciting, TomcatB will process the request as any other request. +

      +
    10. +
    11. TomcatA starts up +

      Upon start up, before TomcatA starts taking new request and making itself + available to it will follow the start up sequence described above 1) 2). + It will join the cluster, contact TomcatB for the current state of all the sessions. + And once it receives the session state, it finishes loading and opens its HTTP/mod_jk ports. + So no requests will make it to TomcatA until it has received the session state from TomcatB. +

      +
    12. +
    13. TomcatA receives a request, invalidate is called on the session (S1) +

      The invalidate call is intercepted, and the session is queued with invalidated sessions. + When the request is complete, instead of sending out the session that has changed, it sends out + an "expire" message to TomcatB and TomcatB will invalidate the session as well. +

      + +
    14. +
    15. TomcatB receives a request, for a new session (S2) +

      Same scenario as in step 3) +

      + + +
    16. +
    17. TomcatA The session S2 expires due to inactivity. +

      The invalidate call is intercepted the same was as when a session is invalidated by the user, + and the session is queued with invalidated sessions. + At this point, the invalidated session will not be replicated across until + another request comes through the system and checks the invalid queue. +

      +
    18. +
    + +

    Phuuuhh! :)

    + +

    Membership + Clustering membership is established using very simple multicast pings. + Each Tomcat instance will periodically send out a multicast ping, + in the ping message the instance will broad cast its IP and TCP listen port + for replication. + If an instance has not received such a ping within a given timeframe, the + member is considered dead. Very simple, and very effective! + Of course, you need to enable multicasting on your system. +

    + +

    TCP Replication + Once a multicast ping has been received, the member is added to the cluster + Upon the next replication request, the sending instance will use the host and + port info and establish a TCP socket. Using this socket it sends over the serialized data. + The reason I choose TCP sockets is because it has built in flow control and guaranteed delivery. + So I know, when I send some data, it will make it there :) +

    + +

    Distributed locking and pages using frames + Tomcat does not keep session instances in sync across the cluster. + The implementation of such logic would be to much overhead and cause all + kinds of problems. If your client accesses the same session + simultaneously using multiple requests, then the last request + will override the other sessions in the cluster. +

    + +

    Monitoring your Cluster with JMX

    +

    Monitoring is a very important question when you use a cluster. Some of the cluster objects are JMX MBeans

    +

    Add the following parameter to your startup script with Java 5:

    +
    set CATALINA_OPTS=\
    +-Dcom.sun.management.jmxremote \
    +-Dcom.sun.management.jmxremote.port=%my.jmx.port% \
    +-Dcom.sun.management.jmxremote.ssl=false \
    +-Dcom.sun.management.jmxremote.authenticate=false
    + +

    + List of Cluster Mbeans +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameDescriptionMBean ObjectName - EngineMBean ObjectName - Host
    ClusterThe complete cluster elementtype=Clustertype=Cluster,host=${HOST}
    DeltaManagerThis manager control the sessions and handle session replication type=Manager,context=${APP.CONTEXT.PATH}, host=${HOST}type=Manager,context=${APP.CONTEXT.PATH}, host=${HOST}
    FarmWarDeployerManages the process of deploying an application to all nodes in the clusterNot supportedtype=Cluster, host=${HOST}, component=deployer
    MemberRepresents a node in the clustertype=Cluster, component=member, name=${NODE_NAME}type=Cluster, host=${HOST}, component=member, name=${NODE_NAME}
    ReplicationValveThis valve control the replication to the backup nodestype=Valve,name=ReplicationValvetype=Valve,name=ReplicationValve,host=${HOST}
    JvmRouteBinderValveThis is a cluster fallback valve to change the Session ID to the current tomcat jvmroute.type=Valve,name=JvmRouteBinderValve, + context=${APP.CONTEXT.PATH}type=Valve,name=JvmRouteBinderValve,host=${HOST}, + context=${APP.CONTEXT.PATH}
    +

    FAQ

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/comments.html b/tomcat/docs/comments.html new file mode 100644 index 0000000..341f2cb --- /dev/null +++ b/tomcat/docs/comments.html @@ -0,0 +1,122 @@ + +Apache Tomcat 8 (8.5.43) - Documentation User Comments

    Documentation User Comments

    Introduction

    + +

    The Tomcat documentation integrates the +Apache Comments System. +It allows users to add comments to most documentation pages. The comments +section can be found at the end of each page.

    + +

    Allowed Content

    + +

    Please use the Apache Comments System responsibly. We can only provide +this service to the community as long as it isn't misused.

    + +

    The comments are not for general Q&A. +Comments should be pointed towards suggestions on improving the documentation +or server. Questions on how to use Apache Tomcat should be directed +to our mailing lists.

    + +

    Comments may be removed by moderators if they are either +implemented or considered invalid/off-topic.

    + +

    HTML is not allowed in comments, and will just display as raw source code +if attempted. Links that do not point to an Apache site (*.apache.org) will +need approval by a moderator before the comment is visible to regular visitors.

    + +

    License

    + +

    Any submitted comments must be contributed under the terms of the +Apache License, Version 2.0.

    + +

    Verified Users

    + +

    Verified users gain the Apache feather next to their name, +and may post comments with links in them without requiring approval +by a moderator before the comments are shown. Being a verified user +in itself does not give you moderating rights. If you are interested +in becoming a verified user, please contact us on the +users mailing list.

    + +

    All ASF committers are automatically verified users.

    + +

    Moderators

    + +

    Moderators are allowed to mark comments as "Resolved", "Invalid" +or "Sticky", remove marks, approve comments e.g. if they contain +a link, and delete comments. Moderators can also subscribe to new +comments and comment updates and use the dashboard to gain some +overview over all comments of a site.

    + +

    To use the moderation features, you need to login to the comments +system. Furthermore you will need to allow cookies to be set for +comments.apache.org (this is done using a secure https cookie). Once +logged in as a moderator you will see additional moderation +options attached to each comment.

    + +

    If you are a long time follower of the Apache Tomcat projects +and you are interested in becoming a moderator, please contact us on the +users mailing list.

    + +

    Privacy Policy

    + +

    No data except what you personally submit is kept on record. +A cookie is used to keep track of moderators and other people +who wish to create an account to avoid having to enter their +credentials whenever they wish to post a comment.

    + +

    To prevent spam and unsolicited comments, we use a digest of +visitors' IPs to keep track of comments posted by them.

    + +

    Entering an email address when you post a comment is completely +optional, and will not be shared with anyone. If you enter an +email address, it will be used to notify you when someone posts +a reply to one of your comments, provided you have registered +an account and validated your email address.

    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/ajp.html b/tomcat/docs/config/ajp.html new file mode 100644 index 0000000..e549e70 --- /dev/null +++ b/tomcat/docs/config/ajp.html @@ -0,0 +1,735 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - The AJP Connector

    The AJP Connector

    Table of Contents

    Introduction

    + +

    The AJP Connector element represents a + Connector component that communicates with a web + connector via the AJP protocol. This is used for cases + where you wish to invisibly integrate Tomcat into an existing (or new) + Apache installation, and you want Apache to handle the static content + contained in the web application, and/or utilize Apache's SSL + processing.

    + +

    This connector supports load balancing when used in conjunction with + the jvmRoute attribute of the + Engine.

    + +

    The native connectors supported with this Tomcat release are:

    +
      +
    • JK 1.2.x with any of the supported servers. See + the JK docs + for details.
    • +
    • mod_proxy on Apache httpd 2.x (included by default in Apache HTTP + Server 2.2), with AJP enabled: see + the + httpd docs for details.
    • +
    + +

    Other native connectors supporting AJP may work, but are no longer + supported.

    + +

    Attributes

    + +

    Common Attributes

    + +

    All implementations of Connector + support the following attributes:

    + +
    + Attribute + + Description +
    ajpFlush +

    A boolean value which can be used to enable or disable sending + AJP flush messages to the fronting proxy whenever an explicit + flush happens. The default value is true.
    + An AJP flush message is a SEND_BODY_CHUNK packet with no body content. + Proxy implementations like mod_jk or mod_proxy_ajp will flush the + data buffered in the web server to the client when they receive + such a packet. Setting this to false can reduce + AJP packet traffic but might delay sending packets to the client. + At the end of the response, AJP does always flush to the client.

    +
    allowTrace +

    A boolean value which can be used to enable or disable the TRACE + HTTP method. If not specified, this attribute is set to false.

    +
    asyncTimeout +

    The default timeout for asynchronous requests in milliseconds. If not + specified, this attribute is set to the Servlet specification default of + 30000 (30 seconds).

    +
    enableLookups +

    Set to true if you want calls to + request.getRemoteHost() to perform DNS lookups in + order to return the actual host name of the remote client. Set + to false to skip the DNS lookup and return the IP + address in String form instead (thereby improving performance). + By default, DNS lookups are disabled.

    +
    maxHeaderCount +

    The maximum number of headers in a request that are allowed by the + container. A request that contains more headers than the specified limit + will be rejected. A value of less than 0 means no limit. + If not specified, a default of 100 is used.

    +
    maxParameterCount +

    The maximum number of parameter and value pairs (GET plus POST) which + will be automatically parsed by the container. Parameter and value pairs + beyond this limit will be ignored. A value of less than 0 means no limit. + If not specified, a default of 10000 is used. Note that + FailedRequestFilter filter can be + used to reject requests that hit the limit.

    +
    maxPostSize +

    The maximum size in bytes of the POST which will be handled by + the container FORM URL parameter parsing. The limit can be disabled by + setting this attribute to a value less than zero. If not specified, this + attribute is set to 2097152 (2 megabytes). Note that the + FailedRequestFilter + can be used to reject requests that exceed this limit.

    +
    maxSavePostSize +

    The maximum size in bytes of the POST which will be saved/buffered by + the container during FORM or CLIENT-CERT authentication. For both types + of authentication, the POST will be saved/buffered before the user is + authenticated. For CLIENT-CERT authentication, the POST is buffered for + the duration of the SSL handshake and the buffer emptied when the request + is processed. For FORM authentication the POST is saved whilst the user + is re-directed to the login form and is retained until the user + successfully authenticates or the session associated with the + authentication request expires. The limit can be disabled by setting this + attribute to -1. Setting the attribute to zero will disable the saving of + POST data during authentication. If not specified, this attribute is set + to 4096 (4 kilobytes).

    +
    parseBodyMethods +

    A comma-separated list of HTTP methods for which request + bodies using application/x-www-form-urlencoded will be parsed + for request parameters identically to POST. This is useful in RESTful + applications that want to support POST-style semantics for PUT requests. + Note that any setting other than POST causes Tomcat + to behave in a way that goes against the intent of the servlet + specification. + The HTTP method TRACE is specifically forbidden here in accordance + with the HTTP specification. + The default is POST

    +
    port +

    The TCP port number on which this Connector + will create a server socket and await incoming connections. Your + operating system will allow only one server application to listen + to a particular port number on a particular IP address. If the special + value of 0 (zero) is used, then Tomcat will select a free port at random + to use for this connector. This is typically only useful in embedded and + testing applications.

    +
    protocol +

    Sets the protocol to handle incoming traffic. To configure an AJP + connector this must be specified. If no value for protocol is provided, + an HTTP connector rather than an AJP connector + will be configured.
    + The standard protocol value for an AJP connector is AJP/1.3 + which uses an auto-switching mechanism to select either a Java NIO based + connector or an APR/native based connector. If the + PATH (Windows) or LD_LIBRARY_PATH (on most unix + systems) environment variables contain the Tomcat native library, the + native/APR connector will be used. If the native library cannot be + found, the Java NIO based connector will be used.
    + To use an explicit protocol rather than rely on the auto-switching + mechanism described above, the following values may be used:
    + org.apache.coyote.ajp.AjpNioProtocol + - non blocking Java NIO connector.
    + org.apache.coyote.ajp.AjpNio2Protocol + - non blocking Java NIO2 connector.
    + org.apache.coyote.ajp.AjpAprProtocol + - the APR/native connector.
    + Custom implementations may also be used.
    + Take a look at our Connector + Comparison chart. +

    +
    proxyName +

    If this Connector is being used in a proxy + configuration, configure this attribute to specify the server name + to be returned for calls to request.getServerName(). + See Proxy Support for more + information.

    +
    proxyPort +

    If this Connector is being used in a proxy + configuration, configure this attribute to specify the server port + to be returned for calls to request.getServerPort(). + See Proxy Support for more + information.

    +
    redirectPort +

    If this Connector is supporting non-SSL + requests, and a request is received for which a matching + <security-constraint> requires SSL transport, + Catalina will automatically redirect the request to the port + number specified here.

    +
    scheme +

    Set this attribute to the name of the protocol you wish to have + returned by calls to request.getScheme(). For + example, you would set this attribute to "https" + for an SSL Connector. The default value is "http". +

    +
    secure +

    Set this attribute to true if you wish to have + calls to request.isSecure() to return true + for requests received by this Connector. You would want this on an + SSL Connector or a non SSL connector that is receiving data from a + SSL accelerator, like a crypto card, a SSL appliance or even a webserver. + The default value is false.

    +
    sendReasonPhrase +

    Set this attribute to true if you wish to have + a reason phrase in the response. + The default value is false.

    +

    Note: This option is deprecated and will be removed + in Tomcat 9. The reason phrase will not be sent.

    +
    URIEncoding +

    This specifies the character encoding used to decode the URI bytes, + after %xx decoding the URL. If not specified, UTF-8 will be used unless + the org.apache.catalina.STRICT_SERVLET_COMPLIANCE + system property is set to true + in which case ISO-8859-1 will be used.

    +
    useBodyEncodingForURI +

    This specifies if the encoding specified in contentType should be used + for URI query parameters, instead of using the URIEncoding. This + setting is present for compatibility with Tomcat 4.1.x, where the + encoding specified in the contentType, or explicitly set using + Request.setCharacterEncoding method was also used for the parameters from + the URL. The default value is false. +

    +

    Notes: See notes on this attribute in + HTTP Connector documentation.

    +
    useIPVHosts +

    Set this attribute to true to cause Tomcat to use + the IP address passed by the native web server to determine the Host + to send the request to. The default value is false.

    +
    xpoweredBy +

    Set this attribute to true to cause Tomcat to advertise + support for the Servlet specification using the header recommended in the + specification. The default value is false.

    +
    + +
    + +

    Standard Implementations

    + +

    To use AJP, you must specify the protocol attribute (see above).

    + +

    The standard AJP connectors (NIO, NIO2 and APR/native) all support the + following attributes in addition to the common Connector attributes listed + above.

    + +
    + Attribute + + Description +
    acceptCount +

    The maximum queue length for incoming connection requests when + all possible request processing threads are in use. Any requests + received when the queue is full will be refused. The default + value is 100.

    +
    acceptorThreadCount +

    The number of threads to be used to accept connections. Increase this + value on a multi CPU machine, although you would never really need more + than 2. Also, with a lot of non keep alive connections, you + might want to increase this value as well. Default value is + 1.

    +
    acceptorThreadPriority +

    The priority of the acceptor threads. The threads used to accept + new connections. The default value is 5 (the value of the + java.lang.Thread.NORM_PRIORITY constant). See the JavaDoc + for the java.lang.Thread class for more details on what + this priority means.

    +
    address +

    For servers with more than one IP address, this attribute + specifies which address will be used for listening on the specified + port. By default, this port will be used on all IP addresses + associated with the server. A value of 127.0.0.1 + indicates that the Connector will only listen on the loopback + interface.

    +
    bindOnInit +

    Controls when the socket used by the connector is bound. By default it + is bound when the connector is initiated and unbound when the connector is + destroyed. If set to false, the socket will be bound when the + connector is started and unbound when it is stopped.

    +
    clientCertProvider +

    When client certificate information is presented in a form other than + instances of java.security.cert.X509Certificate it needs to + be converted before it can be used and this property controls which JSSE + provider is used to perform the conversion. For example it is used with + the AJP connectors, the HTTP APR connector and + with the + org.apache.catalina.valves.SSLValve.If not specified, the default + provider will be used.

    +
    connectionLinger +

    The number of seconds during which the sockets used by this + Connector will linger when they are closed. The default + value is -1 which disables socket linger.

    +
    connectionTimeout +

    The number of milliseconds this Connector will wait, + after accepting a connection, for the request URI line to be + presented. The default value for AJP protocol connectors + is -1 (i.e. infinite).

    +
    executor +

    A reference to the name in an Executor + element. If this attribute is set, and the named executor exists, the + connector will use the executor, and all the other thread attributes will + be ignored. Note that if a shared executor is not specified for a + connector then the connector will use a private, internal executor to + provide the thread pool.

    +
    executorTerminationTimeoutMillis +

    The time that the private internal executor will wait for request + processing threads to terminate before continuing with the process of + stopping the connector. If not set, the default is 5000 (5 + seconds).

    +
    keepAliveTimeout +

    The number of milliseconds this Connector will wait for + another AJP request before closing the connection. + The default value is to use the value that has been set for the + connectionTimeout attribute.

    +
    maxConnections +

    The maximum number of connections that the server will accept and + process at any given time. When this number has been reached, the server + will accept, but not process, one further connection. This additional + connection be blocked until the number of connections being processed + falls below maxConnections at which point the server will + start accepting and processing new connections again. Note that once the + limit has been reached, the operating system may still accept connections + based on the acceptCount setting. The default value varies by + connector type. For NIO and NIO2 the default is 10000. + For APR/native, the default is 8192.

    +

    Note that for APR/native on Windows, the configured value will be + reduced to the highest multiple of 1024 that is less than or equal to + maxConnections. This is done for performance reasons.
    + If set to a value of -1, the maxConnections feature is disabled + and connections are not counted.

    +
    maxCookieCount +

    The maximum number of cookies that are permitted for a request. A value + of less than zero means no limit. If not specified, a default value of 200 + will be used.

    +
    maxThreads +

    The maximum number of request processing threads to be created + by this Connector, which therefore determines the + maximum number of simultaneous requests that can be handled. If + not specified, this attribute is set to 200. If an executor is associated + with this connector, this attribute is ignored as the connector will + execute tasks using the executor rather than an internal thread pool. Note + that if an executor is configured any value set for this attribute will be + recorded correctly but it will be reported (e.g. via JMX) as + -1 to make clear that it is not used.

    +
    minSpareThreads +

    The minimum number of threads always kept running. This includes both + active and idle threads. If not specified, the default of 10 + is used. If an executor is associated with this connector, this attribute + is ignored as the connector will execute tasks using the executor rather + than an internal thread pool. Note that if an executor is configured any + value set for this attribute will be recorded correctly but it will be + reported (e.g. via JMX) as -1 to make clear that it is not + used.

    +
    packetSize +

    This attribute sets the maximum AJP packet size in Bytes. The maximum + value is 65536. It should be the same as the max_packet_size + directive configured for mod_jk. Normally it is not necessary to change + the maximum packet size. Problems with the default value have been + reported when sending certificates or certificate chains. The default + value is 8192. If set to less than 8192 then the setting will ignored and + the default value of 8192 used.

    +
    processorCache +

    The protocol handler caches Processor objects to speed up performance. + This setting dictates how many of these objects get cached. + -1 means unlimited, default is 200. If not using + Servlet 3.0 asynchronous processing, a good default is to use the same as + the maxThreads setting. If using Servlet 3.0 asynchronous processing, a + good default is to use the larger of maxThreads and the maximum number of + expected concurrent requests (synchronous and asynchronous).

    +
    requiredSecret +

    Only requests from workers with this secret keyword will be accepted. +

    +
    tcpNoDelay +

    If set to true, the TCP_NO_DELAY option will be + set on the server socket, which improves performance under most + circumstances. This is set to true by default.

    +
    threadPriority +

    The priority of the request processing threads within the JVM. + The default value is 5 (the value of the + java.lang.Thread.NORM_PRIORITY constant). See the JavaDoc + for the java.lang.Thread class for more details on what + this priority means.If an executor is associated + with this connector, this attribute is ignored as the connector will + execute tasks using the executor rather than an internal thread pool. Note + that if an executor is configured any value set for this attribute will be + recorded correctly but it will be reported (e.g. via JMX) as + -1 to make clear that it is not used.

    +
    tomcatAuthentication +

    If set to true, the authentication will be done in Tomcat. + Otherwise, the authenticated principal will be propagated from the native + webserver and used for authorization in Tomcat. Note that this principal + will have no roles associated with it. + The default value is true. If + tomcatAuthorization is set to true this + attribute has no effect.

    +
    tomcatAuthorization +

    If set to true, the authenticated principal will be + propagated from the native webserver and considered already authenticated + in Tomcat. If the web application has one or more security constraints, + authorization will then be performed by Tomcat and roles assigned to the + authenticated principal. If the appropriate Tomcat Realm for the request + does not recognise the provided user name, a Principal will be still be + created but it will have no roles. The default value is + false.

    +
    + +
    + +

    Java TCP socket attributes

    + +

    The NIO and NIO2 implementation support the following Java TCP socket + attributes in addition to the common Connector and HTTP attributes listed + above.

    + +
    + Attribute + + Description +
    socket.rxBufSize +

    (int)The socket receive buffer (SO_RCVBUF) size in bytes. JVM default + used if not set.

    +
    socket.txBufSize +

    (int)The socket send buffer (SO_SNDBUF) size in bytes. JVM default + used if not set.

    +
    socket.tcpNoDelay +

    (bool)This is equivalent to standard attribute + tcpNoDelay.

    +
    socket.soKeepAlive +

    (bool)Boolean value for the socket's keep alive setting + (SO_KEEPALIVE). JVM default used if not set.

    +
    socket.ooBInline +

    (bool)Boolean value for the socket OOBINLINE setting. JVM default + used if not set.

    +
    socket.soReuseAddress +

    (bool)Boolean value for the sockets reuse address option + (SO_REUSEADDR). JVM default used if not set.

    +
    socket.soLingerOn +

    (bool)Boolean value for the sockets so linger option (SO_LINGER). + A value for the standard attribute connectionLinger + that is >=0 is equivalent to setting this to true. + A value for the standard attribute connectionLinger + that is <0 is equivalent to setting this to false. + Both this attribute and soLingerTime must be set else the + JVM defaults will be used for both.

    +
    socket.soLingerTime +

    (int)Value in seconds for the sockets so linger option (SO_LINGER). + This is equivalent to standard attribute + connectionLinger. + Both this attribute and soLingerOn must be set else the + JVM defaults will be used for both.

    +
    socket.soTimeout +

    This is equivalent to standard attribute + connectionTimeout.

    +
    socket.performanceConnectionTime +

    (int)The first value for the performance settings. See + Socket Performance Options + All three performance attributes must be set else the JVM defaults will + be used for all three.

    +
    socket.performanceLatency +

    (int)The second value for the performance settings. See + Socket Performance Options + All three performance attributes must be set else the JVM defaults will + be used for all three.

    +
    socket.performanceBandwidth +

    (int)The third value for the performance settings. See + Socket Performance Options + All three performance attributes must be set else the JVM defaults will + be used for all three.

    +
    socket.unlockTimeout +

    (int) The timeout for a socket unlock. When a connector is stopped, it will try to release the acceptor thread by opening a connector to itself. + The default value is 250 and the value is in milliseconds

    +
    +
    + +

    NIO specific configuration

    + +

    The following attributes are specific to the NIO connector.

    + +
    + Attribute + + Description +
    socket.directBuffer +

    (bool)Boolean value, whether to use direct ByteBuffers or java mapped + ByteBuffers. Default is false.
    + When you are using direct buffers, make sure you allocate the + appropriate amount of memory for the direct memory space. On Sun's JDK + that would be something like -XX:MaxDirectMemorySize=256m. +

    +
    socket.appReadBufSize +

    (int)Each connection that is opened up in Tomcat get associated with + a read ByteBuffer. This attribute controls the size of this buffer. By + default this read buffer is sized at 8192 bytes. For lower + concurrency, you can increase this to buffer more data. For an extreme + amount of keep alive connections, decrease this number or increase your + heap size.

    +
    socket.appWriteBufSize +

    (int)Each connection that is opened up in Tomcat get associated with + a write ByteBuffer. This attribute controls the size of this buffer. By + default this write buffer is sized at 8192 bytes. For low + concurrency you can increase this to buffer more response data. For an + extreme amount of keep alive connections, decrease this number or + increase your heap size.
    + The default value here is pretty low, you should up it if you are not + dealing with tens of thousands concurrent connections.

    +
    socket.bufferPool +

    (int)The NIO connector uses a class called NioChannel that holds + elements linked to a socket. To reduce garbage collection, the NIO + connector caches these channel objects. This value specifies the size of + this cache. The default value is 500, and represents that + the cache will hold 500 NioChannel objects. Other values are + -1 for unlimited cache and 0 for no cache.

    +
    socket.bufferPoolSize +

    (int)The NioChannel pool can also be size based, not used object + based. The size is calculated as follows:
    + NioChannel + buffer size = read buffer size + write buffer size
    + SecureNioChannel buffer size = application read buffer size + + application write buffer size + network read buffer size + + network write buffer size
    + The value is in bytes, the default value is 1024*1024*100 + (100MB).

    +
    socket.processorCache +

    (int)Tomcat will cache SocketProcessor objects to reduce garbage + collection. The integer value specifies how many objects to keep in the + cache at most. The default is 500. Other values are + -1 for unlimited cache and 0 for no cache.

    +
    socket.keyCache +

    (int)Tomcat will cache KeyAttachment objects to reduce garbage + collection. The integer value specifies how many objects to keep in the + cache at most. The default is 500. Other values are + -1 for unlimited cache and 0 for no cache.

    +
    socket.eventCache +

    (int)Tomcat will cache PollerEvent objects to reduce garbage + collection. The integer value specifies how many objects to keep in the + cache at most. The default is 500. Other values are + -1 for unlimited cache and 0 for no cache.

    +
    selectorPool.maxSelectors +

    (int)The max selectors to be used in the pool, to reduce selector + contention. Use this option when the command line + org.apache.tomcat.util.net.NioSelectorShared value is set + to false. Default value is 200.

    +
    selectorPool.maxSpareSelectors +

    (int)The max spare selectors to be used in the pool, to reduce + selector contention. When a selector is returned to the pool, the system + can decide to keep it or let it be GC'd. Use this option when the + command line org.apache.tomcat.util.net.NioSelectorShared + value is set to false. Default value is -1 (unlimited).

    +
    command-line-options +

    The following command line options are available for the NIO + connector:
    + -Dorg.apache.tomcat.util.net.NioSelectorShared=true|false + - default is true. Set this value to false if you wish to + use a selector for each thread. When you set it to false, you can + control the size of the pool of selectors by using the + selectorPool.maxSelectors attribute.

    +
    +
    + +

    NIO2 specific configuration

    + +

    The following attributes are specific to the NIO2 connector.

    + +
    + Attribute + + Description +
    useCaches +

    (bool)Use this attribute to enable or disable object caching to + reduce the amount of GC objects produced. + The default value is false.

    +
    socket.directBuffer +

    (bool)Boolean value, whether to use direct ByteBuffers or java mapped + ByteBuffers. Default is false.
    + When you are using direct buffers, make sure you allocate the + appropriate amount of memory for the direct memory space. On Sun's JDK + that would be something like -XX:MaxDirectMemorySize=256m. +

    +
    socket.appReadBufSize +

    (int)Each connection that is opened up in Tomcat get associated with + a read ByteBuffer. This attribute controls the size of this buffer. By + default this read buffer is sized at 8192 bytes. For lower + concurrency, you can increase this to buffer more data. For an extreme + amount of keep alive connections, decrease this number or increase your + heap size.

    +
    socket.appWriteBufSize +

    (int)Each connection that is opened up in Tomcat get associated with + a write ByteBuffer. This attribute controls the size of this buffer. By + default this write buffer is sized at 8192 bytes. For low + concurrency you can increase this to buffer more response data. For an + extreme amount of keep alive connections, decrease this number or + increase your heap size.
    + The default value here is pretty low, you should up it if you are not + dealing with tens of thousands concurrent connections.

    +
    socket.bufferPoolSize +

    (int)The NIO2 connector uses a class called Nio2Channel that holds + elements linked to a socket. To reduce garbage collection, the NIO + connector caches these channel objects. This value specifies the size of + this cache. The default value is 500, and represents that + the cache will hold 500 Nio2Channel objects. Other values are + -1 for unlimited cache and 0 for no cache.

    +
    socket.processorCache +

    (int)Tomcat will cache SocketProcessor objects to reduce garbage + collection. The integer value specifies how many objects to keep in the + cache at most. The default is 500. Other values are + -1 for unlimited cache and 0 for no cache.

    +
    +
    + +

    APR/native specific configuration

    + +

    The APR/native implementation supports the following attributes in + addition to the common Connector and AJP attributes listed above.

    + +
    + Attribute + + Description +
    pollTime +

    Duration of a poll call in microseconds. Lowering this value will + slightly decrease latency of connections being kept alive in some cases + , but will use more CPU as more poll calls are being made. The default + value is 2000 (2ms). +

    +
    + +
    + +

    Nested Components

    + +

    None at this time.

    + +

    Special Features

    + +

    Proxy Support

    + +

    The proxyName and proxyPort attributes can + be used when Tomcat is run behind a proxy server. These attributes + modify the values returned to web applications that call the + request.getServerName() and request.getServerPort() + methods, which are often used to construct absolute URLs for redirects. + Without configuring these attributes, the values returned would reflect + the server name and port on which the connection from the proxy server + was received, rather than the server name and port to whom the client + directed the original request.

    + +

    For more information, see the + Proxy Support How-To.

    + +
    + +

    Connector Comparison

    + +

    Below is a small chart that shows how the connectors differ.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Java Nio Connector
    NIO
    Java Nio2 Connector
    NIO2
    APR/native Connector
    APR
    ClassnameAjpNioProtocolAjpNio2ProtocolAjpAprProtocol
    Tomcat Version7.x onwards8.x onwards5.5.x onwards
    Support PollingYESYESYES
    Polling SizemaxConnectionsmaxConnectionsmaxConnections
    Read Request HeadersBlockingBlockingBlocking
    Read Request BodyBlockingBlockingBlocking
    Write Response Headers and BodyBlockingBlockingBlocking
    Wait for next RequestNon BlockingNon BlockingNon Blocking
    Max ConnectionsmaxConnectionsmaxConnectionsmaxConnections
    + +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/automatic-deployment.html b/tomcat/docs/config/automatic-deployment.html new file mode 100644 index 0000000..6634091 --- /dev/null +++ b/tomcat/docs/config/automatic-deployment.html @@ -0,0 +1,540 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - Automatic Deployment - Use cases

    Automatic Deployment - Use cases

    Table of Contents

    Introduction

    + +

    This page defines the expected behaviour of the automatic deployer in many + typical use cases. This is a complex area of Tomcat's functionality. + While any difference between this document and Tomcat's behaviour is a + bug, the fix may be to change this document, Tomcat's behaviour or + both.

    + +

    Key

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    TermDescription
    XMLAn XML configuration file located in the Host's + configBase. It must contain a single <Context> element + and may contain optional nested elements. It does not define an + explicit docBase attribute. It represents a single web + application. It is often referred to as a context.xml file.
    XML+EWAn XML configuration file located in the Host's + configBase. It must contain a single <Context> element + and may contain optional nested elements. It includes an explicit + docBase attribute that points to an external WAR. It + represents a single web application. It is often referred to as a + context.xml file.
    XML+EDAn XML configuration file located in the Host's + configBase. It must contain a single <Context> element + and may contain optional nested elements. It includes an explicit + docBase attribute that points to an external directory. It + represents a single web application. It is often referred to as a + context.xml file.
    WARA WAR file located in the Host's appBase. The WAR does + not include an embedded context.xml file.
    WAR+XMLA WAR file located in the Host's appBase. The WAR does + include an embedded context.xml file.
    DIRA directory located in the Host's appBase. The directory + does not include an embedded context.xml file.
    DIR+XMLA directory located in the Host's appBase. The directory + does include an embedded context.xml file.
    redeployThe Context object that represents the web application is destroyed + and a new Context object is created. If present and permitted by the + configuration, this new Context object is created by parsing the + context.xml file. The web.xml file is parsed during the application + start process. Any sessions stored in the standard Manager in the + default configuration will not be persisted. Any requests to the web + application during the redeploy will be handled as if the web + application is not deployed.
    reloadThe Context object that represents the web application is stopped and + then started. The web.xml file is parsed during the application start + process. Any sessions stored in the standard Manager in the default + configuration will not be persisted. Any requests to the web + application during the reload will be held until the reload completes + at which point they will continue using the reloaded web application. +
    + +

    New files

    + +

    This section describes Tomcat's behaviour when the automatic + deployment process discovers a new web application.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Starting artifact(s)Configuration SettingsResult
    deployXMLcopyXMLunpackWARsXMLWARDIRNotes
    XMLeithereithereitherYNN1, 2, 3
    XML+EWeithereitherfalseYNN1
    XML+EWeithereithertrueYNY1
    XML+EDeithereithereitherYNN1, 2
    WAR+XMLfalseeitherfalseNYN4
    WAR+XMLfalseeithertrueNYY4
    WAR+XMLtruefalsefalseNYN
    WAR+XMLtruefalsetrueNYY
    WAR+XMLtruetruefalseYYN
    WAR+XMLtruetruetrueYYY
    WAReithereitherfalseNYN
    WAReithereithertrueNYY
    DIR+XMLfalseeithereitherNNY4
    DIR+XMLtruefalseeitherNNY
    DIR+XMLtruetrueeitherYNY
    DIRfalseeithereitherNNY
    + +

    Deleted files

    + +

    This section describes Tomcat's behaviour when the automatic + deployment process detects that a web application file has been deleted.

    + +

    When a file is deleted or modified any redeploy resources that are listed + after the modified/deleted resource are themselves deleted (and possibly + re-created). The order of redeploy resources is:

    + +
      +
    1. WAR
    2. +
    3. DIR
    4. +
    5. XML
    6. +
    7. global resources
    8. +
    + +

    There are some exceptions to the deletion rule above:

    + +
      +
    • global resources are never deleted
    • +
    • external resources are never deleted
    • +
    • if the WAR or DIR has been modified then the XML file is only deleted if + copyXML is true and deployXML is + true
    • +
    + +

    In the following table:

    + +
      +
    • '-' means "unchanged from not present". i.e. the artifact wasn't present + before the change and isn't present after it either. '-' rather than 'N' + is used to focus attention on what changes.
    • +
    • 'R' means that the directory is re-created by expanding the WAR file. + This will only happen if unpackWARs is true.
    • +
    • 'XW' means that the if the WAR contains a META-INF/context.xml file it + will be extracted and placed in the Host's configBase. + This only happens if copyXML is true and + deployXML is true.
    • +
    • 'XD' means that the if the directory contains a META-INF/context.xml + file it will be copied to the Host's configBase. This only + happens if copyXML is true and deployXML + is true.
    • +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Artifacts presentArtifact removedArtifacts remaining
    XMLWARDIRXMLWARDIRNotes
    NNYDIR--N
    NYNWAR-N-
    NYYDIR-YR
    NYYWAR-NN
    YNNXMLN--
    YNYDIRN-N5
    YNYXMLXD-Y
    YYNWARNN-5
    YYNXMLXWY-
    YYYDIRXWYR
    YYYWARNNN
    YYYXMLXWYY
    YY (external)NWARYN-3
    YY (external)NXMLNY (external)-6
    YNY (external)DIRY-N3
    YNY (external)XMLN-Y (external)6
    YY (external)YDIRYY (external)R
    YY (external)YWARYNN3
    YY (external)YXMLNY (external)N6
    + +

    Modified files

    + +

    This section describes Tomcat's behaviour when the automatic + deployment process detects that a web application file has been modified.

    + +

    In the following table:

    + +
      +
    • '-' means "unchanged from not present". i.e. the artifact wasn't present + before the change and isn't present after it either. '-' rather than 'N' + is used to focus attention on what changes.
    • +
    • 'M' means that the artifact has been modified.
    • +
    • 'R' means that the directory is deleted and re-created by expanding the + WAR file. This will only happen if unpackWARs is + true.
    • +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Artifacts presentArtifact modifiedArtifacts remaining
    XMLWARDIRXMLWARDIRAction
    NNYDIR--MNone
    NYNWAR-M-Redeploy
    NYYDIR-YMNone
    NYYWAR-MRRedeploy
    YNNXMLM--Redeploy
    YNYDIRY-MNone
    YNYXMLM-YRedeploy
    YYNWARYM-Reload
    YYNXMLMY-Redeploy
    YYYDIRYYMNone
    YYYWARYMRReload
    YYYXMLMYYRedeploy
    YY(external)NWARYM(external)-Reload
    YY(external)NXMLMY(external)-Redeploy
    YNY(external)DIRY-M(external)None
    YNY(external)XMLM-Y(external)Redeploy
    YY(external)YDIRYY(external)MNone
    YY(external)YWARYM(external)RReload
    YY(external)YXMLMY(external)YRedeploy
    + +

    Added files

    + +

    This is treated as if the added file has been modified with the following + additional actions:

    + +
      +
    • If a WAR is added, any DIR is removed and may be recreated depending on + unpackWARs.
    • +
    • If an XML file is added that refers to an external docBase any + WAR or DIR in the appBase will be removed. The DIR may be recreated if + the external resource is a WAR and unpackWARs is true.
    • +
    • If a DIR is added when a WAR already exists and unpackWARs is + false, the DIR will be ignored but a warning will be + logged when the DIR is first detected. If the WAR is removed, the DIR + will be left and may be deployed via automatic deployment.
    • +
    • If a WAR is added to the appBase when an external WAR already + exists, the WAR in the appBase will be ignored but a warning + will be logged when the WAR in the appBase is first detected. + If the external WAR is removed, the WAR in the appBase will be + left and may be deployed via automatic deployment.
    • +
    • If an XML file is added to the META-INF directory of an application + deployed from that DIR, the application will always be redeployed. The + result will be the same as for a new deployment.
    • +
    + +

    Notes

    + +
      +
    1. deployXML and copyXML are ignored since an XML file + was discovered in the configBase.
    2. +
    3. unpackWARs is ignored since there is no WAR file.
    4. +
    5. The context will fail to start because there is no content in the + expected docBase.
    6. +
    7. The web application fails to deploy because it contains an embedded + META-INF/context.xml, deployXML is false and an + XML has not been provided in the configBase.
    8. +
    9. The XML file is only deleted if copyXML is true + and deployXML is true.
    10. +
    11. Although the external resource is still present, the web application is + fully undeployed as Tomcat has no knowledge of the external resource. +
    12. +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/cluster-channel.html b/tomcat/docs/config/cluster-channel.html new file mode 100644 index 0000000..b96cd36 --- /dev/null +++ b/tomcat/docs/config/cluster-channel.html @@ -0,0 +1,140 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - The Cluster Channel object

    The Cluster Channel object

    Table of Contents

    Introduction

    + The cluster channel is the main component of a small framework we've nicknamed Apache Tribes.
    + The channel manages a set of sub components and together they create a group communication framework.
    + This framework is then used internally by the components that need to send messages between different Tomcat instances. +
    + A few examples of these components would be the SimpleTcpCluster that does the messaging for the DeltaManager, + or the BackupManager that uses a different replication strategy. The ReplicatedContext object does also + use the channel object to communicate context attribute changes. +

    Nested Components

    +

    Channel/Membership:
    + The Membership component is responsible for auto discovering new nodes in the cluster + and also to provide for notifications for any nodes that have not responded with a heartbeat. + The default implementation uses multicast.
    + In the membership component you configure how your nodes, aka. members, are to be discovered and/or + divided up. + You can always find out more about Apache Tribes +

    +

    Channel/Sender:
    + The Sender component manages all outbound connections and data messages that are sent + over the network from one node to another. + This component allows messages to be sent in parallel. + The default implementation uses TCP client sockets, and socket tuning for outgoing messages are + configured here.
    + You can always find out more about Apache Tribes +

    +

    Channel/Sender/Transport:
    + The Transport component is the bottom IO layer for the sender component. + The default implementation uses non-blocking TCP client sockets.
    + You can always find out more about Apache Tribes +

    +

    Channel/Receiver:
    + The receiver component listens for messages from other nodes. + Here you will configure the cluster thread pool, as it will dispatch incoming + messages to a thread pool for faster processing. + The default implementation uses non-blocking TCP server sockets.
    + You can always find out more about Apache Tribes +

    +

    Channel/Interceptor:
    + The channel will send messages through an interceptor stack. Because of this, you have the ability to + customize the way messages are sent and received, and even how membership is handled.
    + You can always find out more about Apache Tribes +

    +

    Attributes

    + +

    Common Attributes

    + +
    + Attribute + + Description +
    className + The default value here is org.apache.catalina.tribes.group.GroupChannel and is + currently the only implementation available. +
    + + +
    + +

    org.apache.catalina.tribes.group.GroupChannel Attributes

    + +
    + Attribute + + Description +
    heartbeat + Flag whether the channel manages its own heartbeat. + If set to true, the channel start a local thread for the heart beat. + If set this flag to false, you must set SimpleTcpCluster#heartbeatBackgroundEnabled + to true. default value is true. +
    heartbeatSleeptime + If heartbeat == true, specifies the interval of heartbeat thread in milliseconds. + The default is 5000 (5 seconds). +
    optionCheck + If set to true, the GroupChannel will check the option flags that each + interceptor is using. Reports an error if two interceptor share the same + flag. The default is false. +
    jmxEnabled + Flag whether the channel components register with JMX or not. + The default value is true. +
    jmxDomain + if jmxEnabled set to true, specifies the jmx domain which + this channel should be registered. The ClusterChannel is used as the + default value. +
    jmxPrefix + if jmxEnabled set to true, specifies the jmx prefix which + will be used with channel ObjectName. +
    + +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/cluster-deployer.html b/tomcat/docs/config/cluster-deployer.html new file mode 100644 index 0000000..625d46f --- /dev/null +++ b/tomcat/docs/config/cluster-deployer.html @@ -0,0 +1,107 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - The Cluster Deployer object

    The Cluster Deployer object

    Table of Contents

    Introduction

    +

    The Farm War Deployer can deploy and undeploy web applications on the other + nodes in the cluster.

    +

    Note: FarmWarDeployer can be configured at host level + cluster only. +

    +

    org.apache.catalina.ha.deploy.FarmWarDeployer

    + +

    Attributes

    + +
    + Attribute + + Description +
    className + The cluster deployer class, currently only one is available, + org.apache.catalina.ha.deploy.FarmWarDeployer. +
    deployDir + Deployment directory. This is the pathname of a directory where deploy + the web applications. You may specify an absolute pathname, or a + pathname that is relative to the $CATALINA_BASE directory. In the + current implementation, this attribute must be the same value as the + Host's appBase. +
    tempDir + The temporaryDirectory to store binary data when downloading a war from + the cluster. You may specify an absolute pathname, or a pathname that is + relative to the $CATALINA_BASE directory. +
    watchDir + This is the pathname of a directory where watch for changes(add/modify/remove) + of web applications. You may specify an absolute pathname, or a pathname + that is relative to the $CATALINA_BASE directory. + Note: if watchEnabled is false, this + attribute will have no effect. +
    watchEnabled + Set to true if you want to watch for changes of web applications. + Only when this attribute set to true, you can trigger a deploy/undeploy + of web applications. The flag's value defaults to false. +
    processDeployFrequency + Frequency of the Farm watchDir check. Cluster wide deployment will be + done once for the specified amount of backgroundProcess calls (ie, the + lower the amount, the most often the checks will occur). The minimum + value is 1, and the default value is 2. + Note: if watchEnabled is false, this + attribute will have no effect. +
    maxValidTime + The maximum valid time(in seconds) of FileMessageFactory. + FileMessageFactory will be removed immediately after receiving the + complete WAR file but when failing to receive a FileMessage which was + sent dividing, FileMessageFactory will leak without being removed. + FileMessageFactory that is leaking will be automatically removed after + maxValidTime. If a negative value specified, FileMessageFactory will + never be removed. If the attribute is not provided, a default of 300 + seconds (5 minutes) is used. +
    + +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/cluster-interceptor.html b/tomcat/docs/config/cluster-interceptor.html new file mode 100644 index 0000000..f677c35 --- /dev/null +++ b/tomcat/docs/config/cluster-interceptor.html @@ -0,0 +1,317 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - The Channel Interceptor object

    The Channel Interceptor object

    Table of Contents

    Introduction

    +

    + Apache Tribes supports an interceptor architecture to intercept both messages and membership notifications. + This architecture allows decoupling of logic and opens the way for some very useful feature add ons. +

    +

    Available Interceptors

    +
      +
    • org.apache.catalina.tribes.group.interceptors.TcpFailureDetector
    • +
    • org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor
    • +
    • org.apache.catalina.tribes.group.interceptors.MessageDispatchInterceptor
    • +
    • org.apache.catalina.tribes.group.interceptors.NonBlockingCoordinator
    • +
    • org.apache.catalina.tribes.group.interceptors.OrderInterceptor
    • +
    • org.apache.catalina.tribes.group.interceptors.SimpleCoordinator
    • +
    • org.apache.catalina.tribes.group.interceptors.StaticMembershipInterceptor
    • +
    • org.apache.catalina.tribes.group.interceptors.TwoPhaseCommitInterceptor
    • +
    • org.apache.catalina.tribes.group.interceptors.DomainFilterInterceptor
    • +
    • org.apache.catalina.tribes.group.interceptors.FragmentationInterceptor
    • +
    • org.apache.catalina.tribes.group.interceptors.GzipInterceptor
    • +
    • org.apache.catalina.tribes.group.interceptors.TcpPingInterceptor
    • +
    • org.apache.catalina.tribes.group.interceptors.EncryptInterceptor
    • +
    +

    Static Membership

    +

    + In addition to dynamic discovery, Apache Tribes also supports static membership, with membership verification. + To achieve this add the org.apache.catalina.tribes.group.interceptors.StaticMembershipInterceptor + after the org.apache.catalina.tribes.group.interceptors.TcpFailureDetector interceptor. + Inside the StaticMembershipInterceptor you can add the static members you wish to have. + The TcpFailureDetector will do a health check on the static members,and also monitor them for crashes + so they will have the same level of notification mechanism as the members that are automatically discovered.

    +
         <Interceptor className="org.apache.catalina.tribes.group.interceptors.StaticMembershipInterceptor">
    +       <LocalMember className="org.apache.catalina.tribes.membership.StaticMember"
    +                  domain="staging-cluster"
    +                  uniqueId="{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,1}"/>
    +       <Member className="org.apache.catalina.tribes.membership.StaticMember"
    +                  port="5678"
    +                  securePort="-1"
    +                  host="tomcat01.mydomain.com"
    +                  domain="staging-cluster"
    +                  uniqueId="{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}"/>
    +     </Interceptor>
    +

    Attributes

    + +

    Common Attributes

    +
    + Attribute + + Description +
    className + Required, as there is no default +
    optionFlag + If you want the interceptor to trigger on certain message depending on the message's option flag, + you can setup the interceptors flag here. + The default value is 0, meaning this interceptor will trigger on all messages. +
    +
    + +

    org.apache.catalina.tribes.group.interceptors.DomainFilterInterceptor Attributes

    +
    + Attribute + + Description +
    domain + The logical cluster domain that this Interceptor accepts. + Two different type of values are possible:
    + 1. Regular string values like "staging-domain" or "tomcat-cluster" will be converted into bytes + using ISO-8859-1 encoding.
    + 2. byte array in string form, for example {216,123,12,3}
    +
    logInterval + This value indicates the interval for logging for messages from different domains. + The default is 100, which means that to log per 100 messages. +
    +
    +

    org.apache.catalina.tribes.group.interceptors.FragmentationInterceptor Attributes

    +
    + Attribute + + Description +
    expire + How long do we keep the fragments in memory and wait for the rest to arrive. + The default is 60000 ms. +
    maxSize + The maximum message size in bytes. If the message size exceeds this value, this interceptor fragments the message and sends them. + If it is less than this value, this interceptor does not fragment the message and sent in as one message. The default is 1024*100. +
    +
    +

    org.apache.catalina.tribes.group.interceptors.MessageDispatchInterceptor Attributes

    +
    + Attribute + + Description +
    optionFlag + The default and hard coded value is 8 (org.apache.catalina.tribes.Channel.SEND_OPTIONS_ASYNCHRONOUS). + The dispatcher will trigger on this value only, as it is predefined by Tribes. +
    alwaysSend + What behavior should be executed when the dispatch queue is full. If true (default), then the message is + is sent synchronously, if false an error is thrown. +
    maxQueueSize + Size in bytes of the dispatch queue, the default value is 1024*1024*64 (64MB) sets the maximum queue size for the dispatch queue + if the queue fills up, one can trigger the behavior, if alwaysSend is set to true, the message will be sent synchronously + if the flag is false, an error is thrown +
    maxThreads + The maximum number of threads in this pool, default is 10. +
    maxSpareThreads + The number of threads to keep in the pool, default is 2. +
    keepAliveTime + Maximum number of milliseconds of until Idle thread terminates. Default value is 5000(5 seconds). +
    +
    +

    org.apache.catalina.tribes.group.interceptors.TcpFailureDetector Attributes

    +
    + Attribute + + Description +
    connectTimeout + Specifies the timeout, in milliseconds, to use when attempting a TCP connection + to the suspect node. Default is 1000. +
    performSendTest + If true is set, send a test message to the suspect node. Default is true. +
    performReadTest + If true is set, read the response of the test message that sent. Default is false. + Note: if performSendTest is false, this attribute will have no effect. +
    readTestTimeout + Specifies the timeout, in milliseconds, to use when performing a read test + to the suspicious node. Default is 5000. +
    removeSuspectsTimeout + The maximum time(in seconds) for remove from removeSuspects. Member of + removeSuspects will be automatically removed after removeSuspectsTimeout. + If a negative value specified, the removeSuspects members never be + removed until disappeared really. If the attribute is not provided, + a default of 300 seconds (5 minutes) is used. +
    +
    +

    org.apache.catalina.tribes.group.interceptors.TcpPingInterceptor Attributes

    +
    + Attribute + + Description +
    interval + If useThread == true, defines the interval of sending a ping message. + default is 1000 ms. +
    useThread + Flag of whether to start a thread for sending a ping message. + If set to true, this interceptor will start a local thread for sending a ping message. + if set to false, channel heartbeat will send a ping message. + default is false. +
    +
    +

    org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor Attributes

    +
    + Attribute + + Description +
    interval + Defines the interval in number of messages when we are to report the throughput statistics. + The report is logged to the org.apache.juli.logging.LogFactory.getLog(ThroughputInterceptor.class) + logger under the INFO level. + Default value is to report every 10000 messages. +
    +
    +

    org.apache.catalina.tribes.group.interceptors.EncryptInterceptor Attributes

    +

    + The EncryptInterceptor adds encryption to the channel messages carrying + session data between nodes. Added in Tomcat 9.0.13. +

    +

    + If using the TcpFailureDetector, the EncryptInterceptor + must be inserted into the interceptor chain before the + TcpFailureDetector. This is becuase when validating cluster + members, TcpFailureDetector writes channel data directly + to the other members without using the remainder of the interceptor chain, + but on the receiving side, the message still goes through the chain (in reverse). + Because of this asymmetry, the EncryptInterceptor must execute + before the TcpFailureDetector on the sender and after + it on the receiver, otherwise message corruption will occur. +

    +
    + Attribute + + Description +
    encryptionAlgorithm + The encryption algorithm to be used, including the mode and padding. Please see + https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html + for the standard JCA names that can be used. + + EncryptInterceptor currently supports the following + block-cipher modes: + CBC, OFB, CFB, and GCM. + + The length of the key will specify the flavor of the encryption algorithm + to be used, if applicable (e.g. AES-128 versus AES-256). + + The default algorithm is AES/CBC/PKCS5Padding. +
    encryptionKey + The key to be used with the encryption algorithm. + + The key should be specified as hex-encoded bytes of the appropriate + length for the algorithm (e.g. 16 bytes / 32 characters / 128 bits for + AES-128, 32 bytes / 64 characters / 256 bits for AES-256, etc.). +
    +
    +

    Nested Components

    + +

    StaticMember Attributes

    +

    LocalMember:
    + Static member that is the local member of the static cluster group. +

    +
    + Attribute + + Description +
    className + Only one implementation available:org.apache.catalina.tribes.membership.StaticMember +
    port + There is no need to set. + The value of this attribute inherits from the cluster receiver setting. +
    securePort + There is no need to set. + The value of this attribute inherits from the cluster receiver setting. +
    host + There is no need to set. + The value of this attribute inherits from the cluster receiver setting. +
    domain + The logical cluster domain for that this static member listens for cluster messages. + Two different type of values are possible:
    + 1. Regular string values like "staging-domain" or "tomcat-cluster" will be converted into bytes + using ISO-8859-1 encoding. + 2. byte array in string form, for example {216,123,12,3}
    +
    uniqueId + A universally uniqueId for this static member. + The values must be 16 bytes in the following form:
    + 1. byte array in string form, for example {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}
    +
    + +

    Member:
    + Static member that add to the static cluster group. +

    +
    + Attribute + + Description +
    className + Only one implementation available:org.apache.catalina.tribes.membership.StaticMember +
    port + The port that this static member listens to for cluster messages +
    securePort + The secure port this static member listens to for encrypted cluster messages + default value is -1, this value means the member is not listening on a secure port +
    host + The host (or network interface) that this static member listens for cluster messages. + Three different type of values are possible:
    + 1. IP address in the form of "216.123.1.23"
    + 2. Hostnames like "tomcat01.mydomain.com" or "tomcat01" as long as they resolve correctly
    + 3. byte array in string form, for example {216,123,12,3}
    +
    domain + The logical cluster domain for that this static member listens for cluster messages. + Two different type of values are possible:
    + 1. Regular string values like "staging-domain" or "tomcat-cluster" will be converted into bytes + using ISO-8859-1 encoding.
    + 2. byte array in string form, for example {216,123,12,3}
    +
    uniqueId + A universally uniqueId for this static member. + The values must be 16 bytes in the following form:
    + 1. byte array in string form, for example {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}
    +
    +
    + + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/cluster-listener.html b/tomcat/docs/config/cluster-listener.html new file mode 100644 index 0000000..2887991 --- /dev/null +++ b/tomcat/docs/config/cluster-listener.html @@ -0,0 +1,77 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - The ClusterListener object

    The ClusterListener object

    Table of Contents

    Introduction

    +

    + The org.apache.catalina.ha.ClusterListener base class + lets you listen in on messages that are received by the Cluster component. +

    + +

    org.apache.catalina.ha.session.ClusterSessionListener

    +

    + When using the DeltaManager, the messages are received by the Cluster object and are propagated to the + to the manager through this listener. +

    +

    Attributes

    + +

    Common Attributes

    + +
    + Attribute + + Description +
    className + +
    + + +
    + + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/cluster-manager.html b/tomcat/docs/config/cluster-manager.html new file mode 100644 index 0000000..e622c50 --- /dev/null +++ b/tomcat/docs/config/cluster-manager.html @@ -0,0 +1,283 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - The ClusterManager object

    The ClusterManager object

    Table of Contents

    Introduction

    +

    A cluster manager is an extension to Tomcat's session manager interface, + org.apache.catalina.Manager. + A cluster manager must implement the + org.apache.catalina.ha.ClusterManager and is solely responsible + for how the session is replicated.
    + There are currently two different managers, the + org.apache.catalina.ha.session.DeltaManager replicates deltas of + session data to all members in the cluster. This implementation is proven and + works very well, but has a limitation as it requires the cluster members to be + homogeneous, all nodes must deploy the same applications and be exact + replicas. The org.apache.catalina.ha.session.BackupManager also + replicates deltas but only to one backup node. The location of the backup node + is known to all nodes in the cluster. It also supports heterogeneous + deployments, so the manager knows at what locations the web application is + deployed.

    +

    The <Manager>

    +

    The <Manager> element defined inside the + <Cluster> element is the template defined for all web + applications that are marked <distributable/> in their + web.xml file. However, you can still override the manager + implementation on a per web application basis, by putting the + <Manager> inside the <Context> element + either in the context.xml file or the + server.xml file.

    +

    Attributes

    +

    Common Attributes

    +
    + Attribute + + Description +
    className +
    name + The name of this cluster manager, the name is used to identify a + session manager on a node. The name might get modified by the + Cluster element to make it unique in the container. +
    notifyListenersOnReplication + Set to true if you wish to have session listeners notified + when session attributes are being replicated or removed across Tomcat + nodes in the cluster. +
    processExpiresFrequency +

    Frequency of the session expiration, and related manager operations. + Manager operations will be done once for the specified amount of + backgroundProcess calls (i.e., the lower the amount, the more often the + checks will occur). The minimum value is 1, and the default value is 6. +

    +
    secureRandomClass +

    Name of the Java class that extends + java.security.SecureRandom to use to generate session IDs. + If not specified, the default value is + java.security.SecureRandom.

    +
    secureRandomProvider +

    Name of the provider to use to create the + java.security.SecureRandom instances that generate session + IDs. If an invalid algorithm and/or provider is specified, the Manager + will use the platform default provider and the default algorithm. If not + specified, the platform default provider will be used.

    +
    secureRandomAlgorithm +

    Name of the algorithm to use to create the + java.security.SecureRandom instances that generate session + IDs. If an invalid algorithm and/or provider is specified, the Manager + will use the platform default provider and the default algorithm. If not + specified, the default algorithm of SHA1PRNG will be used. If the + default algorithm is not supported, the platform default will be used. + To specify that the platform default should be used, do not set the + secureRandomProvider attribute and set this attribute to the empty + string.

    +
    recordAllActions +

    Flag whether send all actions for session across Tomcat cluster + nodes. If set to false, if already done something to the same attribute, + make sure don't send multiple actions across Tomcat cluster nodes. + In that case, sends only the actions that have been added at last. + Default is false.

    +
    +
    +

    org.apache.catalina.ha.session.DeltaManager Attributes

    +
    + Attribute + + Description +
    expireSessionsOnShutdown + When a web application is being shutdown, Tomcat issues an expire call + to each session to notify all the listeners. If you wish for all + sessions to expire on all nodes when a shutdown occurs on one node, set + this value to true. + Default value is false. +
    maxActiveSessions + The maximum number of active sessions that will be created by this + Manager, or -1 (the default) for no limit. For this manager, all + sessions are counted as active sessions irrespective if whether or not + the current node is the primary node for the session. +
    notifySessionListenersOnReplication + Set to true if you wish to have session listeners notified + when sessions are created and expired across Tomcat nodes in the + cluster. +
    notifyContainerListenersOnReplication + Set to true if you wish to have container listeners notified + across Tomcat nodes in the cluster. +
    stateTransferTimeout + The time in seconds to wait for a session state transfer to complete + from another node when a node is starting up. + Default value is 60 seconds. +
    sendAllSessions + Flag whether send sessions as split blocks. + If set to true, send all sessions as one big block. + If set to false, send sessions as split blocks. + Default value is true. +
    sendAllSessionsSize + The number of sessions in a session block message. This value is + effective only when sendAllSessions is false. + Default is 1000. +
    sendAllSessionsWaitTime + Wait time between sending of session block messages. This value is + effective only when sendAllSessions is false. + Default is 2000 milliseconds. +
    sessionAttributeNameFilter +

    A regular expression used to filter which session attributes will be + replicated. An attribute will only be replicated if its name matches + this pattern. If the pattern is zero length or null, all + attributes are eligible for replication. The pattern is anchored so the + session attribute name must fully match the pattern. As an example, the + value (userName|sessionHistory) will only replicate the + two session attributes named userName and + sessionHistory. If not specified, the default value of + null will be used.

    +
    sessionAttributeValueClassNameFilter +

    A regular expression used to filter which session attributes will be + replicated. An attribute will only be replicated if the implementation + class name of the value matches this pattern. If the pattern is zero + length or null, all attributes are eligible for + replication. The pattern is anchored so the fully qualified class name + must fully match the pattern. If not specified, the default value of + null will be used unless a SecurityManager is + enabled in which case the default will be + java\\.lang\\.(?:Boolean|Integer|Long|Number|String).

    +
    stateTimestampDrop + When this node sends a GET_ALL_SESSIONS message to other + node, all session messages that are received as a response are queued. + If this attribute is set to true, the received session + messages (except any GET_ALL_SESSIONS sent by other nodes) + are filtered by their timestamp. A message is dropped if it is not a + GET_ALL_SESSIONS message and its timestamp is earlier than + the timestamp of our GET_ALL_SESSIONS message. + If set to false, all queued session messages are handled. + Default is true. +
    warnOnSessionAttributeFilterFailure +

    If sessionAttributeNameFilter or + sessionAttributeValueClassNameFilter blocks an + attribute, should this be logged at WARN level? If + WARN level logging is disabled then it will be logged at + DEBUG. The default value of this attribute is + false unless a SecurityManager is enabled in + which case the default will be true.

    +
    +
    +

    org.apache.catalina.ha.session.BackupManager Attributes

    +
    + Attribute + + Description +
    mapSendOptions + The backup manager uses a replicated map, this map is sending and + receiving messages. You can setup the flag for how this map is sending + messages, the default value is 6(synchronous).
    + Note that if you use asynchronous messaging it is possible for update + messages for a session to be processed by the receiving node in a + different order to the order in which they were sent. +
    maxActiveSessions + The maximum number of active sessions that will be created by this + Manager, or -1 (the default) for no limit. For this manager, only + sessions where the current node is the primary node for the session are + considered active sessions. +
    rpcTimeout + Timeout for RPC message used for broadcast and transfer state from + another map. + Default value is 15000 milliseconds. +
    sessionAttributeNameFilter +

    A regular expression used to filter which session attributes will be + replicated. An attribute will only be replicated if its name matches + this pattern. If the pattern is zero length or null, all + attributes are eligible for replication. The pattern is anchored so the + session attribute name must fully match the pattern. As an example, the + value (userName|sessionHistory) will only replicate the + two session attributes named userName and + sessionHistory. If not specified, the default value of + null will be used.

    +
    sessionAttributeValueClassNameFilter +

    A regular expression used to filter which session attributes will be + replicated. An attribute will only be replicated if the implementation + class name of the value matches this pattern. If the pattern is zero + length or null, all attributes are eligible for + replication. The pattern is anchored so the fully qualified class name + must fully match the pattern. If not specified, the default value of + null will be used unless a SecurityManager is + enabled in which case the default will be + java\\.lang\\.(?:Boolean|Integer|Long|Number|String).

    +
    terminateOnStartFailure + Set to true if you wish to terminate replication map when replication + map fails to start. If replication map is terminated, associated context + will fail to start. If you set this attribute to false, replication map + does not end. It will try to join the map membership in the heartbeat. + Default value is false . +
    warnOnSessionAttributeFilterFailure +

    If sessionAttributeNameFilter or + sessionAttributeValueClassNameFilter blocks an + attribute, should this be logged at WARN level? If + WARN level logging is disabled then it will be logged at + DEBUG. The default value of this attribute is + false unless a SecurityManager is enabled in + which case the default will be true.

    +
    accessTimeout + The timeout for a ping message. If a remote map does not respond within + this timeout period, its regarded as disappeared. + Default value is 5000 milliseconds. +
    +
    +

    Nested Components

    +

    All Manager Implementations

    +

    All Manager implementations allow nesting of a + <SessionIdGenerator> element. It defines + the behavior of session id generation. All implementations + of the SessionIdGenerator allow the + following attributes: +

    +
    + Attribute + + Description +
    sessionIdLength +

    The length of the session ID may be changed with the + sessionIdLength attribute. +

    +
    +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/cluster-membership.html b/tomcat/docs/config/cluster-membership.html new file mode 100644 index 0000000..c9a316b --- /dev/null +++ b/tomcat/docs/config/cluster-membership.html @@ -0,0 +1,161 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - The Cluster Membership object

    The Cluster Membership object

    Table of Contents

    Introduction

    +

    + The membership component in the Apache Tribes Channel is responsible + for dynamic discovery of other members(nodes) in the cluster. +

    +

    Default Implementation

    +

    + The default implementation of the cluster group notification is built on top of multicast heartbeats + sent using UDP packets to a multicast IP address. + Cluster members are grouped together by using the same multicast address/port combination. + Each member sends out a heartbeat with a given interval (frequency), and this + heartbeat is used for dynamic discovery. + In a similar fashion, if a heartbeat has not been received in a timeframe specified by dropTime + ms. a member is considered suspect and the channel and any membership listener will be notified. +

    +

    Attributes

    + +

    Multicast Attributes

    + +
    + Attribute + + Description +
    className +

    + The default value is org.apache.catalina.tribes.membership.McastService + and is currently the only implementation. + This implementation uses multicast heartbeats for member discovery. +

    +
    address +

    + The multicast address that the membership will broadcast its presence and listen + for other heartbeats on. The default value is 228.0.0.4 + Make sure your network is enabled for multicast traffic.
    + The multicast address, in conjunction with the port is what + creates a cluster group. To divide up your farm into several different group, or to + split up QA from production, change the port or the address +
    Previously known as mcastAddr. +

    +
    port +

    + The multicast port, the default value is 45564
    + The multicast port, in conjunction with the address is what + creates a cluster group. To divide up your farm into several different group, or to + split up QA from production, change the port or the address +

    +
    frequency +

    + The frequency in milliseconds in which heartbeats are sent out. The default value is 500 ms.
    + In most cases the default value is sufficient. Changing this value, simply changes the interval in between heartbeats. +

    +
    dropTime +

    + The membership component will time out members and notify the Channel if a member fails to send a heartbeat within + a give time. The default value is 3000 ms. This means, that if a heartbeat is not received from a + member in that timeframe, the membership component will notify the cluster of this.
    + On a high latency network you may wish to increase this value, to protect against false positives.
    + Apache Tribes also provides a TcpFailureDetector that will + verify a timeout using a TCP connection when a heartbeat timeout has occurred. This protects against false positives. +

    +
    bind +

    + Use this attribute if you wish to bind your multicast traffic to a specific network interface. + By default, or when this attribute is unset, it tries to bind to 0.0.0.0 and sometimes on multihomed hosts + this becomes a problem. +

    +
    ttl +

    + The time-to-live setting for the multicast heartbeats. + This setting should be a value between 0 and 255. The default value is VM implementation specific. +

    +
    domain +

    + Apache Tribes has the ability to logically group members into domains, by using this domain attribute. + The org.apache.catalina.tribes.Member.getDomain() method returns the value specified here. +

    +
    soTimeout +

    + The sending and receiving of heartbeats is done on a single thread, hence to avoid blocking this thread forever, + you can control the SO_TIMEOUT value on this socket.
    + If a value smaller or equal to 0 is presented, the code will default this value to frequency +

    +
    recoveryEnabled +

    + In case of a network failure, Java multicast socket don't transparently fail over, instead the socket will continuously + throw IOException upon each receive request. When recoveryEnabled is set to true, this will close the multicast socket + and open a new socket with the same properties as defined above.
    + The default is true.
    +

    +
    recoveryCounter +

    + When recoveryEnabled==true this value indicates how many + times an error has to occur before recovery is attempted. The default is + 10.
    +

    +
    recoverySleepTime +

    + When recoveryEnabled==true this value indicates how long time (in milliseconds) + the system will sleep in between recovery attempts, until it recovers successfully. + The default is 5000 (5 seconds).
    +

    +
    localLoopbackDisabled +

    + Membership uses multicast, it will call java.net.MulticastSocket.setLoopbackMode(localLoopbackDisabled). + When localLoopbackDisabled==true multicast messages will not reach other nodes on the same local machine. + The default is false.
    +

    +
    + +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/cluster-receiver.html b/tomcat/docs/config/cluster-receiver.html new file mode 100644 index 0000000..23a0e1f --- /dev/null +++ b/tomcat/docs/config/cluster-receiver.html @@ -0,0 +1,159 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - The Cluster Receiver object

    The Cluster Receiver object

    Table of Contents

    Introduction

    +

    + The receiver component is responsible for receiving cluster messages. + As you might notice through the configuration, is that the receiving of messages + and sending of messages are two different components, this is different from many other + frameworks, but there is a good reason for it, to decouple the logic for how messages are sent from + how messages are received.
    + The receiver is very much like the Tomcat Connector, its the base of the thread pool + for incoming cluster messages. The receiver is straight forward, but all the socket settings + for incoming traffic are managed here. +

    +

    Blocking vs Non-Blocking Receiver

    +

    + The receiver supports both a non blocking, org.apache.catalina.tribes.transport.nio.NioReceiver, and a + blocking, org.apache.catalina.tribes.transport.bio.BioReceiver. It is preferred to use the non blocking receiver + to be able to grow your cluster without running into thread starvation.
    + Using the non blocking receiver allows you to with a very limited thread count to serve a large number of messages. + Usually the rule is to use 1 thread per node in the cluster for small clusters, and then depending on your message frequency + and your hardware, you'll find an optimal number of threads peak out at a certain number. +

    +

    Attributes

    +

    Common Attributes

    +
    + Attribute + + Description +
    className + The implementation of the receiver component. Two implementations available, + org.apache.catalina.tribes.transport.nio.NioReceiver and + org.apache.catalina.tribes.transport.bio.BioReceiver.
    + The org.apache.catalina.tribes.transport.nio.NioReceiver is the + preferred implementation +
    address + The address (network interface) to listen for incoming traffic. + Same as the bind address. The default value is auto and translates to + java.net.InetAddress.getLocalHost().getHostAddress(). +
    direct + Possible values are true or false. + Set to true if you want the receiver to use direct bytebuffers when reading data + from the sockets. +
    port + The listen port for incoming data. The default value is 4000. + To avoid port conflicts the receiver will automatically bind to a free port within the range of + port <= bindPort < port+autoBind + So for example, if port is 4000, and autoBind is set to 10, then the receiver will open up + a server socket on the first available port in the range 4000-4009. +
    autoBind + Default value is 100. + Use this value if you wish to automatically avoid port conflicts the cluster receiver will try to open a + server socket on the port attribute port, and then work up autoBind number of times. +
    securePort + The secure listen port. This port is SSL enabled. If this attribute is omitted no SSL port is opened up. + There default value is unset, meaning there is no SSL socket available. +
    udpPort + The UDP listen port. If this attribute is omitted no UDP port is opened up. + There default value is unset, meaning there is no UDP listener available. +
    selectorTimeout + The value in milliseconds for the polling timeout in the NioReceiver. On older versions of the JDK + there have been bugs, that should all now be cleared out where the selector never woke up. + The default value is a very high 5000 milliseconds. +
    maxThreads + The maximum number of threads in the receiver thread pool. The default value is 6 + Adjust this value relative to the number of nodes in the cluster, the number of messages being exchanged and + the hardware you are running on. A higher value doesn't mean more efficiency, tune this value according to your + own test results. +
    minThreads + Minimum number of threads to be created when the receiver is started up. Default value is 6 +
    maxIdleTime + Maximum number of milliseconds of until Idle thread terminates. Default value is 60000 milliseconds. +
    ooBInline + Boolean value for the socket OOBINLINE option. Possible values are true or false. +
    rxBufSize + The receiver buffer size on the receiving sockets. Value is in bytes, the default value is 43800 bytes. +
    txBufSize + The sending buffer size on the receiving sockets. Value is in bytes, the default value is 25188 bytes. +
    udpRxBufSize + The receive buffer size on the datagram socket. + Default value is 25188 bytes. +
    udpTxBufSize + The send buffer size on the datagram socket. + Default value is 43800 bytes. +
    soKeepAlive + Boolean value for the socket SO_KEEPALIVE option. Possible values are true or false. +
    soLingerOn + Boolean value to determine whether to use the SO_LINGER socket option. + Possible values are true or false. Default value is true. +
    soLingerTime + Sets the SO_LINGER socket option time value. The value is in seconds. + The default value is 3 seconds. +
    soReuseAddress + Boolean value for the socket SO_REUSEADDR option. Possible values are true or false. +
    tcpNoDelay + Boolean value for the socket TCP_NODELAY option. Possible values are true or false. + The default value is true +
    timeout + Sets the SO_TIMEOUT option on the socket. The value is in milliseconds and the default value is 3000 + milliseconds. +
    useBufferPool + Boolean value whether to use a shared buffer pool of cached org.apache.catalina.tribes.io.XByteBuffer + objects. If set to true, the XByteBuffer that is used to pass a message up the channel, will be recycled at the end + of the requests. This means that interceptors in the channel must not maintain a reference to the object + after the org.apache.catalina.tribes.ChannelInterceptor#messageReceived method has exited. +
    +
    +

    NioReceiver

    +
    +

    BioReceiver

    +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/cluster-sender.html b/tomcat/docs/config/cluster-sender.html new file mode 100644 index 0000000..73ab500 --- /dev/null +++ b/tomcat/docs/config/cluster-sender.html @@ -0,0 +1,175 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - The Cluster Sender object

    The Cluster Sender object

    Table of Contents

    Introduction

    +

    + The channel sender component is responsible for delivering outgoing cluster messages over the network. + In the default implementation, org.apache.catalina.tribes.transport.ReplicationTransmitter, + the sender is a fairly empty shell with not much logic around a fairly complex <Transport> + component the implements the actual delivery mechanism. +

    +

    Concurrent Parallel Delivery

    +

    + In the default transport implementation, org.apache.catalina.tribes.transport.nio.PooledParallelSender, + Apache Tribes implements what we like to call "Concurrent Parallel Delivery". + This means that we can send a message to more than one destination at the same time(parallel), and + deliver two messages to the same destination at the same time(concurrent). Combine these two and we have + "Concurrent Parallel Delivery". +

    +

    + When is this useful? The simplest example we can think of is when part of your code is sending a 10MB message, + like a war file being deployed, and you need to push through a small 10KB message, say a session being replicated, + you don't have to wait for the 10MB message to finish, as a separate thread will push in the small message + transmission at the same time. Currently there is no interrupt, pause or priority mechanism available, but check back soon. +

    +

    Nested Elements

    +

    + The nested element <Transport> is not required, but encouraged, as this is where + you would set all the socket options for the outgoing messages. Please see its attributes below. + There are two implementations, in a similar manner to the receiver, one is non-blocking + based and the other is built using blocking IO.
    + org.apache.catalina.tribes.transport.bio.PooledMultiSender is the blocking implementation and + org.apache.catalina.tribes.transport.nio.PooledParallelSender. + Parallel delivery is not available for the blocking implementation due to the fact that it is blocking a thread on sending data. +

    +

    Attributes

    +

    Common Sender Attributes

    +
    + Attribute + + Description +
    className + Required, only available implementation is org.apache.catalina.tribes.transport.ReplicationTransmitter +
    +
    +

    Common Transport Attributes

    +
    + Attribute + + Description +
    className + Required, an implementation of the org.apache.catalina.tribes.transport.MultiPointSender.
    + Non-blocking implementation is org.apache.catalina.tribes.transport.nio.PooledParallelSender
    + Blocking implementation is org.apache.catalina.tribes.transport.bio.PooledMultiSender +
    rxBufSize + The receive buffer size on the socket. + Default value is 25188 bytes. +
    txBufSize + The send buffer size on the socket. + Default value is 43800 bytes. +
    udpRxBufSize + The receive buffer size on the datagram socket. + Default value is 25188 bytes. +
    udpTxBufSize + The send buffer size on the datagram socket. + Default value is 43800 bytes. +
    directBuffer + Possible values are true or false. + Set to true if you want the receiver to use direct bytebuffers when writing data + to the sockets. Default value is false +
    keepAliveCount + The number of requests that can go through the socket before the socket is closed, and reopened + for the next request. The default value is -1, which is unlimited. +
    keepAliveTime + The number of milliseconds a connection is kept open after its been opened. + The default value is -1, which is unlimited. +
    timeout + Sets the SO_TIMEOUT option on the socket. The value is in milliseconds and the default value is 3000 + milliseconds.(3 seconds) This timeout starts when a message send attempt is starting, until the transfer has been completed. + For the NIO sockets, this will mean, that the caller can guarantee that we will not attempt sending the message + longer than this timeout value. For the blocking IO implementation, this translated directly to the soTimeout.
    + A timeout will not spawn a retry attempt, in order to guarantee the return of the application thread. +
    maxRetryAttempts + How many times do we retry a failed message, that received a IOException at the socket level. + The default value is 1, meaning we will retry a message that has failed once. + In other words, we will attempt a message send no more than twice. One is the original send, and one is the + maxRetryAttempts. +
    ooBInline + Boolean value for the socket OOBINLINE option. Possible values are true or false. +
    soKeepAlive + Boolean value for the socket SO_KEEPALIVE option. Possible values are true or false. +
    soLingerOn + Boolean value to determine whether to use the SO_LINGER socket option. + Possible values are true or false. Default value is true. +
    soLingerTime + Sets the SO_LINGER socket option time value. The value is in seconds. + The default value is 3 seconds. +
    soReuseAddress + Boolean value for the socket SO_REUSEADDR option. Possible values are true or false. +
    soTrafficClass + Sets the traffic class level for the socket, the value is between 0 and 255. + Default value is int soTrafficClass = 0x04 | 0x08 | 0x010; + Different values are defined in + java.net.Socket#setTrafficClass(int). +
    tcpNoDelay + Boolean value for the socket TCP_NODELAY option. Possible values are true or false. + The default value is true +
    throwOnFailedAck + Boolean value, default value is true. + If set to true, the sender will throw a org.apache.catalina.tribes.RemoteProcessException + when we receive a negative ack from the remote member. + Set to false, and Tribes will treat a positive ack the same way as a negative ack, that the message was received. +
    +
    +

    Common PooledSender Attributes

    +
    + Attribute + + Description +
    poolSize + The maximum number of concurrent connections from A to B. + The value is based on a per-destination count. + The default value is 25 +
    maxWait + The maximum number of milliseconds that the senderPool will wait when + there are no available senders. The default value is 3000 + milliseconds.(3 seconds). +
    +
    +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/cluster-valve.html b/tomcat/docs/config/cluster-valve.html new file mode 100644 index 0000000..9d7a140 --- /dev/null +++ b/tomcat/docs/config/cluster-valve.html @@ -0,0 +1,168 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - The Cluster Valve object

    The Cluster Valve object

    Table of Contents

    Introduction

    +

    + A cluster valve is no different from any other Tomcat Valve. + The cluster valves are interceptors in the invocation chain for HTTP requests, and the clustering implementation + uses these valves to make intelligent decision around data and when data should be replicated. +

    +

    + A cluster valve must implement the org.apache.catalina.ha.ClusterValve interface. + This is a simple interface that extends the org.apache.catalina.Valve interface. +

    +

    org.apache.catalina.ha.tcp.ReplicationValve

    + The ReplicationValve will notify the cluster at the end of a HTTP request + so that the cluster can make a decision whether there is data to be replicated or not. +

    Attributes

    +
    + Attribute + + Description +
    className + Set value to org.apache.catalina.ha.tcp.ReplicationValve +
    filter + For known file extensions or urls, you can use this Valve to notify the + cluster that the session has not been modified during this request and + the cluster doesn't have to probe the session managers for changes. If + the request matches this filter pattern, the cluster assumes there has + been no session change. An example filter would look like + filter=".*\.gif|.*\.js|.*\.jpeg|.*\.jpg|.*\.png|.*\.htm|.*\.html|.*\.css|.*\.txt" + . The filter is a regular expression using + java.util.regex. +
    primaryIndicator + Boolean value, so to true, and the replication valve will insert a request attribute with the name + defined by the primaryIndicatorName attribute. + The value inserted into the request attribute is either Boolean.TRUE or + Boolean.FALSE +
    primaryIndicatorName + Default value is org.apache.catalina.ha.tcp.isPrimarySession + The value defined here is the name of the request attribute that contains the boolean value + if the session is primary on this server or not. +
    statistics + Boolean value. Set to true if you want the valve to collect request statistics. + Default value is false +
    +
    +

    org.apache.catalina.ha.session.JvmRouteBinderValve

    + In case of a mod_jk failover, the JvmRouteBinderValve will replace the + jvmWorker attribute in the session Id, to make future requests stick to this + node. If you want fallback capability, don't enable this valve, but if you want your failover to stick, + and for mod_jk not to have to keep probing the node that went down, you use this valve. +

    Attributes

    +
    + Attribute + + Description +
    className + org.apache.catalina.ha.session.JvmRouteBinderValve +
    enabled + Default value is true + Runtime attribute to turn on and off turn over of the session's jvmRoute value. +
    sessionIdAttribute + Old sessionid before failover is registered in request attributes with this attribute. + Default attribute name is org.apache.catalina.ha.session.JvmRouteOrignalSessionID. +
    +
    +

    org.apache.catalina.ha.authenticator.ClusterSingleSignOn

    + The ClusterSingleSignOn supports feature of single sign on in cluster. + By using ClusterSingleSignOn, the security identity authenticated + by one web application is recognized by other web applications on the same virtual host, + and it is propagated to other nodes in the cluster. + +

    See the Single Sign On special + feature on the Host element for more information.

    + +

    Note: ClusterSingleSignOn can be configured at host level cluster only. +

    + +

    Attributes

    +
    + Attribute + + Description +
    className +

    Java class name of the implementation to use. This MUST be set to + org.apache.catalina.ha.authenticator.ClusterSingleSignOn.

    +
    cookieDomain +

    Sets the host domain to be used for sso cookies.

    +
    mapSendOptions +

    The Valve uses a replicated map. You can setup the flag for how this + map sends messages. The default value is 6 (synchronous). + Note that if you use asynchronous messaging it is possible for update + messages to be processed by the receiving node in a different order to + the order in which they were sent.

    +
    requireReauthentication +

    Default false. Flag to determine whether each request needs to be + reauthenticated to the security Realm. If "true", this + Valve uses cached security credentials (username and password) to + reauthenticate to the Realm each request associated + with an SSO session. If "false", the Valve can itself authenticate + requests based on the presence of a valid SSO cookie, without + rechecking with the Realm.

    +
    rpcTimeout +

    The Valve uses a replicated map. This is the timeout for messages + that transfer state to/from the other nodes in the cluster. If not + specified, a default value of 15000 milliseconds is used. +

    +
    terminateOnStartFailure +

    Set to true if you wish this Valve to fail if the + underlying replication fails to start. If the Valve fails, then the + associated container will fail to start. If you set this attribute to + false, and the underlying replications fails to start, the Valve will + start and it will attempt to join the cluster and start replication as + part of the heartbeat process. If not specified, the default value of + false is used.

    +
    accessTimeout + The timeout for a ping message. If a remote map does not respond within + this timeout period, its regarded as disappeared. + Default value is 5000 milliseconds. +
    +
    +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/cluster.html b/tomcat/docs/config/cluster.html new file mode 100644 index 0000000..5b3081c --- /dev/null +++ b/tomcat/docs/config/cluster.html @@ -0,0 +1,176 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - The Cluster object

    The Cluster object

    Table of Contents

    Introduction

    +

    + The tomcat cluster implementation provides session replication, context attribute replication and + cluster wide WAR file deployment. + While the Cluster configuration is fairly complex, the default configuration will work + for most people out of the box.

    + The Tomcat Cluster implementation is very extensible, and hence we have exposed a myriad of options, + making the configuration seem like a lot, but don't lose faith, instead you have a tremendous control + over what is going on.

    +

    Security

    + +

    The cluster implementation is written on the basis that a secure, trusted +network is used for all of the cluster related network traffic. It is not safe +to run a cluster on a insecure, untrusted network.

    + +

    There are many options for providing a secure, trusted network for use by a +Tomcat cluster. These include:

    +
      +
    • private LAN
    • +
    • a Virtual Private Network (VPN)
    • +
    • IPSEC
    • +
    + +

    Engine vs Host placement

    +

    + You can place the <Cluster> element inside either the <Engine> + container or the <Host> container.
    + Placing it in the engine, means that you will support clustering in all virtual hosts of Tomcat, + and share the messaging component. When you place the <Cluster> inside the <Engine> + element, the cluster will append the host name of each session manager to the managers name so that two contexts with + the same name but sitting inside two different hosts will be distinguishable. +

    +

    Context Attribute Replication

    +

    To configure context attribute replication, simply do this by swapping out the context implementation + used for your application context.

    +
    <Context className="org.apache.catalina.ha.context.ReplicatedContext"/>
    +

    + This context extends the Tomcat StandardContext + so all the options from the base implementation are valid. +

    +

    Nested Components

    +

    Manager:
    + The session manager element identifies what kind of session manager is used in this cluster implementation. + This manager configuration is identical to the one you would use in a regular <Context> configuration. +
    The default value is the org.apache.catalina.ha.session.DeltaManager that is closely coupled with + the SimpleTcpCluster implementation. Other managers like the org.apache.catalina.ha.session.BackupManager + are/could be loosely coupled and don't rely on the SimpleTcpCluster for its data replication. +

    +

    Channel:
    + The Channel and its sub components are all part of the IO layer + for the cluster group, and is a module in it's own that we have nick named "Tribes" +
    + Any configuring and tuning of the network layer, the messaging and the membership logic + will be done in the channel and its nested components. + You can always find out more about Apache Tribes +

    +

    Valve:
    + The Tomcat Cluster implementation uses Tomcat Valves to + track when requests enter and exit the servlet container. It uses these valves to be able to make + intelligent decisions on when to replicate data, which is always at the end of a request. +

    +

    Deployer:
    + The Deployer component is the Tomcat Farm Deployer. It allows you to deploy and undeploy applications + cluster wide. +

    +

    ClusterListener:
    + ClusterListener's are used to track messages sent and received using the SimpleTcpCluster. + If you wish to track messages, you can add a listener here, or you can add a valve to the channel object. +

    +

    Deprecated configuration options

    +

    + Deprecated settings: In the previous version of Tomcat you were able to control session + manager settings using manager.<property>=value. + This has been discontinued, as the way it was written interferes with + the ability to support multiple different manager classes under one cluster implementation, + as the same properties might have the different effect on different managers. +

    +

    Attributes

    +

    SimpleTcpCluster Attributes

    +
    + Attribute + + Description +
    className +

    The main cluster class, currently only one is available, + org.apache.catalina.ha.tcp.SimpleTcpCluster +

    +
    channelSendOptions +

    The Tribes channel send options, default is 8.
    + This option is used to set the flag that all messages sent through the + SimpleTcpCluster uses. The flag decides how the messages are sent, and is a simple logical OR.

    + +
    int options = Channel.SEND_OPTIONS_ASYNCHRONOUS |
    +              Channel.SEND_OPTIONS_SYNCHRONIZED_ACK |
    +              Channel.SEND_OPTIONS_USE_ACK;
    +

    Some of the values are:
    + Channel.SEND_OPTIONS_SYNCHRONIZED_ACK = 0x0004
    + Channel.SEND_OPTIONS_ASYNCHRONOUS = 0x0008
    + Channel.SEND_OPTIONS_USE_ACK = 0x0002
    + So to use ACK and ASYNC messaging, the flag would be 10 (8+2) +
    + Note that if you use ASYNC messaging it is possible for update messages + for a session to be processed by the receiving nodes in a different order + to the order in which they were sent.

    +
    channelStartOptions +

    Sets the start and stop flags for the <Channel> object used by the cluster. + The default is Channel.DEFAULT which starts all the channel services, such as + sender, receiver, multicast sender and multicast receiver. + The following flags are available today:

    +
    Channel.DEFAULT = Channel.SND_RX_SEQ (1) |
    +                  Channel.SND_TX_SEQ (2) |
    +                  Channel.MBR_RX_SEQ (4) |
    +                  Channel.MBR_TX_SEQ (8);
    +

    To start a channel without multicasting, you would want to use the value Channel.SND_RX_SEQ | Channel.SND_TX_SEQ + that equals to 3. +

    +
    heartbeatBackgroundEnabled +

    Flag whether invoke channel heartbeat at container background thread. Default value is false. + Enable this flag don't forget to disable the channel heartbeat thread. +

    +
    notifyLifecycleListenerOnFailure +

    Flag whether notify LifecycleListeners if all ClusterListener couldn't accept channel message. + Default value is false. +

    +
    +
    +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/context.html b/tomcat/docs/config/context.html new file mode 100644 index 0000000..0302285 --- /dev/null +++ b/tomcat/docs/config/context.html @@ -0,0 +1,1267 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - The Context Container

    The Context Container

    Table of Contents

    Introduction

    + +

    + The description below uses the variable name $CATALINA_BASE to refer the + base directory against which most relative paths are resolved. If you have + not configured Tomcat for multiple instances by setting a CATALINA_BASE + directory, then $CATALINA_BASE will be set to the value of $CATALINA_HOME, + the directory into which you have installed Tomcat. +

    + +

    The Context element represents a web + application, which is run within a particular virtual host. + Each web application is based on a Web Application Archive + (WAR) file, or a corresponding directory containing the corresponding + unpacked contents, as described in the Servlet Specification (version + 2.2 or later). For more information about web application archives, + you can download the + Servlet + Specification, and review the Tomcat + Application Developer's Guide.

    + +

    The web application used to process each HTTP request is selected + by Catalina based on matching the longest possible prefix of the + Request URI against the context path of each defined Context. + Once selected, that Context will select an appropriate servlet to + process the incoming request, according to the servlet mappings defined + by the web application deployment.

    + +

    You may define as many Context elements as you + wish. Each such Context MUST have a unique context name within a virtual + host. The context path does not need to be unique (see parallel + deployment below). In addition, a Context must be present with a + context path equal to + a zero-length string. This Context becomes the default + web application for this virtual host, and is used to process all + requests that do not match any other Context's context path.

    + +

    Parallel deployment

    +

    You may deploy multiple versions of a web application with the same + context path at the same time. The rules used to match requests to a + context version are as follows: +

    +
      +
    • If no session information is present in the request, use the latest + version.
    • +
    • If session information is present in the request, check the session + manager of each version for a matching session and if one is found, use that + version.
    • +
    • If session information is present in the request but no matching session + can be found, use the latest version.
    • +
    +

    The Host may be configured (via the + undeployOldVersions) to remove old versions deployed in this way + once they are no longer in use.

    +
    + +

    Naming

    +

    When autoDeploy or deployOnStartup operations + are performed by a Host, the name and context path of the web application are + derived from the name(s) of the file(s) that define(s) the web application. + Consequently, the context path may not be defined in a + META-INF/context.xml embedded in the application and there is a + close relationship between the context name, context path, + context version and the base file name (the name minus any + .war or .xml extension) of the file.

    + +

    If no version is specified then the context name is always the + same as the context path. If the context path is the empty + string then the base name will be ROOT (always in upper case) + otherwise the base name will be the context path with the + leading '/' removed and any remaining '/' characters replaced with '#'.

    + +

    If a version is specified then the context path remains unchanged + and both the context name and the base name have the string + '##' appended to them followed by the version identifier.

    + +

    Some examples of these naming conventions are given below.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Context PathContext VersionContext NameBase File NameExample File Names (.xml, .war & directory)
    /fooNone/foofoofoo.xml, foo.war, foo
    /foo/barNone/foo/barfoo#barfoo#bar.xml, foo#bar.war, foo#bar
    Empty StringNoneEmpty StringROOTROOT.xml, ROOT.war, ROOT
    /foo42/foo##42foo##42foo##42.xml, foo##42.war, foo##42
    /foo/bar42/foo/bar##42foo#bar##42foo#bar##42.xml, foo#bar##42.war, foo#bar##42
    Empty String42##42ROOT##42ROOT##42.xml, ROOT##42.war, ROOT##42
    + +

    The version component is treated as a String both for + performance reasons and to allow flexibility in versioning schemes. String + comparisons are used to determine version order. If version is not specified, + it is treated as the empty string. + Therefore, + foo.war will be treated as an earlier version than + foo##11.war and + foo##11.war will be treated as an earlier version than + foo##2.war. If using a purely numerical versioning scheme it is + recommended that zero padding is used so that foo##002.war is + treated as an earlier version than foo##011.war. +

    + +

    If you want to deploy a WAR file or a directory using a context path that + is not related to the base file name then one of the following options must + be used to prevent double-deployment: +

    +
      +
    • Disable autoDeploy and deployOnStartup and define all + Contexts in server.xml
    • +
    • Locate the WAR and/or directory outside of the Host's appBase and use + a context.xml file with a docBase attribute to define it.
    • +
    +
    + +

    Defining a context

    +

    It is NOT recommended to place <Context> elements directly in the + server.xml file. This is because it makes modifying the + Context configuration more invasive since the main + conf/server.xml file cannot be reloaded without restarting + Tomcat. Default Context elements (see below) will also + overwrite the configuration of any <Context> elements + placed directly in server.xml. To prevent this, the override + attribute of the <Context> element defined in server.xml should be set + to true.

    + +

    Individual Context elements may be explicitly defined: +

    +
      +
    • In an individual file at /META-INF/context.xml inside the + application files. Optionally (based on the Host's copyXML attribute) + this may be copied to + $CATALINA_BASE/conf/[enginename]/[hostname]/ and renamed to + application's base file name plus a ".xml" extension.
    • +
    • In individual files (with a ".xml" extension) in the + $CATALINA_BASE/conf/[enginename]/[hostname]/ directory. + The context path and version will be derived from the base name of the file + (the file name less the .xml extension). This file will always take precedence + over any context.xml file packaged in the web application's META-INF + directory.
    • +
    • Inside a Host element in the main + conf/server.xml.
    • +
    + +

    Default Context elements may be defined that apply to + multiple web applications. Configuration for an individual web application + will override anything configured in one of these defaults. Any nested + elements, e.g. <Resource> elements, that are defined in a default + Context will be created once for each + Context to which the default applies. They will not be + shared between Context elements. +

    +
      +
    • In the $CATALINA_BASE/conf/context.xml file: + the Context element information will be loaded by all web applications.
    • +
    • In the + $CATALINA_BASE/conf/[enginename]/[hostname]/context.xml.default + file: the Context element information will be loaded by all web applications + of that host.
    • +
    + +

    With the exception of server.xml, files that define Context + elements may only define a single Context element. +

    + +

    In addition to explicitly specified Context elements, there are + several techniques by which Context elements can be created automatically + for you. See + Automatic Application Deployment and + User Web Applications + for more information.

    + +

    To define multiple contexts that use a single WAR file or directory, + use one of the options described in the Naming + section above for creating a Context that has a path + that is not related to the base file name.

    +
    +

    Attributes

    + +

    Common Attributes

    + +

    All implementations of Context + support the following attributes:

    + +
    + Attribute + + Description +
    allowCasualMultipartParsing +

    Set to true if Tomcat should automatically parse + multipart/form-data request bodies when HttpServletRequest.getPart* + or HttpServletRequest.getParameter* is called, even when the + target servlet isn't marked with the @MultipartConfig annotation + (See Servlet Specification 3.0, Section 3.2 for details). + Note that any setting other than false causes Tomcat + to behave in a way that is not technically spec-compliant. + The default is false

    +
    allowMultipleLeadingForwardSlashInPath +

    Tomcat normalises sequences of multiple / characters in + a URI to a single /. This is for consistencuy with the + behaviour of file systems as URIs are often translated to file system + paths. As a result, the return value of + HttpServletRequest#getContextPath() is expected to start + with multiple / characters for some URIs. This will cause + problems if this value is used directly with + HttpServletResponse#sendRedirect() as redirect paths that + start with // are treated as protocol relative redirects. + To avoid potential issues, Tomcat will collapse multiple leading + / characters at the start of the return value for + HttpServletRequest#getContextPath() to a single + /. This attribute has a default value of false + which enables the collapsing of multiple / characters. To + disable this behaviour, set this attribute to true.

    +
    altDDName +

    The absolute path to the alternative deployment descriptor for this + context. This overrides the default deployment descriptor located at + /WEB-INF/web.xml.

    +
    backgroundProcessorDelay +

    This value represents the delay in seconds between the + invocation of the backgroundProcess method on this context and + its child containers, including all wrappers. + Child containers will not be invoked if their delay value is not + negative (which would mean they are using their own processing + thread). Setting this to a positive value will cause + a thread to be spawn. After waiting the specified amount of time, + the thread will invoke the backgroundProcess method on this host + and all its child containers. A context will use background + processing to perform session expiration and class monitoring for + reloading. If not specified, the default value for this attribute is + -1, which means the context will rely on the background processing + thread of its parent host.

    +
    className +

    Java class name of the implementation to use. This class must + implement the org.apache.catalina.Context interface. + If not specified, the standard value (defined below) will be used.

    +
    containerSciFilter +

    The regular expression that specifies which container provided SCIs + should be filtered out and not used for this context. Matching uses + java.util.regex.Matcher.find() so the regular expression + only has to match a sub-string of the fully qualified class name of the + container provided SCI for it to be filtered out. If not specified, + no filtering will be applied.

    +
    cookies +

    Set to true if you want cookies to be used for + session identifier communication if supported by the client (this + is the default). Set to false if you want to disable + the use of cookies for session identifier communication, and rely + only on URL rewriting by the application.

    +
    createUploadTargets +

    Set to true if Tomcat should attempt to create the + temporary upload location specified in the MultipartConfig + for a Servlet if the location does not already exist. If not specified, + the default value of false will be used.

    +
    crossContext +

    Set to true if you want calls within this application + to ServletContext.getContext() to successfully return a + request dispatcher for other web applications running on this virtual + host. Set to false (the default) in security + conscious environments, to make getContext() always + return null.

    +
    docBase +

    The Document Base (also known as the Context + Root) directory for this web application, or the pathname + to the web application archive file (if this web application is + being executed directly from the WAR file). You may specify + an absolute pathname for this directory or WAR file, or a pathname + that is relative to the appBase directory of the + owning Host.

    +

    The value of this field must not be set unless the Context element is + defined in server.xml or the docBase is not located under + the Host's appBase.

    +

    If a symbolic link is used for docBase then changes to the + symbolic link will only be effective after a Tomcat restart or + by undeploying and redeploying the context. A context reload is not + sufficient.

    +
    dispatchersUseEncodedPaths +

    Controls whether paths used in calls to obtain a request dispatcher + ares expected to be encoded. This affects both how Tomcat handles calls + to obtain a request dispatcher as well as how Tomcat generates paths + used to obtain request dispatchers internally. If not specified, the + default value of true is used.

    +
    failCtxIfServletStartFails +

    Set to true to have the context fail its startup if any + servlet that has load-on-startup >=0 fails its own startup.

    +

    If not specified, the attribute of the same name in the parent Host + configuration is used if specified. Otherwise the default value of + false is used.

    +
    fireRequestListenersOnForwards +

    Set to true to fire any configured + ServletRequestListeners when Tomcat forwards a request. This is + primarily of use to users of CDI frameworks that use + ServletRequestListeners to configure the necessary environment for a + request. If not specified, the default value of false is + used.

    +
    logEffectiveWebXml +

    Set to true if you want the effective web.xml used for a + web application to be logged (at INFO level) when the application + starts. The effective web.xml is the result of combining the + application's web.xml with any defaults configured by Tomcat and any + web-fragment.xml files and annotations discovered. If not specified, the + default value of false is used.

    +
    mapperContextRootRedirectEnabled +

    If enabled, requests for a web application context root will be + redirected (adding a trailing slash) if necessary by the Mapper rather + than the default Servlet. This is more efficient but has the side effect + of confirming that the context path exists. If not specified, the + default value of true is used.

    +
    mapperDirectoryRedirectEnabled +

    If enabled, requests for a web application directory will be + redirected (adding a trailing slash) if necessary by the Mapper rather + than the default Servlet. This is more efficient but has the side effect + of confirming that the directory is exists. If not specified, the + default value of false is used.

    +
    override +

    Set to true to ignore any settings in both the global + or Host default contexts. By default, settings + from a default context will be used but may be overridden by a setting + the same attribute explicitly for the Context.

    +
    path +

    The context path of this web application, which is + matched against the beginning of each request URI to select the + appropriate web application for processing. All of the context paths + within a particular Host must be unique. + If you specify a context path of an empty string (""), you are + defining the default web application for this Host, which + will process all requests not assigned to other Contexts.

    +

    This attribute must only be used when statically defining a Context + in server.xml. In all other circumstances, the path will be inferred + from the filenames used for either the .xml context file or the docBase. +

    +

    Even when statically defining a Context in server.xml, this attribute + must not be set unless either the docBase is not located under the + Host's appBase or both + deployOnStartup and autoDeploy are false. If + this rule is not followed, double deployment is likely to result.

    +
    preemptiveAuthentication +

    When set to true and the user presents credentials for a + resource that is not protected by a security constraint, if the + authenticator supports preemptive authentication (the standard + authenticators provided with Tomcat do) then the user' credentials + will be processed. If not specified, the default of false is + used. +

    +
    privileged +

    Set to true to allow this context to use container + servlets, like the manager servlet. Use of the privileged + attribute will change the context's parent class loader to be the + Server class loader rather than the Shared class + loader. Note that in a default installation, the Common class + loader is used for both the Server and the Shared + class loaders.

    +
    reloadable +

    Set to true if you want Catalina to monitor classes in + /WEB-INF/classes/ and /WEB-INF/lib for + changes, and automatically reload the web application if a change + is detected. This feature is very useful during application + development, but it requires significant runtime overhead and is + not recommended for use on deployed production applications. That's + why the default setting for this attribute is false. You + can use the Manager web + application, however, to trigger reloads of deployed applications + on demand.

    +
    resourceOnlyServlets +

    Comma separated list of Servlet names (as used in + /WEB-INF/web.xml) that expect a resource to be present. + Ensures that welcome files associated with Servlets that expect a + resource to be present (such as the JSP Servlet) are not used when there + is no resource present. This prevents issues caused by the clarification + of welcome file mapping in section 10.10 of the Servlet 3.0 + specification. If the + org.apache.catalina.STRICT_SERVLET_COMPLIANCE + system property is set to + true, the default value of this attribute will be the empty + string, else the default value will be jsp.

    +
    sendRedirectBody +

    If true, redirect responses will include a short + response body that includes details of the redirect as recommended by + RFC 2616. This is disabled by default since including a response body + may cause problems for some application component such as compression + filters.

    +
    sessionCookieDomain +

    The domain to be used for all session cookies created for this + context. If set, this overrides any domain set by the web application. + If not set, the value specified by the web application, if any, will be + used.

    +
    sessionCookieName +

    The name to be used for all session cookies created for this + context. If set, this overrides any name set by the web application. + If not set, the value specified by the web application, if any, will be + used, or the name JSESSIONID if the web application does + not explicitly set one.

    +
    sessionCookiePath +

    The path to be used for all session cookies created for this + context. If set, this overrides any path set by the web application. + If not set, the value specified by the web application will be used, or + the context path used if the web application does not explicitly set + one. To configure all web application to use an empty path (this can be + useful for portlet specification implementations) set this attribute to + / in the global CATALINA_BASE/conf/context.xml + file.

    +

    Note: Once one web application using + sessionCookiePath="/" obtains a session, all + subsequent sessions for any other web application in the same host also + configured with sessionCookiePath="/" will always + use the same session ID. This holds even if the session is invalidated + and a new one created. This makes session fixation protection more + difficult and requires custom, Tomcat specific code to change the + session ID shared by the multiple applications.

    +
    sessionCookiePathUsesTrailingSlash +

    Some browsers, such as Internet Explorer, Safari and Edge, will send + a session cookie for a context with a path of /foo with a + request to /foobar in violation of RFC6265. This could + expose a session ID from an application deployed at /foo to + an application deployed at /foobar. If the application + deployed at /foobar is untrusted, this could create a + security risk. However, it should be noted that RFC 6265, section 8.5 + makes clear that path alone should not be view as sufficient to prevent + untrusted applications accessing cookies from other applications. To + mitigate this risk, this attribute may be set to true and + Tomcat will add a trailing slash to the path associated with the session + cookie so, in the above example, the cookie path becomes /foo/. However, + with a cookie path of /foo/, browsers will no longer send the cookie + with a request to /foo. This should not be a problem unless there is a + servlet mapped to /*. In this case this attribute will need to be set to + false to disable this feature. The default value for this + attribute is false.

    +
    swallowAbortedUploads +

    Set to false if Tomcat should not read any additional request + body data for aborted uploads and instead abort the client connection. + This setting is used in the following situations: +

    +
      +
    • the size of the request body is larger than the + maxPostSize configured in the connector
    • +
    • the size limit of a MultiPart upload is reached
    • +
    • the servlet sets the response status to 413 (Request Entity Too + Large)
    • +
    +

    + Not reading the additional data will free the request processing thread + more quickly. Unfortunately most HTTP clients will not read the response + if they cannot write the full request.

    +

    The default is true, so additional data will be + read.

    +

    Note if an error occurs during the request processing that triggers + a 5xx response, any unread request data will always be ignored and the + client connection will be closed once the error response has been + written.

    +
    swallowOutput +

    If the value of this flag is true, the bytes output to + System.out and System.err by the web application will be redirected to + the web application logger. If not specified, the default value + of the flag is false.

    +
    tldValidation +

    If the value of this flag is true, the TLD files + will be XML validated on context startup. If the + org.apache.catalina.STRICT_SERVLET_COMPLIANCE + system property is set to + true, the default value of this attribute will be + true, else the default value will be false. + Setting this attribute to true will incur a performance + penalty.

    +
    useHttpOnly +

    Should the HttpOnly flag be set on session cookies to prevent client + side script from accessing the session ID? Defaults to + true.

    +
    useRelativeRedirects +

    Controls whether HTTP 1.1 and later location headers generated by a + call to + javax.servlet.http.HttpServletResponse#sendRedirect(String) + will use relative or absolute redirects. Relative redirects are more + efficient but may not work with reverse proxies that change the context + path. It should be noted that it is not recommended to use a reverse + proxy to change the context path because of the multiple issues it + creates. Absolute redirects should work with reverse proxies that change + the context path but may cause issues with the + org.apache.catalina.filters.RemoteIpFilter if the filter is + changing the scheme and/or port. If the + org.apache.catalina.STRICT_SERVLET_COMPLIANCE + system property is set to + true, the default value of this attribute will be + false, else the default value will be true. +

    +
    validateClientProvidedNewSessionId +

    When a client provides the ID for a new session, this attribute + controls whether that ID is validated. The only use case for using a + client provided session ID is to have a common session ID across + multiple web applications. Therefore, any client provided session ID + should already exist in another web application. If this check is + enabled, the client provided session ID will only be used if the session + ID exists in at least one other web application for the current host. + Note that the following additional tests are always applied, + irrespective of this setting:

    +
      +
    • The session ID is provided by a cookie
    • +
    • The session cookie has a path of {@code /}
    • +
    +

    If not specified, the default value of true will be + used.

    +
    wrapperClass +

    Java class name of the org.apache.catalina.Wrapper + implementation class that will be used for servlets managed by this + Context. If not specified, a standard default value will be used.

    +
    xmlBlockExternal +

    If the value of this flag is true, the parsing of + web.xml, web-fragment.xml, *.tld, + *.jspx, *.tagx and tagPlugins.xml + files for this web application will not permit external entities to be + loaded. If not specified, the default value of true will + be used.

    +
    xmlNamespaceAware +

    If the value of this flag is true, the parsing of + web.xml and web-fragment.xml files for this + web application will be namespace-aware. Note that *.tld, + *.jspx and *.tagx files are always parsed + using a namespace-aware parser and that the tagPlugins.xml + file (if any) is never parsed using a namespace-aware parser. Note also + that if you turn this flag on, you should probably also turn + xmlValidation on. If the + org.apache.catalina.STRICT_SERVLET_COMPLIANCE + system property is set to + true, the default value of this attribute will be + true, else the default value will be false. + Setting this attribute to true will incur a performance + penalty.

    +
    xmlValidation +

    If the value of this flag is true, the parsing of + web.xml and web-fragment.xml files for this + web application will use a validating parser. If the + org.apache.catalina.STRICT_SERVLET_COMPLIANCE + system property is set to + true, the default value of this attribute will be + true, else the default value will be false. + Setting this attribute to true will incur a performance + penalty.

    +
    + +
    + + +

    Standard Implementation

    + +

    The standard implementation of Context is + org.apache.catalina.core.StandardContext. + It supports the following additional attributes (in addition to the + common attributes listed above):

    + +
    + Attribute + + Description +
    addWebinfClassesResources +

    This attribute controls if, in addition to static resources being + served from META-INF/resources inside web application JAR + files, static resources are also served from + WEB-INF/classes/META-INF/resources. This only applies to + web applications with a major version of 3 or higher. Since this is a + proprietary extension to the Servlet 3 specification, it is disabled by + default. To enable this feature, set the attribute to true. +

    +
    antiResourceLocking +

    If true, Tomcat will prevent any file locking. + This will significantly impact startup time of applications, + but allows full webapp hot deploy and undeploy on platforms + or configurations where file locking can occur. + If not specified, the default value is false.

    + +

    Please note that setting this to true has some side + effects, including the disabling of JSP reloading in a running server: + see + Bugzilla 37668.

    + +

    Please note that setting this flag to true in applications that are + outside the appBase for the Host (the webapps directory + by default) will cause the application to be deleted on + Tomcat shutdown. You probably don't want to do this, so think twice + before setting antiResourceLocking=true on a webapp that's outside the + appBase for its Host.

    +
    clearReferencesHttpClientKeepAliveThread +

    If true and an sun.net.www.http.HttpClient + keep-alive timer thread has been started by this web application and is + still running, Tomcat will change the context class loader for that + thread from the web application class loader to the parent of the web + application class loader to prevent a memory leak. Note that the + keep-alive timer thread will stop on its own once the keep-alives all + expire however, on a busy system that might not happen for some time. If + not specified, the default value of true will be used.

    +
    clearReferencesObjectStreamClassCaches +

    If true, when the web application is stopped Tomcat + looks for SoftReferences to classes loaded by the web + application in the ObjectStreamClass class used for + serialization and clears any SoftReferences it finds. This + feature uses reflection to identify the SoftReferences and + therefore requires that the command line option + -XaddExports:java.base/java.io=ALL-UNNAMED is set + when running on Java 9 and above. If not specified, the default value of + true will be used.

    +
    clearReferencesRmiTargets +

    If true, Tomcat looks for memory leaks associated with + RMI Targets and clears any it finds. This feature uses reflection to + identify the leaks and therefore requires that the command line option + -XaddExports:java.rmi/sun.rmi.transport=ALL-UNNAMED is set + when running on Java 9 and above. Applications without memory leaks + should operate correctly with this attribute set to false. + If not specified, the default value of true will be used.

    +
    clearReferencesStopThreads +

    If true, Tomcat attempts to terminate threads that have + been started by the web application. Stopping threads is performed via + the deprecated (for good reason) Thread.stop() method and + is likely to result in instability. As such, enabling this should be + viewed as an option of last resort in a development environment and is + not recommended in a production environment. If not specified, the + default value of false will be used. If this feature is + enabled, web applications may take up to two seconds longer to stop as + executor threads are given up to two seconds to stop gracefully before + Thread.stop() is called on any remaining threads.

    +
    clearReferencesStopTimerThreads +

    If true, Tomcat attempts to terminate + java.util.Timer threads that have been started by the web + application. Unlike standard threads, timer threads can be stopped + safely although there may still be side-effects for the application. If + not specified, the default value of false will be used.

    +
    clearReferencesThreadLocals +

    If true, Tomcat attempts to clear + java.lang.ThreadLocal variables that have been populated + with classes loaded by the web application. If not specified, the + default value of true will be used.

    +
    copyXML +

    Set to true if you want a context XML descriptor + embedded inside the application (located at + /META-INF/context.xml) to be copied to the owning + Host's xmlBase when the application + is deployed. On subsequent starts, the copied context XML descriptor + will be used in preference to any context XML descriptor embedded inside + the application even if the descriptor embedded inside the application + is more recent. The flag's value defaults to false. Note if + the deployXML attribute of the owning + Host is false or if the + copyXML attribute of the owning + Host is true, this attribute will + have no effect.

    +
    jndiExceptionOnFailedWrite +

    If true, any attempt by an application to modify the + provided JNDI context with a call to bind(), unbind(), + createSubContext(), destroySubContext() or close() will trigger a + javax.naming.OperationNotSupportedException as required by + section EE.5.3.4 of the Java EE specification. This exception can be + disabled by setting this attribute to false in which case any calls to + modify the JNDI context will return without making any changes + and methods that return values will return null. If not + specified, the specification compliant default of true will + be used.

    +
    renewThreadsWhenStoppingContext +

    If true, when this context is stopped, Tomcat renews all + the threads from the thread pool that was used to serve this context. + This also requires that the + ThreadLocalLeakPreventionListener be configured in + server.xml and that the threadRenewalDelay + property of the Executor be >=0. If not specified, the + default value of true will be used.

    +
    unloadDelay +

    Number of ms that the container will wait for servlets to unload. + If not specified, the default value is 2000 ms.

    +
    unpackWAR +

    If false, the unpackWARs attribute of + the owning Host will be overridden and the WAR + file will not be unpacked. If true, the value of the owning + Host's unpackWARs + attribute will determine if the WAR is unpacked. If not specified, the + default value is true.

    +
    useNaming +

    Set to true (the default) to have Catalina enable a + JNDI InitialContext for this web application that is + compatible with Java2 Enterprise Edition (J2EE) platform + conventions.

    +
    workDir +

    Pathname to a scratch directory to be provided by this Context + for temporary read-write use by servlets within the associated web + application. This directory will be made visible to servlets in the + web application by a servlet context attribute (of type + java.io.File) named + javax.servlet.context.tempdir as described in the + Servlet Specification. If not specified, a suitable directory + underneath $CATALINA_BASE/work will be provided.

    +
    + +
    + + +

    Nested Components

    + +

    You can nest at most one instance of the following utility components + by nesting a corresponding element inside your Context + element:

    +
      +
    • Cookie Processor - + Configure parsing and generation of HTTP cookie headers.
    • +
    • Loader - + Configure the web application class loader that will be used to load + servlet and bean classes for this web application. Normally, the + default configuration of the class loader will be sufficient.
    • +
    • Manager - + Configure the session manager that will be used to create, destroy, + and persist HTTP sessions for this web application. Normally, the + default configuration of the session manager will be sufficient.
    • +
    • Realm - + Configure a realm that will allow its + database of users, and their associated roles, to be utilized solely + for this particular web application. If not specified, this web + application will utilize the Realm associated with the owning + Host or Engine.
    • +
    • Resources - + Configure the resource manager that will be used to access the static + resources associated with this web application. Normally, the + default configuration of the resource manager will be sufficient.
    • +
    • WatchedResource - The auto deployer will monitor the + specified static resource of the web application for updates, and will + reload the web application if it is updated. The content of this element + must be a string.
    • +
    • JarScanner - + Configure the Jar Scanner that will be used to scan the web application + for JAR files and directories of class files. It is typically used during + web application start to identify configuration files such as TLDs o + web-fragment.xml files that must be processed as part of the web + application initialisation. Normally, the default Jar Scanner + configuration will be sufficient.
    • +
    + +

    Special Features

    + + +

    Logging

    + +

    A context is associated with the + org.apache.catalina.core.ContainerBase.[enginename].[hostname].[path] + log category. Note that the brackets are actually part of the name, don't omit them.

    + +
    + + +

    Access Logs

    + +

    When you run a web server, one of the output files normally generated + is an access log, which generates one line of information for + each request processed by the server, in a standard format. Catalina + includes an optional Valve implementation that + can create access logs in the same standard format created by web servers, + or in any number of custom formats.

    + +

    You can ask Catalina to create an access log for all requests + processed by an Engine, + Host, or Context + by nesting a Valve element like this:

    + +
    <Context>
    +  ...
    +  <Valve className="org.apache.catalina.valves.AccessLogValve"
    +         prefix="localhost_access_log" suffix=".txt"
    +         pattern="common"/>
    +  ...
    +</Context>
    + +

    See Access Logging Valves + for more information on the configuration attributes that are + supported.

    + +
    + + +

    Automatic Context Configuration

    + +

    If you use the standard Context implementation, + the following configuration steps occur automatically when Catalina + is started, or whenever this web application is reloaded. No special + configuration is required to enable this feature.

    + +
      +
    • If you have not declared your own Loader + element, a standard web application class loader will be configured. +
    • +
    • If you have not declared your own Manager + element, a standard session manager will be configured.
    • +
    • If you have not declared your own Resources + element, a standard resources manager will be configured.
    • +
    • The web application properties listed in conf/web.xml + will be processed as defaults for this web application. This is used + to establish default mappings (such as mapping the *.jsp + extension to the corresponding JSP servlet), and other standard + features that apply to all web applications.
    • +
    • The web application properties listed in the + /WEB-INF/web.xml resource for this web application + will be processed (if this resource exists).
    • +
    • If your web application has specified security constraints that might + require user authentication, an appropriate Authenticator that + implements the login method you have selected will be configured.
    • +
    + +
    + + +

    Context Parameters

    + +

    You can configure named values that will be made visible to the + web application as servlet context initialization parameters by nesting + <Parameter> elements inside this element. For + example, you can create an initialization parameter like this:

    +
    <Context>
    +  ...
    +  <Parameter name="companyName" value="My Company, Incorporated"
    +         override="false"/>
    +  ...
    +</Context>
    + +

    This is equivalent to the inclusion of the following element in the + web application deployment descriptor (/WEB-INF/web.xml): +

    +
    <context-param>
    +  <param-name>companyName</param-name>
    +  <param-value>My Company, Incorporated</param-value>
    +</context-param>
    +

    but does not require modification of the deployment descriptor + to customize this value.

    + +

    The valid attributes for a <Parameter> element + are as follows:

    + +
    + Attribute + + Description +
    description +

    Optional, human-readable description of this context + initialization parameter.

    +
    name +

    The name of the context initialization parameter to be created.

    +
    override +

    Set this to false if you do not want + a <context-param> for the same parameter name, + found in the web application deployment descriptor, to override the + value specified here. By default, overrides are allowed.

    +
    value +

    The parameter value that will be presented to the application + when requested by calling + ServletContext.getInitParameter().

    +
    + +
    + + +

    Environment Entries

    + +

    You can configure named values that will be made visible to the + web application as environment entry resources, by nesting + <Environment> entries inside this element. For + example, you can create an environment entry like this:

    +
    <Context>
    +  ...
    +  <Environment name="maxExemptions" value="10"
    +         type="java.lang.Integer" override="false"/>
    +  ...
    +</Context>
    + +

    This is equivalent to the inclusion of the following element in the + web application deployment descriptor (/WEB-INF/web.xml): +

    +
    <env-entry>
    +  <env-entry-name>maxExemptions</env-entry-name>
    +  <env-entry-value>10</env-entry-value>
    +  <env-entry-type>java.lang.Integer</env-entry-type>
    +</env-entry>
    +

    but does not require modification of the deployment descriptor + to customize this value.

    + +

    The valid attributes for an <Environment> element + are as follows:

    + +
    + Attribute + + Description +
    description +

    Optional, human-readable description of this environment entry.

    +
    name +

    The name of the environment entry to be created, relative to the + java:comp/env context.

    +
    override +

    Set this to false if you do not want + an <env-entry> for the same environment entry name, + found in the web application deployment descriptor, to override the + value specified here. By default, overrides are allowed.

    +
    type +

    The fully qualified Java class name expected by the web application + for this environment entry. Must be a legal value for + <env-entry-type> in the web application deployment + descriptor.

    +
    value +

    The parameter value that will be presented to the application + when requested from the JNDI context. This value must be convertable + to the Java type defined by the type attribute.

    +
    + +
    + + +

    Lifecycle Listeners

    + +

    If you have implemented a Java object that needs to know when this + Context is started or stopped, you can declare it by + nesting a Listener element inside this element. The + class name you specify must implement the + org.apache.catalina.LifecycleListener interface, and + the class must be packaged in a jar and placed in the + $CATALINA_HOME/lib directory. + It will be notified about the occurrence of the corresponding + lifecycle events. Configuration of such a listener looks like this:

    + +
    <Context>
    +  ...
    +  <Listener className="com.mycompany.mypackage.MyListener" ... >
    +  ...
    +</Context>
    + +

    Note that a Listener can have any number of additional properties + that may be configured from this element. Attribute names are matched + to corresponding JavaBean property names using the standard property + method naming patterns.

    + +
    + + +

    Request Filters

    + +

    You can ask Catalina to check the IP address, or host name, on every + incoming request directed to the surrounding + Engine, Host, or + Context element. The remote address or name + will be checked against configured "accept" and/or "deny" + filters, which are defined using java.util.regex Regular + Expression syntax. Requests that come from locations that are + not accepted will be rejected with an HTTP "Forbidden" error. + Example filter declarations:

    + +
    <Context>
    +  ...
    +  <Valve className="org.apache.catalina.valves.RemoteHostValve"
    +         allow=".*\.mycompany\.com|www\.yourcompany\.com"/>
    +  <Valve className="org.apache.catalina.valves.RemoteAddrValve"
    +         deny="192\.168\.1\.\d+"/>
    +  ...
    +</Context>
    + +

    See Remote Address Filter + and Remote Host Filter for + more information about the configuration options that are supported.

    + +
    + + +

    Resource Definitions

    + +

    You can declare the characteristics of the resource + to be returned for JNDI lookups of <resource-ref> and + <resource-env-ref> elements in the web application + deployment descriptor. You MUST also define + the needed resource parameters as attributes of the Resource + element, to configure the object factory to be used (if not known to Tomcat + already), and the properties used to configure that object factory.

    + +

    For example, you can create a resource definition like this:

    +
    <Context>
    +  ...
    +  <Resource name="jdbc/EmployeeDB" auth="Container"
    +            type="javax.sql.DataSource"
    +     description="Employees Database for HR Applications"/>
    +  ...
    +</Context>
    + +

    This is equivalent to the inclusion of the following element in the + web application deployment descriptor (/WEB-INF/web.xml):

    +
    <resource-ref>
    +  <description>Employees Database for HR Applications</description>
    +  <res-ref-name>jdbc/EmployeeDB</res-ref-name>
    +  <res-ref-type>javax.sql.DataSource</res-ref-type>
    +  <res-auth>Container</res-auth>
    +</resource-ref>
    + +

    but does not require modification of the deployment + descriptor to customize this value.

    + +

    The valid attributes for a <Resource> element + are as follows:

    + +
    + Attribute + + Description +
    auth +

    Specify whether the web Application code signs on to the + corresponding resource manager programmatically, or whether the + Container will sign on to the resource manager on behalf of the + application. The value of this attribute must be + Application or Container. This + attribute is required if the web application + will use a <resource-ref> element in the web + application deployment descriptor, but is optional if the + application uses a <resource-env-ref> instead.

    +
    closeMethod +

    Name of the zero-argument method to call on a singleton resource when + it is no longer required. This is intended to speed up clean-up of + resources that would otherwise happen as part of garbage collection. + This attribute is ignored if the singleton attribute is + false.

    +

    For javax.sql.DataSource and + javax.sql.XADataSource resources that implement + AutoCloseable such as Apache Commons DBCP 2 and the default + Apache Tomcat connection pool, this attribute is defaults to + close. This may be disabled by setting the attribute to the + empty string. For all other resource types no default is defined and no + close method will be called by default.

    +
    description +

    Optional, human-readable description of this resource.

    +
    name +

    The name of the resource to be created, relative to the + java:comp/env context.

    +
    scope +

    Specify whether connections obtained through this resource + manager can be shared. The value of this attribute must be + Shareable or Unshareable. By default, + connections are assumed to be shareable.

    +
    singleton +

    Specify whether this resource definition is for a singleton resource, + i.e. one where there is only a single instance of the resource. If this + attribute is true, multiple JNDI lookups for this resource + will return the same object. If this attribute is false, + multiple JNDI lookups for this resource will return different objects. + This attribute must be true for + javax.sql.DataSource resources to enable JMX registration + of the DataSource. The value of this attribute must be true + or false. By default, this attribute is true. +

    +
    type +

    The fully qualified Java class name expected by the web + application when it performs a lookup for this resource.

    +
    + + +
    + + +
    + +

    This element is used to create a link to a global JNDI resource. Doing + a JNDI lookup on the link name will then return the linked global + resource.

    + +

    For example, you can create a resource link like this:

    +
    <Context>
    +  ...
    +  <ResourceLink name="linkToGlobalResource"
    +            global="simpleValue"
    +            type="java.lang.Integer"
    +  ...
    +</Context>
    + +

    The valid attributes for a <ResourceLink> element + are as follows:

    + +
    + Attribute + + Description +
    global +

    The name of the linked global resource in the + global JNDI context.

    +
    name +

    The name of the resource link to be created, relative to the + java:comp/env context.

    +
    type +

    The fully qualified Java class name expected by the web + application when it performs a lookup for this resource link.

    +
    factory +

    The fully qualified Java class name for the class creating these objects. + This class should implement the javax.naming.spi.ObjectFactory interface.

    +
    + +

    When the attribute factory="org.apache.naming.factory.DataSourceLinkFactory" the resource link can be used with + two additional attributes to allow a shared data source to be used with different credentials. + When these two additional attributes are used in combination with the javax.sql.DataSource + type, different contexts can share a global data source with different credentials. + Under the hood, what happens is that a call to getConnection() + is simply translated to a call + getConnection(username, password) on the global data source. This is an easy way to get code to be transparent to what schemas are being used, + yet be able to control connections (or pools) in the global configuration. +

    +
    + Attribute + + Description +
    username +

    username value for the getConnection(username, password) + call on the linked global DataSource. +

    +
    password +

    password value for the getConnection(username, password) + call on the linked global DataSource. +

    +
    +

    Shared Data Source Example:

    +

    Warning: This feature works only if the global DataSource +supports getConnection(username, password) method. +Apache Commons DBCP 2 pool that +Tomcat uses by default does not support it. See its Javadoc for +BasicDataSource class. +Apache Tomcat JDBC pool does support it, +but by default this support is disabled and can be enabled by +alternateUsernameAllowed attribute. See its documentation +for details.

    +
    <GlobalNamingResources>
    +  ...
    +  <Resource name="sharedDataSource"
    +            global="sharedDataSource"
    +            type="javax.sql.DataSource"
    +            factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
    +            alternateUsernameAllowed="true"
    +            username="bar"
    +            password="barpass"
    +            ...
    +  ...
    +</GlobalNamingResources>
    +
    +<Context path="/foo"...>
    +  ...
    +  <ResourceLink
    +            name="appDataSource"
    +            global="sharedDataSource"
    +            type="javax.sql.DataSource"
    +            factory="org.apache.naming.factory.DataSourceLinkFactory"
    +            username="foo"
    +            password="foopass"
    +  ...
    +</Context>
    +<Context path="/bar"...>
    +  ...
    +  <ResourceLink
    +            name="appDataSource"
    +            global="sharedDataSource"
    +            type="javax.sql.DataSource"
    +  ...
    +</Context>
    +

    When a request for getConnection() is made in the + /foo context, the request is translated into + getConnection("foo","foopass"), + while a request in the /bar gets passed straight through.

    +
    + +

    Transaction

    + +

    You can declare the characteristics of the UserTransaction + to be returned for JNDI lookup for java:comp/UserTransaction. + You MUST define an object factory class to instantiate + this object as well as the needed resource parameters as attributes of the + Transaction + element, and the properties used to configure that object factory.

    + +

    The valid attributes for the <Transaction> element + are as follows:

    + +
    + Attribute + + Description +
    factory +

    The class name for the JNDI object factory.

    +
    + +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/cookie-processor.html b/tomcat/docs/config/cookie-processor.html new file mode 100644 index 0000000..310898f --- /dev/null +++ b/tomcat/docs/config/cookie-processor.html @@ -0,0 +1,202 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - The Cookie Processor Component

    The Cookie Processor Component

    Table of Contents

    Introduction

    + +

    The CookieProcessor element represents the component that + parses received cookie headers into javax.servlet.http.Cookie + objects accessible through HttpServletRequest.getCookies() and + converts javax.servlet.http.Cookie objects added to the response + through HttpServletResponse.addCookie() to the HTTP headers + returned to the client.

    + +

    A CookieProcessor element MAY be nested inside a + Context component. If it is not included, a default + implementation will be created automatically.

    + +

    Attributes

    + +

    Common Attributes

    + +

    All implementations of CookieProcessor support the + following attributes:

    + +
    + Attribute + + Description +
    className +

    Java class name of the implementation to use. This class must + implement the org.apache.tomcat.util.http.CookieProcessor + interface. If not specified, the standard value (defined below) will be + used.

    +
    + +
    + + +

    Standard Implementation

    + +

    The standard implementation of CookieProcessor is + org.apache.tomcat.util.http.Rfc6265CookieProcessor.

    + +

    This cookie processor is based on RFC6265 with the following changes to + support better interoperability:

    + +
      +
    • Values 0x80 to 0xFF are permitted in cookie-octet to support the use + of UTF-8 in cookie values as used by HTML 5.
    • +
    • For cookies without a value, the '=' is not required after the name as + some browsers do not sent it.
    • +
    + +

    The RFC 6265 cookie processor is generally more lenient than the legacy + cookie parser. In particular:

    + +
      +
    • The '=' and '/' characters are always + permitted in a cookie value.
    • +
    • Name only cookies are always permitted.
    • +
    • The cookie header is always preserved.
    • +
    + +

    The RFC 6265 Cookie Processor supports the following + additional attributes.

    + +
    + Attribute + + Description +
    sameSiteCookies +

    Enables setting same-site cookie attribute.

    + +

    If value is none then the same-site cookie attribute + won't be set. This is the default value.

    + +

    If value is lax then the browser only sends the cookie + in same-site requests and cross-site top level GET requests.

    + +

    If value is strict then the browser prevents sending the + cookie in any cross-site request.

    +
    + +
    + +
    + +

    This is the legacy cookie parser based on RFC6265, RFC2109 and RFC2616. + It implements a strict interpretation of the cookie specifications. Due to + various interoperability issues with browsers not all strict behaviours + are enabled by default and additional options are available to further + relax the behaviour of this cookie processor if required.

    + +
    + Attribute + + Description +
    allowEqualsInValue +

    If this is true Tomcat will allow '=' + characters when parsing unquoted cookie values. If false, + cookie values containing '=' will be terminated when the + '=' is encountered and the remainder of the cookie value + will be dropped.

    +

    If not set the specification compliant default value of + false will be used.

    +
    allowHttpSepsInV0 +

    If this is true Tomcat will allow HTTP separators in + cookie names and values.

    +

    If not specified, the default specification compliant value of + false will be used.

    +
    allowNameOnly +

    If this is true Tomcat will allow name only cookies + (with or without trailing '=') when parsing cookie headers. + If false, name only cookies will be dropped.

    +

    If not set the specification compliant default value of + false will be used.

    +
    alwaysAddExpires +

    If this is true Tomcat will always add an expires + parameter to a SetCookie header even for cookies with version greater + than zero. This is to work around a known IE6 and IE7 bug that causes I + to ignore the Max-Age parameter in a SetCookie header.

    +

    If org.apache.catalina.STRICT_SERVLET_COMPLIANCE is set + to true, the default of this setting will be + false, else the default value will be true. +

    +
    forwardSlashIsSeparator +

    If this is true Tomcat will treat the forward slash + character ('/') as an HTTP separator when processing cookie + headers. If org.apache.catalina.STRICT_SERVLET_COMPLIANCE + is set to true, the default of this setting will be + true, else the default value will be false. +

    +
    sameSiteCookies +

    Enables setting same-site cookie attribute.

    + +

    If value is none then the same-site cookie attribute + won't be set. This is the default value.

    + +

    If value is lax then the browser only sends the cookie + in same-site requests and cross-site top level GET requests.

    + +

    If value is strict then the browser prevents sending the + cookie in any cross-site request.

    +
    + +
    + +

    Nested Components

    + +

    No element may be nested inside a CookieProcessor.

    + +

    Special Features

    + +

    No special features are associated with a CookieProcessor + element.

    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/credentialhandler.html b/tomcat/docs/config/credentialhandler.html new file mode 100644 index 0000000..dea79e2 --- /dev/null +++ b/tomcat/docs/config/credentialhandler.html @@ -0,0 +1,209 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - The CredentialHandler Component

    The CredentialHandler Component

    Table of Contents

    Introduction

    + +

    The CredentialHandler element represents the component + used by a Realm to compare a provided credential such + as a password with the version of the credential stored by the + Realm. The CredentialHandler can + also be used to generate a new stored version of a given credential that would + be required, for example, when adding a new user to a + Realm or when changing a user's password.

    + +

    A CredentialHandler element MUST be nested inside a + Realm component. If it is not included, + a default CredentialHandler will be created using the + MessageDigestCredentialHandler.

    + +

    Attributes

    + +

    Common Attributes

    + +

    All implementations of CredentialHandler support the + following attributes:

    + +
    + Attribute + + Description +
    className +

    Java class name of the implementation to use. This class must + implement the org.apache.catalina.CredentialHandler + interface.

    +
    + +

    Unlike most Catalina components, there are several standard + CredentialHandler implementations available. As a result, + if a CredentialHandler element is present then the + className attribute MUST be used to select the implementation + you wish to use.

    + +
    + + +

    MessageDigestCredentialHandler

    + +

    The MessageDigestCredentialHandler is used when stored + passwords are protected by a message digest. This credential handler + supports the following forms of stored passwords:

    +
      +
    • plainText - the plain text credentials if no + algorithm is specified
    • +
    • encodedCredential - a hex encoded digest of the + password digested using the configured digest
    • +
    • {MD5}encodedCredential - a Base64 encoded MD5 + digest of the password
    • +
    • {SHA}encodedCredential - a Base64 encoded SHA1 digest + of the password
    • +
    • {SSHA}encodedCredential - 20 character salt followed + by the salted SHA1 digest Base64 encoded
    • +
    • salt$iterationCount$encodedCredential - a hex encoded + salt, iteration code and a hex encoded credential, each separated by + $
    • +
    + +

    If the stored password form does not include an iteration count then an + iteration count of 1 is used.

    + +

    If the stored password form does not include salt then no salt is + used.

    + +
    + Attribute + + Description +
    algorithm +

    The name of the java.security.MessageDigest algorithm + used to encode user passwords stored in the database. If not specified, + user passwords are assumed to be stored in clear-text.

    +
    encoding +

    Digesting the password requires that it is converted to bytes. This + attribute determines the character encoding to use for conversions + between characters and bytes. If not specified, UTF-8 will be used.

    +
    iterations +

    The number of iterations to use when creating a new stored credential + from a clear text credential.

    +
    saltLength +

    The length of the randomly generated salt to use when creating a + new stored credential from a clear text credential.

    +
    + +
    + +

    NestedCredentialHandler

    + +

    The NestedCredentialHandler is an implementation of + CredentialHandler that delegates to one or more + sub-CredentialHandlers.

    + +

    Using the NestedCredentialHandler gives the developer + the ability to combine multiple CredentialHandlers of the + same or different types.

    + +

    Sub-CredentialHandlers are defined by nesting CredentialHandler elements + inside the CredentialHandler element that defines the + NestedCredentialHandler. Credentials will be matched against each + CredentialHandler in the order they are listed. A match against + any CredentialHandler will be sufficient for the credentials to be + considered matched.

    + +
    + +

    SecretKeyCredentialHandler

    + +

    The SecretKeyCredentialHandler is used when stored + passwords are built using javax.crypto.SecretKeyFactory. This + credential handler supports the following forms of stored passwords:

    +
      +
    • salt$iterationCount$encodedCredential - a hex encoded + salt, iteration code and a hex encoded credential, each separated by + $
    • +
    + +

    If the stored password form does not include an iteration count then an + iteration count of 1 is used.

    + +

    If the stored password form does not include salt then no salt is + used.

    + +
    + Attribute + + Description +
    algorithm +

    The name of the secret key algorithm used to encode user passwords + stored in the database. If not specified, a default of + PBKDF2WithHmacSHA1 is used.

    +
    keyLength +

    The length of key to generate for the stored credential. If not + specified, a default of 160 is used.

    +
    iterations +

    The number of iterations to use when creating a new stored credential + from a clear text credential.

    +
    saltLength +

    The length of the randomly generated salt to use when creating a + new stored credential from a clear text credential.

    +
    + +
    + +

    Nested Components

    + +

    If you are using the NestedCredentialHandler Implementation or a + CredentialHandler that extends the NestedCredentialHandler one or more + <CredentialHandler> elements may be nested inside it. +

    + +

    Special Features

    + +

    No special features are associated with a + CredentialHandler element.

    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/engine.html b/tomcat/docs/config/engine.html new file mode 100644 index 0000000..8be609d --- /dev/null +++ b/tomcat/docs/config/engine.html @@ -0,0 +1,259 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - The Engine Container

    The Engine Container

    Table of Contents

    Introduction

    + +

    The Engine element represents the entire request + processing machinery associated with a particular Catalina + Service. It receives and processes + all requests from one or more Connectors, + and returns the completed response to the Connector for ultimate + transmission back to the client.

    + +

    Exactly one Engine element MUST be nested inside + a Service element, following all of the + corresponding Connector elements associated with this Service.

    + +

    Attributes

    + +

    Common Attributes

    + +

    All implementations of Engine + support the following attributes:

    + +
    + Attribute + + Description +
    backgroundProcessorDelay +

    This value represents the delay in seconds between the + invocation of the backgroundProcess method on this engine and + its child containers, including all hosts and contexts. + Child containers will not be invoked if their delay value is not + negative (which would mean they are using their own processing + thread). Setting this to a positive value will cause + a thread to be spawn. After waiting the specified amount of time, + the thread will invoke the backgroundProcess method on this engine + and all its child containers. If not specified, the default value for + this attribute is 10, which represent a 10 seconds delay.

    +
    className +

    Java class name of the implementation to use. This class must + implement the org.apache.catalina.Engine interface. + If not specified, the standard value (defined below) will be used.

    +
    defaultHost +

    The default host name, which identifies the + Host that will process requests directed + to host names on this server, but which are not configured in + this configuration file. This name MUST match the name + attributes of one of the Host elements + nested immediately inside.

    +
    jvmRoute +

    Identifier which must be used in load balancing scenarios to enable + session affinity. The identifier, which must be unique across all + Tomcat servers which participate in the cluster, will be appended to + the generated session identifier, therefore allowing the front end + proxy to always forward a particular session to the same Tomcat + instance.

    +

    + Note that the jvmRoute can also be set using the + jvmRoute system property. The jvmRoute + set in an <Engine> attribute will override + any jvmRoute system property. +

    +
    name +

    Logical name of this Engine, used in log and error messages. When + using multiple Service elements in the same + Server, each Engine MUST be assigned a unique + name.

    +
    startStopThreads +

    The number of threads this Engine will use to start + child Host elements in parallel. The special + value of 0 will result in the value of + Runtime.getRuntime().availableProcessors() being used. + Negative values will result in + Runtime.getRuntime().availableProcessors() + value being + used unless this is less than 1 in which case 1 thread will be used. If + not specified, the default value of 1 will be used.

    +
    + +
    + + +

    Standard Implementation

    + +

    The standard implementation of Engine is + org.apache.catalina.core.StandardEngine. + It supports the following additional attributes (in addition to the + common attributes listed above):

    + +
    + Attribute + + Description +
    + +
    + + +

    Nested Components

    + +

    You can nest one or more Host elements inside + this Engine element, each representing a different virtual + host associated with this server. At least one Host + is required, and one of the nested Hosts MUST + have a name that matches the name specified for the + defaultHost attribute, listed above.

    + +

    You can nest at most one instance of the following utility components + by nesting a corresponding element inside your Engine + element:

    +
      +
    • Realm - + Configure a realm that will allow its + database of users, and their associated roles, to be shared across all + Hosts and Contexts + nested inside this Engine, unless overridden by a + Realm configuration at a lower level.
    • +
    + +

    Special Features

    + + +

    Logging

    + +

    An engine is associated with the + org.apache.catalina.core.ContainerBase.[enginename] + log category. Note that the brackets are actually part of the name, + don't omit them.

    + +
    + + +

    Access Logs

    + +

    When you run a web server, one of the output files normally generated + is an access log, which generates one line of information for + each request processed by the server, in a standard format. Catalina + includes an optional Valve implementation that + can create access logs in the same standard format created by web servers, + or in any number of custom formats.

    + +

    You can ask Catalina to create an access log for all requests + processed by an Engine, + Host, or Context + by nesting a Valve element like this:

    + +
    <Engine name="Standalone" ...>
    +  ...
    +  <Valve className="org.apache.catalina.valves.AccessLogValve"
    +         prefix="catalina_access_log" suffix=".txt"
    +         pattern="common"/>
    +  ...
    +</Engine>
    + +

    See Access Logging Valves + for more information on the configuration attributes that are + supported.

    + +
    + + +

    Lifecycle Listeners

    + +

    If you have implemented a Java object that needs to know when this + Engine is started or stopped, you can declare it by + nesting a Listener element inside this element. The + class name you specify must implement the + org.apache.catalina.LifecycleListener interface, and + it will be notified about the occurrence of the corresponding + lifecycle events. Configuration of such a listener looks like this:

    + +
    <Engine name="Standalone" ...>
    +  ...
    +  <Listener className="com.mycompany.mypackage.MyListener" ... >
    +  ...
    +</Engine>
    + +

    Note that a Listener can have any number of additional properties + that may be configured from this element. Attribute names are matched + to corresponding JavaBean property names using the standard property + method naming patterns.

    + +
    + + +

    Request Filters

    + +

    You can ask Catalina to check the IP address, or host name, on every + incoming request directed to the surrounding + Engine, Host, or + Context element. The remote address or name + will be checked against configured "accept" and/or "deny" + filters, which are defined using java.util.regex Regular + Expression syntax. Requests that come from locations that are + not accepted will be rejected with an HTTP "Forbidden" error. + Example filter declarations:

    + +
    <Engine name="Standalone" ...>
    +  ...
    +  <Valve className="org.apache.catalina.valves.RemoteHostValve"
    +         allow=".*\.mycompany\.com|www\.yourcompany\.com"/>
    +  <Valve className="org.apache.catalina.valves.RemoteAddrValve"
    +         deny="192\.168\.1\.\d+"/>
    +  ...
    +</Engine>
    + +

    See Remote Address Filter + and Remote Host Filter for + more information about the configuration options that are supported.

    + +
    + + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/executor.html b/tomcat/docs/config/executor.html new file mode 100644 index 0000000..7388400 --- /dev/null +++ b/tomcat/docs/config/executor.html @@ -0,0 +1,127 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - The Executor (thread pool)

    The Executor (thread pool)

    Table of Contents

    Introduction

    + +

    The Executor represents a thread pool that can be shared + between components in Tomcat. Historically there has been a thread pool per + connector created but this allows you to share a thread pool, between (primarily) connector + but also other components when those get configured to support executors

    + + +

    The executor has to implement the org.apache.catalina.Executor interface.

    + +

    The executor is a nested element to the Service element. + And in order for it to be picked up by the connectors, the Executor element has to appear + prior to the Connector element in server.xml

    +

    Attributes

    + +

    Common Attributes

    + +

    All implementations of Executor + support the following attributes:

    + +
    + Attribute + + Description +
    className +

    The class of the implementation. The implementation has to implement the + org.apache.catalina.Executor interface. + This interface ensures that the object can be referenced through its name attribute + and that implements Lifecycle, so that it can be started and stopped with the container. + The default value for the className is org.apache.catalina.core.StandardThreadExecutor

    +
    name +

    The name used to reference this pool in other places in server.xml. + The name is required and must be unique.

    +
    + +
    + +

    Standard Implementation

    + +

    + The default implementation supports the following attributes:

    + +
    + Attribute + + Description +
    threadPriority +

    (int) The thread priority for threads in the executor, the default is + 5 (the value of the Thread.NORM_PRIORITY constant)

    +
    daemon +

    (boolean) Whether the threads should be daemon threads or not, the default is true

    +
    namePrefix +

    (String) The name prefix for each thread created by the executor. + The thread name for an individual thread will be namePrefix+threadNumber

    +
    maxThreads +

    (int) The max number of active threads in this pool, default is 200

    +
    minSpareThreads +

    (int) The minimum number of threads (idle and active) always kept alive, default is 25

    +
    maxIdleTime +

    (int) The number of milliseconds before an idle thread shutsdown, unless the number of active threads are less + or equal to minSpareThreads. Default value is 60000(1 minute)

    +
    maxQueueSize +

    (int) The maximum number of runnable tasks that can queue up awaiting + execution before we reject them. Default value is Integer.MAX_VALUE

    +
    prestartminSpareThreads +

    (boolean) Whether minSpareThreads should be started when starting the Executor or not, + the default is false

    +
    threadRenewalDelay +

    (long) If a ThreadLocalLeakPreventionListener is configured, + it will notify this executor about stopped contexts. + After a context is stopped, threads in the pool are renewed. To avoid renewing all threads at the same time, + this option sets a delay between renewal of any 2 threads. The value is in ms, + default value is 1000 ms. If value is negative, threads are not renewed.

    +
    + + +
    +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/filter.html b/tomcat/docs/config/filter.html new file mode 100644 index 0000000..eafbbd3 --- /dev/null +++ b/tomcat/docs/config/filter.html @@ -0,0 +1,1742 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - Container Provided Filters

    Container Provided Filters

    Table of Contents

    + +

    Introduction

    + +

    Tomcat provides a number of Filters which may be + configured for use with all web applications using + $CATALINA_BASE/conf/web.xml or may be configured for individual + web applications by configuring them in the application's + WEB-INF/web.xml. Each filter is described below.

    + +

    This description uses the variable name $CATALINA_BASE to refer the + base directory against which most relative paths are resolved. If you have + not configured Tomcat for multiple instances by setting a CATALINA_BASE + directory, then $CATALINA_BASE will be set to the value of $CATALINA_HOME, + the directory into which you have installed Tomcat.

    + +

    Add Default Character Set Filter

    + +

    Introduction

    + +

    The HTTP specification is clear that if no character set is specified for + media sub-types of the "text" media type, the ISO-8859-1 character set must + be used. However, browsers may attempt to auto-detect the character set. + This may be exploited by an attacker to perform an XSS attack. Internet + Explorer and other browsers have an option to + enable this behavior.

    + +

    This filter prevents the attack by explicitly setting a character set. + Unless the provided character set is explicitly overridden by the user the + browser will adhere to the explicitly set character set, thus preventing the + XSS attack.

    + +
    + +

    Filter Class Name

    + +

    The filter class name for the Add Default Character Set Filter is + org.apache.catalina.filters.AddDefaultCharsetFilter + .

    + +
    + +

    Initialisation parameters

    + +

    The Add Default Character Set Filter supports the following initialization + parameters:

    + +
    + Attribute + + Description +
    encoding +

    Name of the character set which should be set, if no other character set + was set explicitly by a Servlet. This parameter has two special values + default and system. A value of system + uses the JVM wide default character set, which is usually set by locale. + A value of default will use ISO-8859-1.

    +
    + +
    + +

    CORS Filter

    +

    Introduction

    +

    This filter is an implementation of W3C's CORS (Cross-Origin Resource + Sharing) specification, which is a + mechanism that enables cross-origin requests.

    +

    The filter works by adding required Access-Control-* headers + to HttpServletResponse object. The filter also protects against HTTP + response splitting. If request is invalid, or is not permitted, then request + is rejected with HTTP status code 403 (Forbidden). A + flowchart that + demonstrates request processing by this filter is available.

    +

    The minimal configuration required to use this filter is:

    +
    <filter>
    +  <filter-name>CorsFilter</filter-name>
    +  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
    +</filter>
    +<filter-mapping>
    +  <filter-name>CorsFilter</filter-name>
    +  <url-pattern>/*</url-pattern>
    +</filter-mapping>
    +

    The above configuration enables the filter but does not relax the + cross-origin policy. As a minimum, you will need to add a + cors.allowed.origins initialisation parameter as described + below to enable cross-origin requests. Depending on your requirements, you + may need to provide additional configuration.

    +

    An instance of this filter can only implement one policy. If you want to + apply different policies (e.g. different allowed origins) to different URLs + or sets of URLs within your web application you will need to configure a + separate instance of this filter for each policy you wish to configure.

    +
    +

    Filter Class Name

    +

    The filter class name for the CORS Filter is + org.apache.catalina.filters.CorsFilter.

    +
    +

    Initialisation parameters

    +

    The CORS Filter supports following initialisation parameters:

    +
    + Attribute + + Description +
    cors.allowed.origins +

    A list of origins + that are allowed to access the resource. A * can be + specified to enable access to resource from any origin. Otherwise, a + whitelist of comma separated origins can be provided. Eg: + https://www.w3.org, https://www.apache.org. + Defaults: The empty String. (No origin is allowed to + access the resource).

    +
    cors.allowed.methods +

    A comma separated list of HTTP methods that can be used to access the + resource, using cross-origin requests. These are the methods which will + also be included as part of Access-Control-Allow-Methods + header in pre-flight response. Eg: GET, POST. + Defaults: GET, POST, HEAD, OPTIONS

    +
    cors.allowed.headers +

    A comma separated list of request headers that can be used when + making an actual request. These headers will also be returned as part + of Access-Control-Allow-Headers header in a pre-flight + response. Eg: Origin,Accept. Defaults: + Origin, Accept, X-Requested-With, Content-Type, + Access-Control-Request-Method, Access-Control-Request-Headers

    +
    cors.exposed.headers +

    A comma separated list of headers other than simple response headers + that browsers are allowed to access. These are the headers which will + also be included as part of Access-Control-Expose-Headers + header in the pre-flight response. Eg: + X-CUSTOM-HEADER-PING,X-CUSTOM-HEADER-PONG. + Default: None. Non-simple headers are not exposed by + default.

    +
    cors.preflight.maxage +

    The amount of seconds, browser is allowed to cache the result of the + pre-flight request. This will be included as part of + Access-Control-Max-Age header in the pre-flight response. + A negative value will prevent CORS Filter from adding this response + header to pre-flight response. Defaults: + 1800

    +
    cors.support.credentials +

    A flag that indicates whether the resource supports user credentials. + This flag is exposed as part of + Access-Control-Allow-Credentials header in a pre-flight + response. It helps browser determine whether or not an actual request + can be made using credentials. Defaults: + false

    +
    cors.request.decorate +

    A flag to control if CORS specific attributes should be added to + HttpServletRequest object or not. Defaults: + true

    +
    +

    Here's an example of a more advanced configuration, that overrides + defaults:

    +
    <filter>
    +  <filter-name>CorsFilter</filter-name>
    +  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
    +  <init-param>
    +    <param-name>cors.allowed.origins</param-name>
    +    <param-value>https://www.apache.org</param-value>
    +  </init-param>
    +  <init-param>
    +    <param-name>cors.allowed.methods</param-name>
    +    <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
    +  </init-param>
    +  <init-param>
    +    <param-name>cors.allowed.headers</param-name>
    +    <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
    +  </init-param>
    +  <init-param>
    +    <param-name>cors.exposed.headers</param-name>
    +    <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
    +  </init-param>
    +  <init-param>
    +    <param-name>cors.support.credentials</param-name>
    +    <param-value>true</param-value>
    +  </init-param>
    +  <init-param>
    +    <param-name>cors.preflight.maxage</param-name>
    +    <param-value>10</param-value>
    +  </init-param>
    +</filter>
    +<filter-mapping>
    +  <filter-name>CorsFilter</filter-name>
    +  <url-pattern>/*</url-pattern>
    +</filter-mapping>
    +
    +

    CORS Filter and HttpServletRequest attributes

    +

    CORS Filter adds information about the request, in HttpServletRequest + object, for consumption downstream. Following attributes are set, if + cors.request.decorate initialisation parameter is + true:

    +
      +
    • cors.isCorsRequest: Flag to determine if request is + a CORS request.
    • +
    • cors.request.origin: The Origin URL, i.e. the URL of + the page from where the request originated.
    • +
    • cors.request.type: Type of CORS request. Possible + values: +
        +
      • SIMPLE: A request which is not preceded by a + pre-flight request.
      • +
      • ACTUAL: A request which is preceded by a pre-flight + request.
      • +
      • PRE_FLIGHT: A pre-flight request.
      • +
      • NOT_CORS: A normal same-origin request.
      • +
      • INVALID_CORS: A cross-origin request, which is + invalid.
      • +
      +
    • +
    • cors.request.headers: Request headers sent as + Access-Control-Request-Headers header, for a pre-flight + request. +
    • +
    +
    +

    CSRF Prevention Filter

    + +

    Introduction

    + +

    This filter provides basic CSRF protection for a web application. The + filter assumes that it is mapped to /* and that all URLs + returned to the client are encoded via a call to + HttpServletResponse#encodeRedirectURL(String) or + HttpServletResponse#encodeURL(String).

    + +

    This filter prevents CSRF by generating a nonce and storing it in the + session. URLs are also encoded with the same nonce. When the next request is + received the nonce in the request is compared to the nonce in the session + and only if they are the same is the request allowed to continue.

    + +
    + +

    Filter Class Name

    + +

    The filter class name for the CSRF Prevention Filter is + org.apache.catalina.filters.CsrfPreventionFilter + .

    + +
    + +

    Initialisation parameters

    + +

    The CSRF Prevention Filter supports the following initialisation + parameters:

    + +
    + Attribute + + Description +
    denyStatus +

    HTTP response status code that is used when rejecting denied + request. The default value is 403.

    +
    entryPoints +

    A comma separated list of URLs that will not be tested for the + presence of a valid nonce. They are used to provide a way to navigate + back to a protected application after having navigated away from it. + Entry points will be limited to HTTP GET requests and should not trigger + any security sensitive actions.

    +
    nonceCacheSize +

    The number of previously issued nonces that will be cached on a LRU + basis to support parallel requests, limited use of the refresh and back + in the browser and similar behaviors that may result in the submission + of a previous nonce rather than the current one. If not set, the default + value of 5 will be used.

    +
    randomClass +

    The name of the class to use to generate nonces. The class must be an + instance of java.util.Random. If not set, the default value + of java.security.SecureRandom will be used.

    +
    + +
    + +

    CSRF Prevention Filter for REST APIs

    + +

    Introduction

    + +

    This filter provides basic CSRF protection for REST APIs. The CSRF + protection is applied only for modifying HTTP requests (different from GET, + HEAD, OPTIONS) to protected resources. It is based on a custom header + X-CSRF-Token that provides a valid nonce.

    + +

    CSRF protection mechanism for REST APIs consists of the following steps: +

      +
    • Client asks for a valid nonce. This is performed with a + non-modifying "Fetch" request to protected resource.
    • +
    • Server responds with a valid nonce mapped to the current user + session.
    • +
    • Client provides this nonce in the subsequent modifying requests in + the frame of the same user session.
    • +
    • Server rejects all modifying requests to protected resources that + do not contain a valid nonce.
    • +
    +

    + +
    + +

    Basic configuration sample

    + +

    On the server side

    + +
      +
    • All CSRF protected REST APIs should be protected with an authentication + mechanism.
    • +
    • Protect modifying REST APIs with this filter.
    • +
    • Provide at least one non-modifying operation.
    • +
    +
    <filter>
    +  <filter-name>RestCSRF</filter-name>
    +  <filter-class>org.apache.catalina.filters.RestCsrfPreventionFilter</filter-class>
    +</filter>
    +<filter-mapping>
    +  <filter-name>RestCSRF</filter-name>
    +  <!-- Modifying operations -->
    +  <url-pattern>/resources/removeResource</url-pattern>
    +  <url-pattern>/resources/addResource</url-pattern>
    +  <!-- Non-modifying operations -->
    +  <url-pattern>/resources/listResources</url-pattern>
    +</filter-mapping>
    + +

    On the client side

    + +
      +
    • Make a non-modifying "Fetch" request in order to obtain a valid nonce. + This can be done with sending additional header + X-CSRF-Token: Fetch
    • +
    • Cache the returned session id and nonce in order to provide them in + the subsequent modifying requests to protected resources.
    • +
    • Modifying requests can be denied and header + X-CSRF-Token: Required will be returned in case of + invalid or missing nonce, expired session or in case the session + id is changed by the server.
    • +
    +
    Client Request:
    +GET /rest/resources/listResources HTTP/1.1
    +X-CSRF-Token: Fetch
    +Authorization: Basic ...
    +Host: localhost:8080
    +...
    +
    +Server Response:
    +HTTP/1.1 200 OK
    +Set-Cookie: JSESSIONID=...; Path=/rest; HttpOnly
    +X-CSRF-Token: ...
    +...
    +
    +Client Request:
    +POST /rest/resources/addResource HTTP/1.1
    +Cookie: JSESSIONID=...
    +X-CSRF-Token: ...
    +Authorization: Basic ...
    +Host: localhost:8080
    +...
    +
    +Server Response:
    +HTTP/1.1 200 OK
    +...
    + +
    + +

    RestCsrfPreventionFilter and HttpServletRequest parameters

    + +

    When the client is not able to insert custom headers in its calls to + REST APIs there is additional capability to configure URLs for which a + valid nonce will be accepted as a request parameter.

    + +

    Note: If there is a X-CSRF-Token header, it will be taken + with preference over any parameter with the same name in the request. + Request parameters cannot be used to fetch new nonce, only header can be + used to request a new nonce.

    + +
    <filter>
    +  <filter-name>RestCSRF</filter-name>
    +  <filter-class>org.apache.catalina.filters.RestCsrfPreventionFilter</filter-class>
    +  <init-param>
    +    <param-name>pathsAcceptingParams</param-name>
    +    <param-value>/resources/removeResource,/resources/addResource</param-value>
    +  </init-param>
    +</filter>
    +<filter-mapping>
    +  <filter-name>RestCSRF</filter-name>
    +  <url-pattern>/resources/*</url-pattern>
    +</filter-mapping>
    + +
    + +

    Filter Class Name

    + +

    The filter class name for the CSRF Prevention Filter for REST APIs is + org.apache.catalina.filters.RestCsrfPreventionFilter + .

    + +
    + +

    Initialisation parameters

    + +

    The CSRF Prevention Filter for REST APIs supports the following + initialisation parameters:

    + +
    + Attribute + + Description +
    denyStatus +

    HTTP response status code that is used when rejecting denied + request. The default value is 403.

    +
    pathsAcceptingParams +

    A comma separated list of URLs that can accept nonces via request + parameter X-CSRF-Token. For use cases when a nonce information cannot + be provided via header, one can provide it via request parameters. If + there is a X-CSRF-Token header, it will be taken with preference over + any parameter with the same name in the request. Request parameters + cannot be used to fetch new nonce, only header can be used to request a + new nonce.

    +
    randomClass +

    The name of the class to use to generate nonces. The class must be an + instance of java.util.Random. If not set, the default value + of java.security.SecureRandom will be used.

    +
    + +
    + +

    Expires Filter

    + +

    Introduction

    + +

    + ExpiresFilter is a Java Servlet API port of Apache + mod_expires. + This filter controls the setting of the Expires HTTP header and the + max-age directive of the Cache-Control HTTP header in + server responses. The expiration date can set to be relative to either the + time the source file was last modified, or to the time of the client access. +

    + +

    + These HTTP headers are an instruction to the client about the document's + validity and persistence. If cached, the document may be fetched from the + cache rather than from the source until this time has passed. After that, the + cache copy is considered "expired" and invalid, and a new copy must + be obtained from the source. +

    +

    + To modify Cache-Control directives other than max-age (see + RFC + 2616 section 14.9), you can use other servlet filters or Apache Httpd + mod_headers module. +

    + +
    + +

    Basic configuration sample

    +

    + Basic configuration to add 'Expires' and 'Cache-Control: max-age=' + headers to images, css and javascript. +

    + +
    <filter>
    + <filter-name>ExpiresFilter</filter-name>
    + <filter-class>org.apache.catalina.filters.ExpiresFilter</filter-class>
    + <init-param>
    +    <param-name>ExpiresByType image</param-name>
    +    <param-value>access plus 10 minutes</param-value>
    + </init-param>
    + <init-param>
    +    <param-name>ExpiresByType text/css</param-name>
    +    <param-value>access plus 10 minutes</param-value>
    + </init-param>
    + <init-param>
    +    <param-name>ExpiresByType application/javascript</param-name>
    +    <param-value>access plus 10 minutes</param-value>
    + </init-param>
    +</filter>
    +...
    +<filter-mapping>
    + <filter-name>ExpiresFilter</filter-name>
    + <url-pattern>/*</url-pattern>
    + <dispatcher>REQUEST</dispatcher>
    +</filter-mapping>
    + +
    + +

    Alternate Syntax

    +

    + The ExpiresDefault and ExpiresByType directives can also be + defined in a more readable syntax of the form: +

    + +
    <init-param>
    + <param-name>ExpiresDefault</param-name>
    + <param-value><base> [plus] {<num> <type>}*</param-value>
    +</init-param>
    +
    +<init-param>
    + <param-name>ExpiresByType type</param-name>
    + <param-value><base> [plus] {<num> <type>}*</param-value>
    +</init-param>
    +
    +<init-param>
    + <param-name>ExpiresByType type;encoding</param-name>
    + <param-value><base> [plus] {<num> <type>}*</param-value>
    +</init-param>
    +

    + where <base> is one of: +

    +
      +
    • access
    • +
    • now (equivalent to 'access')
    • +
    • modification
    • +
    + +

    + The plus keyword is optional. <num> should be an + integer value (acceptable to Integer.parseInt()), and + <type> is one of: +

    +
      +
    • year, years
    • +
    • month, months
    • +
    • week, weeks
    • +
    • day, days
    • +
    • hour, hours
    • +
    • minute, minutes
    • +
    • second, seconds
    • +
    +

    + For example, any of the following directives can be used to make documents + expire 1 month after being accessed, by default: +

    + +
    <init-param>
    + <param-name>ExpiresDefault</param-name>
    + <param-value>access plus 1 month</param-value>
    +</init-param>
    +
    +<init-param>
    + <param-name>ExpiresDefault</param-name>
    + <param-value>access plus 4 weeks</param-value>
    +</init-param>
    +
    +<init-param>
    + <param-name>ExpiresDefault</param-name>
    + <param-value>access plus 30 days</param-value>
    +</init-param>
    +

    +The expiry time can be fine-tuned by adding several +'<num> <type>' clauses: +

    + +
    <init-param>
    + <param-name>ExpiresByType text/html</param-name>
    + <param-value>access plus 1 month 15 days 2 hours</param-value>
    +</init-param>
    +
    +<init-param>
    + <param-name>ExpiresByType image/gif</param-name>
    + <param-value>modification plus 5 hours 3 minutes</param-value>
    +</init-param>
    +

    + Note that if you use a modification date based setting, the Expires + header will not be added to content that does not come from + a file on disk. This is due to the fact that there is no modification time + for such content. +

    +
    + +

    Expiration headers generation eligibility

    +

    + A response is eligible to be enriched by ExpiresFilter if : +

    +
      +
    1. no expiration header is defined (Expires header or the + max-age directive of the Cache-Control header),
    2. +
    3. the response status code is not excluded by the directive + ExpiresExcludedResponseStatusCodes,
    4. +
    5. the Content-Type of the response matches one of the types + defined the in ExpiresByType directives or the + ExpiresDefault directive is defined.
    6. +
    + +

    + Note : If Cache-Control header contains other directives than + max-age, they are concatenated with the max-age directive + that is added by the ExpiresFilter. +

    + +
    + +

    Expiration configuration selection

    +

    + The expiration configuration if elected according to the following algorithm: +

    +
      +
    1. ExpiresByType matching the exact content-type returned by + HttpServletResponse.getContentType() possibly including the charset + (e.g. 'text/xml;charset=UTF-8'),
    2. +
    3. ExpiresByType matching the content-type without the charset if + HttpServletResponse.getContentType() contains a charset (e.g. + 'text/xml;charset=UTF-8' -> 'text/xml'),
    4. +
    5. ExpiresByType matching the major type (e.g. substring before + '/') of HttpServletResponse.getContentType() + (e.g. 'text/xml;charset=UTF-8' -> 'text'),
    6. +
    7. ExpiresDefault
    8. +
    + +
    + +

    Filter Class Name

    + +

    The filter class name for the Expires Filter is + org.apache.catalina.filters.ExpiresFilter + .

    + +
    + +

    Initialisation parameters

    + +

    The Expires Filter supports the following + initialisation parameters:

    + +
    + Attribute + + Description +
    ExpiresExcludedResponseStatusCodes +

    + This directive defines the http response status codes for which the + ExpiresFilter will not generate expiration headers. By default, the + 304 status code ("Not modified") is skipped. The + value is a comma separated list of http status codes. +

    +

    + This directive is useful to ease usage of ExpiresDefault directive. + Indeed, the behavior of 304 Not modified (which does specify a + Content-Type header) combined with Expires and + Cache-Control:max-age= headers can be unnecessarily tricky to + understand. +

    +

    See sample below the table

    +
    ExpiresByType <content-type> +

    + This directive defines the value of the Expires header and the + max-age directive of the Cache-Control header generated for + documents of the specified type (e.g., text/html). The second + argument sets the number of seconds that will be added to a base time to + construct the expiration date. The Cache-Control: max-age is + calculated by subtracting the request time from the expiration date and + expressing the result in seconds. +

    +

    + The base time is either the last modification time of the file, or the time + of the client's access to the document. Which should be used is + specified by the <code> field; M means that the + file's last modification time should be used as the base time, and + A means the client's access time should be used. The duration + is expressed in seconds. A2592000 stands for + access plus 30 days in alternate syntax. +

    +

    + The difference in effect is subtle. If M (modification in + alternate syntax) is used, all current copies of the document in all caches + will expire at the same time, which can be good for something like a weekly + notice that's always found at the same URL. If A ( + access or now in alternate syntax) is used, the date of + expiration is different for each client; this can be good for image files + that don't change very often, particularly for a set of related + documents that all refer to the same images (i.e., the images will be + accessed repeatedly within a relatively short timespan). +

    +

    + Note: When the content type includes a charset (e.g. + 'ExpiresByType text/xml;charset=utf-8'), Tomcat removes blank chars + between the ';' and the 'charset' keyword. Due to this, + configuration of an expiration with a charset must not include + such a space character. +

    +

    See sample below the table

    +

    + It overrides, for the specified MIME type only, any + expiration date set by the ExpiresDefault directive. +

    +

    + You can also specify the expiration time calculation using an alternate + syntax, described earlier in this document. +

    +
    ExpiresDefault +

    + This directive sets the default algorithm for calculating the + expiration time for all documents in the affected realm. It can be + overridden on a type-by-type basis by the ExpiresByType directive. See the + description of that directive for details about the syntax of the + argument, and the "alternate syntax" + description as well. +

    +
    + +

    Sample: exclude response status codes 302, 500 and 503

    + +
    <init-param>
    + <param-name>ExpiresExcludedResponseStatusCodes</param-name>
    + <param-value>302, 500, 503</param-value>
    +</init-param>
    + +

    Sample for ExpiresByType initialization parameter

    + +
    <init-param>
    +   <param-name>ExpiresByType text/html</param-name>
    +   <param-value>access plus 1 month 15   days 2 hours</param-value>
    +</init-param>
    +
    +<init-param>
    +   <!-- 2592000 seconds = 30 days -->
    +   <param-name>ExpiresByType image/gif</param-name>
    +   <param-value>A2592000</param-value>
    +</init-param>
    + +
    + +

    Troubleshooting

    +

    + To troubleshoot, enable logging on the + org.apache.catalina.filters.ExpiresFilter. +

    +

    + Extract of logging.properties +

    + +
    org.apache.catalina.filters.ExpiresFilter.level = FINE    
    +

    + Sample of initialization log message: +

    + +
    Mar 26, 2010 2:01:41 PM org.apache.catalina.filters.ExpiresFilter init
    +FINE: Filter initialized with configuration ExpiresFilter[
    + excludedResponseStatusCode=[304],
    + default=null,
    + byType={
    +    image=ExpiresConfiguration[startingPoint=ACCESS_TIME, duration=[10 MINUTE]],
    +    text/css=ExpiresConfiguration[startingPoint=ACCESS_TIME, duration=[10 MINUTE]],
    +    text/javascript=ExpiresConfiguration[startingPoint=ACCESS_TIME, duration=[10 MINUTE]]}]
    +

    + Sample of per-request log message where ExpiresFilter adds an + expiration date is below. The message is on one line and is wrapped here + for better readability. +

    + +
    Mar 26, 2010 2:09:47 PM org.apache.catalina.filters.ExpiresFilter onBeforeWriteResponseBody
    +FINE: Request "/tomcat.gif" with response status "200"
    + content-type "image/gif", set expiration date 3/26/10 2:19 PM
    +

    + Sample of per-request log message where ExpiresFilter does not add + an expiration date: +

    + +
    Mar 26, 2010 2:10:27 PM org.apache.catalina.filters.ExpiresFilter onBeforeWriteResponseBody
    +FINE: Request "/docs/config/manager.html" with response status "200"
    + content-type "text/html", no expiration configured
    +
    + +

    Failed Request Filter

    + +

    Introduction

    + +

    This filter triggers parameters parsing in a request and rejects the + request if some parameters were skipped during parameter parsing because + of parsing errors or request size limitations (such as + maxParameterCount attribute in a + Connector). + This filter can be used to ensure that none parameter values submitted by + client are lost.

    + +

    Note that parameter parsing may consume the body of an HTTP request, so + caution is needed if the servlet protected by this filter uses + request.getInputStream() or request.getReader() + calls. In general the risk of breaking a web application by adding this + filter is not so high, because parameter parsing does check content type + of the request before consuming the request body.

    + +

    Note, that for the POST requests to be parsed correctly, a + SetCharacterEncodingFilter filter must be configured above + this one. See CharacterEncoding page in the FAQ for details.

    + +

    The request is rejected with HTTP status code 400 (Bad Request).

    + +
    + +

    Filter Class Name

    + +

    The filter class name for the Failed Request Filter is + org.apache.catalina.filters.FailedRequestFilter + .

    + +
    + +

    Initialisation parameters

    + +

    The Failed Request Filter does not support any initialization parameters.

    + +
    + +

    HTTP Header Security Filter

    + +

    Introduction

    + +

    There are a number of HTTP headers that can be added to the response to + improve the security of the connection. This filter provides a mechanism for + adding those headers. Note that security related headers with more complex + requirements, like CORS, are implemented as separate Filters.

    + +
    + +

    Filter Class Name

    + +

    The filter class name for the HTTP Header Security Filter is + org.apache.catalina.filters.HttpHeaderSecurityFilter + .

    + +
    + +

    Initialisation parameters

    + +

    The HTTP Header Security Filter supports the following initialization + parameters:

    + +
    + Attribute + + Description +
    hstsEnabled +

    Will an HTTP Strict Transport Security (HSTS) header + (Strict-Transport-Security) be set on the response for + secure requests. Any HSTS header already present will be replaced. See + RFC 6797 for further + details of HSTS. If not specified, the default value of + true will be used.

    +
    hstsMaxAgeSeconds +

    The max age value that should be used in the HSTS header. Negative + values will be treated as zero. If not specified, the default value of + 0 will be used.

    +
    hstsIncludeSubDomains +

    Should the includeSubDomains parameter be included in the HSTS + header. If not specified, the default value of false will + be used.

    +
    hstsPreload +

    Should the preload parameter be included in the HSTS header. If not + specified, the default value of false will be used. See + https://hstspreload.org for + important information about this parameter.

    +
    antiClickJackingEnabled +

    Should the anti click-jacking header (X-Frame-Options) + be set on the response. Any anti click-jacking header already present + will be replaced. If not specified, the default value of + true will be used.

    +
    antiClickJackingOption +

    What value should be used for the anticlick-jacking header? Must be + one of DENY, SAMEORIGIN, + ALLOW-FROM (case-insensitive). If not specified, the + default value of DENY will be used.

    +
    antiClickJackingUri +

    If ALLOW-FROM is used for antiClickJackingOption, + what URI should be allowed? If not specified, the default value of an + empty string will be used.

    +
    blockContentTypeSniffingEnabled +

    Should the header that blocks content type sniffing + (X-Content-Type-Options) be set on every response. If + already present, the header will be replaced. If not specified, the + default value of true will be used.

    +
    xssProtectionEnabled +

    Should the header that enables the browser's cross-site scripting + filter protection (X-XSS-Protection: 1; mode=block) + be set on every response. If already present, the header + will be replaced. If not specified, the default value of + true will be used.

    +
    + +
    + +

    Remote Address Filter

    + +

    Introduction

    + +

    The Remote Address Filter allows you to compare the + IP address of the client that submitted this request against one or more + regular expressions, and either allow the request to continue + or refuse to process the request from this client.

    + +

    The syntax for regular expressions is different than that for + 'standard' wildcard matching. Tomcat uses the java.util.regex + package. Please consult the Java documentation for details of the + expressions supported.

    + +

    Note: There is a caveat when using this filter with + IPv6 addresses. Format of the IP address that this valve is processing + depends on the API that was used to obtain it. If the address was obtained + from Java socket using Inet6Address class, its format will be + x:x:x:x:x:x:x:x. That is, the IP address for localhost + will be 0:0:0:0:0:0:0:1 instead of the more widely used + ::1. Consult your access logs for the actual value.

    + +

    See also: Remote Host Filter.

    +
    + +

    Filter Class Name

    + +

    The filter class name for the Remote Address Filter is + org.apache.catalina.filters.RemoteAddrFilter + .

    + +
    + +

    Initialisation parameters

    + +

    The Remote Address Filter supports the following + initialisation parameters:

    + +
    + Attribute + + Description +
    allow +

    A regular expression (using java.util.regex) that the + remote client's IP address is compared to. If this attribute + is specified, the remote address MUST match for this request to be + accepted. If this attribute is not specified, all requests will be + accepted UNLESS the remote address matches a deny + pattern.

    +
    deny +

    A regular expression (using java.util.regex) that the + remote client's IP address is compared to. If this attribute + is specified, the remote address MUST NOT match for this request to be + accepted. If this attribute is not specified, request acceptance is + governed solely by the accept attribute.

    +
    denyStatus +

    HTTP response status code that is used when rejecting denied + request. The default value is 403. For example, + it can be set to the value 404.

    +
    + +
    + +

    Example

    +

    To allow access only for the clients connecting from localhost:

    +
        <filter>
    +      <filter-name>Remote Address Filter</filter-name>
    +      <filter-class>org.apache.catalina.filters.RemoteAddrFilter</filter-class>
    +      <init-param>
    +        <param-name>allow</param-name>
    +        <param-value>127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1</param-value>
    +      </init-param>
    +    </filter>
    +    <filter-mapping>
    +      <filter-name>Remote Address Filter</filter-name>
    +      <url-pattern>/*</url-pattern>
    +    </filter-mapping>
    +
    + +

    Remote Host Filter

    + +

    Introduction

    + +

    The Remote Host Filter allows you to compare the + hostname of the client that submitted this request against one or more + regular expressions, and either allow the request to continue + or refuse to process the request from this client.

    + +

    The syntax for regular expressions is different than that for + 'standard' wildcard matching. Tomcat uses the java.util.regex + package. Please consult the Java documentation for details of the + expressions supported.

    + +

    Note: This filter processes the value returned by + method ServletRequest.getRemoteHost(). To allow the method + to return proper host names, you have to enable "DNS lookups" feature on + a Connector.

    + +

    See also: Remote Address Filter, + HTTP Connector configuration.

    +
    + +

    Filter Class Name

    + +

    The filter class name for the Remote Address Filter is + org.apache.catalina.filters.RemoteHostFilter + .

    + +
    + +

    Initialisation parameters

    + +

    The Remote Host Filter supports the following + initialisation parameters:

    + +
    + Attribute + + Description +
    allow +

    A regular expression (using java.util.regex) that the + remote client's hostname is compared to. If this attribute + is specified, the remote hostname MUST match for this request to be + accepted. If this attribute is not specified, all requests will be + accepted UNLESS the remote hostname matches a deny + pattern.

    +
    deny +

    A regular expression (using java.util.regex) that the + remote client's hostname is compared to. If this attribute + is specified, the remote hostname MUST NOT match for this request to be + accepted. If this attribute is not specified, request acceptance is + governed solely by the accept attribute.

    +
    denyStatus +

    HTTP response status code that is used when rejecting denied + request. The default value is 403. For example, + it can be set to the value 404.

    +
    + +
    + +

    Remote CIDR Filter

    + +

    Introduction

    + +

    The Remote CIDR Filter allows you to compare the + IP address of the client that submitted this request against one or more + netmasks following the CIDR notation, and either allow the request to + continue or refuse to process the request from this client. IPv4 and + IPv6 are both fully supported. +

    + +

    This filter mimicks Apache httpd's Order, + Allow from and Deny from directives, + with the following limitations: +

    + +
      +
    • Order will always be allow, deny;
    • +
    • dotted quad notations for netmasks are not supported (that is, you + cannot write 192.168.1.0/255.255.255.0, you must write + 192.168.1.0/24; +
    • +
    • shortcuts, like 10.10., which is equivalent to + 10.10.0.0/16, are not supported; +
    • +
    • as the filter name says, this is a CIDR only filter, + therefore subdomain notations like .mydomain.com are not + supported either. +
    • +
    + +

    Some more features of this filter are: +

    + +
      +
    • if you omit the CIDR prefix, this filter becomes a single IP + filter;
    • +
    • unlike the Remote Host Filter, + it can handle IPv6 addresses in condensed form (::1, + fe80::/71, etc).
    • +
    + +
    + +

    Filter Class Name

    + +

    The filter class name for the Remote Address Filter is + org.apache.catalina.filters.RemoteCIDRFilter + .

    + +
    + +

    Initialisation parameters

    + +

    The Remote CIDR Filter supports the following + initialisation parameters:

    + +
    + Attribute + + Description +
    allow +

    A comma-separated list of IPv4 or IPv6 netmasks or addresses + that the remote client's IP address is matched against. + If this attribute is specified, the remote address MUST match + for this request to be accepted. If this attribute is not specified, + all requests will be accepted UNLESS the remote IP is matched by a + netmask in the deny attribute. +

    +
    deny +

    A comma-separated list of IPv4 or IPv6 netmasks or addresses + that the remote client's IP address is matched against. + If this attribute is specified, the remote address MUST NOT match + for this request to be accepted. If this attribute is not specified, + request acceptance is governed solely by the accept + attribute. +

    +
    + +
    + +

    Example

    +

    To allow access only for the clients connecting from localhost:

    +
    +      <filter>
    +      <filter-name>Remote CIDR Filter</filter-name>
    +      <filter-class>org.apache.catalina.filters.RemoteCIDRFilter</filter-class>
    +      <init-param>
    +      <param-name>allow</param-name>
    +      <param-value>127.0.0.0/8, ::1</param-value>
    +      </init-param>
    +      </filter>
    +      <filter-mapping>
    +      <filter-name>Remote CIDR Filter</filter-name>
    +      <url-pattern>/*</url-pattern>
    +      </filter-mapping>
    +    
    +
    + +

    Remote IP Filter

    + +

    Introduction

    + +

    Tomcat port of + mod_remoteip, + this filter replaces the apparent client remote IP address and hostname for + the request with the IP address list presented by a proxy or a load balancer + via a request headers (e.g. "X-Forwarded-For").

    + +

    Another feature of this filter is to replace the apparent scheme + (http/https), server port and request.secure with the scheme presented + by a proxy or a load balancer via a request header + (e.g. "X-Forwarded-Proto").

    + +

    If used in conjunction with Remote Address/Host filters then this filter + should be defined first to ensure that the correct client IP address is + presented to the Remote Address/Host filters.

    + +

    Note: By default this filter has no effect on the + values that are written into access log. The original values are restored + when request processing leaves the filter and that always happens earlier + than access logging. To pass the remote address, remote host, server port + and protocol values set by this filter to the access log, + they are put into request attributes. Publishing these values here + is enabled by default, but AccessLogValve should be explicitly + configured to use them. See documentation for + requestAttributesEnabled attribute of + AccessLogValve.

    + +

    The names of request attributes that are set by this filter + and can be used by access logging are the following:

    + +
      +
    • org.apache.catalina.AccessLog.RemoteAddr
    • +
    • org.apache.catalina.AccessLog.RemoteHost
    • +
    • org.apache.catalina.AccessLog.Protocol
    • +
    • org.apache.catalina.AccessLog.ServerPort
    • +
    • org.apache.tomcat.remoteAddr
    • +
    + +
    + +

    Filter Class Name

    + +

    The filter class name for the Remote IP Filter is + org.apache.catalina.filters.RemoteIpFilter + .

    + +
    + +

    Basic configuration to handle 'x-forwarded-for'

    +

    + The filter will process the x-forwarded-for http header. +

    +
          <filter>
    +        <filter-name>RemoteIpFilter</filter-name>
    +        <filter-class>org.apache.catalina.filters.RemoteIpFilter</filter-class>
    +      </filter>
    +
    +      <filter-mapping>
    +        <filter-name>RemoteIpFilter</filter-name>
    +        <url-pattern>/*</url-pattern>
    +        <dispatcher>REQUEST</dispatcher>
    +      </filter-mapping>
    +
    + +

    Basic configuration to handle 'x-forwarded-for' and 'x-forwarded-proto'

    + +

    + The filter will process x-forwarded-for and + x-forwarded-proto http headers. Expected value for the + x-forwarded-proto header in case of SSL connections is + https (case insensitive).

    +
          <filter>
    +        <filter-name>RemoteIpFilter</filter-name>
    +        <filter-class>org.apache.catalina.filters.RemoteIpFilter</filter-class>
    +        <init-param>
    +          <param-name>protocolHeader</param-name>
    +          <param-value>x-forwarded-proto</param-value>
    +        </init-param>
    +      </filter>
    +
    +      <filter-mapping>
    +        <filter-name>RemoteIpFilter</filter-name>
    +        <url-pattern>/*</url-pattern>
    +        <dispatcher>REQUEST</dispatcher>
    +      </filter-mapping>
    +
    + +

    Advanced configuration with internal proxies

    +

    RemoteIpFilter configuration:

    +
         <filter>
    +       <filter-name>RemoteIpFilter</filter-name>
    +       <filter-class>org.apache.catalina.filters.RemoteIpFilter</filter-class>
    +       <init-param>
    +         <param-name>allowedInternalProxies</param-name>
    +         <param-value>192\.168\.0\.10|192\.168\.0\.11</param-value>
    +       </init-param>
    +       <init-param>
    +         <param-name>remoteIpHeader</param-name>
    +         <param-value>x-forwarded-for</param-value>
    +       </init-param>
    +       <init-param>
    +         <param-name>remoteIpProxiesHeader</param-name>
    +         <param-value>x-forwarded-by</param-value>
    +       </init-param>
    +       <init-param>
    +         <param-name>protocolHeader</param-name>
    +         <param-value>x-forwarded-proto</param-value>
    +       </init-param>
    +     </filter>
    +

    Request values:

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    PropertyValue Before RemoteIpFilterValue After RemoteIpFilter
    request.remoteAddr 192.168.0.10 140.211.11.130
    request.header['x-forwarded-for'] 140.211.11.130, 192.168.0.10 null
    request.header['x-forwarded-by'] null null
    request.header['x-forwarded-proto'] https https
    request.scheme http https
    request.secure false true
    request.serverPort 80 443
    + +

    + Note : x-forwarded-by header is null because only + internal proxies has been traversed by the request. + x-forwarded-for is null because all the proxies are + trusted or internal. +

    +
    + + +

    Advanced configuration with trusted proxies

    +

    RemoteIpFilter configuration:

    +
         <filter>
    +       <filter-name>RemoteIpFilter</filter-name>
    +       <filter-class>org.apache.catalina.filters.RemoteIpFilter</filter-class>
    +       <init-param>
    +         <param-name>allowedInternalProxies</param-name>
    +         <param-value>192\.168\.0\.10|192\.168\.0\.11</param-value>
    +       </init-param>
    +       <init-param>
    +         <param-name>remoteIpHeader</param-name>
    +         <param-value>x-forwarded-for</param-value>
    +       </init-param>
    +       <init-param>
    +         <param-name>remoteIpProxiesHeader</param-name>
    +         <param-value>x-forwarded-by</param-value>
    +       </init-param>
    +       <init-param>
    +         <param-name>trustedProxies</param-name>
    +         <param-value>proxy1|proxy2</param-value>
    +       </init-param>
    +     </filter>
    +

    Request values:

    + + + + + + + + + + + + + + + + + + + + + +
    PropertyValue Before RemoteIpFilterValue After RemoteIpFilter
    request.remoteAddr 192.168.0.10 140.211.11.130
    request.header['x-forwarded-for'] 140.211.11.130, proxy1, proxy2 null
    request.header['x-forwarded-by'] null proxy1, proxy2
    + +

    + Note : proxy1 and proxy2 are both trusted proxies that + come in x-forwarded-for header, they both are migrated in + x-forwarded-by header. x-forwarded-for is null + because all the proxies are trusted or internal. +

    +
    + +

    Advanced configuration with internal and trusted proxies

    +

    RemoteIpFilter configuration:

    +
         <filter>
    +       <filter-name>RemoteIpFilter</filter-name>
    +       <filter-class>org.apache.catalina.filters.RemoteIpFilter</filter-class>
    +       <init-param>
    +         <param-name>allowedInternalProxies</param-name>
    +         <param-value>192\.168\.0\.10|192\.168\.0\.11</param-value>
    +       </init-param>
    +       <init-param>
    +         <param-name>remoteIpHeader</param-name>
    +         <param-value>x-forwarded-for</param-value>
    +       </init-param>
    +       <init-param>
    +         <param-name>remoteIpProxiesHeader</param-name>
    +         <param-value>x-forwarded-by</param-value>
    +       </init-param>
    +       <init-param>
    +         <param-name>trustedProxies</param-name>
    +         <param-value>proxy1|proxy2</param-value>
    +       </init-param>
    +     </filter>
    +

    Request values:

    + + + + + + + + + + + + + + + + + + + + + +
    PropertyValue Before RemoteIpFilterValue After RemoteIpFilter
    request.remoteAddr 192.168.0.10 140.211.11.130
    request.header['x-forwarded-for'] 140.211.11.130, proxy1, proxy2, 192.168.0.10 null
    request.header['x-forwarded-by'] null proxy1, proxy2
    + +

    + Note : proxy1 and proxy2 are both trusted proxies that + come in x-forwarded-for header, they both are migrated in + x-forwarded-by header. As 192.168.0.10 is an internal + proxy, it does not appear in x-forwarded-by. + x-forwarded-for is null because all the proxies are + trusted or internal. +

    +
    + +

    Advanced configuration with an untrusted proxy

    + +

    RemoteIpFilter configuration:

    +
         <filter>
    +       <filter-name>RemoteIpFilter</filter-name>
    +       <filter-class>org.apache.catalina.filters.RemoteIpFilter</filter-class>
    +       <init-param>
    +         <param-name>allowedInternalProxies</param-name>
    +         <param-value>192\.168\.0\.10|192\.168\.0\.11</param-value>
    +       </init-param>
    +       <init-param>
    +         <param-name>remoteIpHeader</param-name>
    +         <param-value>x-forwarded-for</param-value>
    +       </init-param>
    +       <init-param>
    +         <param-name>remoteIpProxiesHeader</param-name>
    +         <param-value>x-forwarded-by</param-value>
    +       </init-param>
    +       <init-param>
    +         <param-name>trustedProxies</param-name>
    +         <param-value>proxy1|proxy2</param-value>
    +       </init-param>
    +     </filter>
    +

    Request values:

    + + + + + + + + + + + + + + + + + + + + + +
    PropertyValue Before RemoteIpFilterValue After RemoteIpFilter
    request.remoteAddr 192.168.0.10 untrusted-proxy
    request.header['x-forwarded-for'] 140.211.11.130, untrusted-proxy, proxy1 140.211.11.130
    request.header['x-forwarded-by'] null proxy1
    + +

    + Note : x-forwarded-by holds the trusted proxy proxy1. + x-forwarded-by holds 140.211.11.130 because + untrusted-proxy is not trusted and thus, we cannot trust that + untrusted-proxy is the actual remote ip. + request.remoteAddr is untrusted-proxy that is an IP + verified by proxy1. +

    +
    + +

    Initialisation parameters

    + +

    The Remote IP Filter supports the + following initialisation parameters:

    + +
    + Attribute + + Description +
    remoteIpHeader +

    Name of the HTTP Header read by this valve that holds the list of + traversed IP addresses starting from the requesting client. If not + specified, the default of x-forwarded-for is used.

    +
    internalProxies +

    Regular expression (using java.util.regex) that a + proxy's IP address must match to be considered an internal proxy. + Internal proxies that appear in the remoteIpHeader will + be trusted and will not appear in the proxiesHeader + value. If not specified the default value of + 10\.\d{1,3}\.\d{1,3}\.\d{1,3}|192\.168\.\d{1,3}\.\d{1,3}|169\.254\.\d{1,3}\.\d{1,3}|127\.\d{1,3}\.\d{1,3}\.\d{1,3}|172\.1[6-9]{1}\.\d{1,3}\.\d{1,3}|172\.2[0-9]{1}\.\d{1,3}\.\d{1,3}|172\.3[0-1]{1}\.\d{1,3}\.\d{1,3}|0:0:0:0:0:0:0:1 + will be used.

    +
    proxiesHeader +

    Name of the HTTP header created by this valve to hold the list of + proxies that have been processed in the incoming + remoteIpHeader. If not specified, the default of + x-forwarded-by is used.

    +
    requestAttributesEnabled +

    Set to true to set the request attributes used by + AccessLog implementations to override the values returned by the + request for remote address, remote host, server port and protocol. + Request attributes are also used to enable the forwarded remote address + to be displayed on the status page of the Manager web application. + If not set, the default value of true will be used.

    +
    trustedProxies +

    Regular expression (using java.util.regex) that a + proxy's IP address must match to be considered an trusted proxy. + Trusted proxies that appear in the remoteIpHeader will + be trusted and will appear in the proxiesHeader value. + If not specified, no proxies will be trusted.

    +
    protocolHeader +

    Name of the HTTP Header read by this valve that holds the protocol + used by the client to connect to the proxy. If not specified, the + default of X-Forwarded-Proto is used.

    +
    portHeader +

    Name of the HTTP Header read by this valve that holds the port + used by the client to connect to the proxy. If not specified, the + default of null is used.

    +
    protocolHeaderHttpsValue +

    Value of the protocolHeader to indicate that it is + an HTTPS request. If not specified, the default of https is + used.

    +
    httpServerPort +

    Value returned by ServletRequest.getServerPort() + when the protocolHeader indicates http + protocol and no portHeader is present. If not + specified, the default of 80 is used.

    +
    httpsServerPort +

    Value returned by ServletRequest.getServerPort() + when the protocolHeader indicates https + protocol and no portHeader is present. If not + specified, the default of 443 is used.

    +
    changeLocalPort +

    If true, the value returned by + ServletRequest.getLocalPort() and + ServletRequest.getServerPort() is modified by the this + filter. If not specified, the default of false is used.

    +
    + + +
    + +

    Request Dumper Filter

    + +

    Introduction

    + +

    The Request Dumper Filter logs information from the request and response + objects and is intended to be used for debugging purposes. When using this + Filter, it is recommended that the + org.apache.catalina.filter.RequestDumperFilter logger is + directed to a dedicated file and that the + org.apache.juli.VerbatimFormatter is used.

    + +

    WARNING: Using this filter has side-effects. The + output from this filter includes any parameters included with the request. + The parameters will be decoded using the default platform encoding. Any + subsequent calls to request.setCharacterEncoding() within + the web application will have no effect.

    + +
    + +

    Filter Class Name

    + +

    The filter class name for the Request Dumper Filter is + org.apache.catalina.filters.RequestDumperFilter + .

    + +
    + +

    Initialisation parameters

    + +

    The Request Dumper Filter does not support any initialization + parameters.

    + +
    + +

    Sample Configuration

    + +

    The following entries in a web application's web.xml would enable the + Request Dumper filter for all requests for that web application. If the + entries were added to CATALINA_BASE/conf/web.xml, the Request + Dumper Filter would be enabled for all web applications.

    +
    <filter>
    +    <filter-name>requestdumper</filter-name>
    +    <filter-class>
    +        org.apache.catalina.filters.RequestDumperFilter
    +    </filter-class>
    +</filter>
    +<filter-mapping>
    +    <filter-name>requestdumper</filter-name>
    +    <url-pattern>*</url-pattern>
    +</filter-mapping>
    + +

    The following entries in CATALINA_BASE/conf/logging.properties would + create a separate log file for the Request Dumper Filter output.

    +
    # To this configuration below, 1request-dumper.org.apache.juli.FileHandler
    +# also needs to be added to the handlers property near the top of the file
    +1request-dumper.org.apache.juli.FileHandler.level = INFO
    +1request-dumper.org.apache.juli.FileHandler.directory = ${catalina.base}/logs
    +1request-dumper.org.apache.juli.FileHandler.prefix = request-dumper.
    +1request-dumper.org.apache.juli.FileHandler.encoding = UTF-8
    +1request-dumper.org.apache.juli.FileHandler.formatter = org.apache.juli.VerbatimFormatter
    +org.apache.catalina.filters.RequestDumperFilter.level = INFO
    +org.apache.catalina.filters.RequestDumperFilter.handlers = \
    +  1request-dumper.org.apache.juli.FileHandler
    +
    +

    Session Initializer Filter

    + +

    Introduction

    +

    The Session Initializer Filter initializes the javax.servlet.http.HttpSession + before the Request is processed. This is required for JSR-356 compliant WebSocket implementations, + if the HttpSession is needed during the HandShake phase.

    + +

    The Java API for WebSocket does not mandate that an HttpSession would + be initialized upon request, and thus javax.servlet.http.HttpServletRequest's + getSession() returns null if the HttpSession was not + initialized in advance.

    + +

    This filter solves that problem by initializing the HttpSession for any HttpServletRequest + that matches its url-pattern.

    +
    + +

    Filter Class Name

    +

    The filter class name for the Session Initializer Filter is + org.apache.catalina.filters.SessionInitializerFilter.

    +
    + +

    Initialisation parameters

    +

    The Session Initializer Filter does not support any initialization parameters.

    +
    + +

    Sample Configuration

    +

    The following entries in the Web Application Deployment Descriptor, web.xml, + would enable the Session Initializer Filter for requests that match the given URL pattern + (in this example, "/ws/*").

    + +
    <filter>
    +    <filter-name>SessionInitializer</filter-name>
    +    <filter-class>org.apache.catalina.filters.SessionInitializerFilter</filter-class>
    +</filter>
    +<filter-mapping>
    +    <filter-name>SessionInitializer</filter-name>
    +    <url-pattern>/ws/*</url-pattern>
    +</filter-mapping>
    +
    +

    Set Character Encoding Filter

    + +

    Introduction

    + +

    User agents don't always include character encoding information in + requests. Depending on the how the request is processed, usually the + default encoding of ISO-8859-1 is used. This is not always + desirable. This filter provides options for setting that encoding or + forcing it to a particular value. Essentially this filter calls + ServletRequest.setCharacterEncoding() method.

    + +

    Effectively the value set by this filter is used when parsing parameters + in a POST request, if parameter parsing occurs later than this filter. Thus + the order of filter mappings is important. Note that the encoding for GET + requests is not set here, but on a Connector. See + CharacterEncoding page in the FAQ for details.

    + +
    + +

    Filter Class Name

    + +

    The filter class name for the Set Character Encoding Filter is + org.apache.catalina.filters.SetCharacterEncodingFilter + .

    + +
    + +

    Initialisation parameters

    + +

    The Set Character Encoding Filter supports the following initialization + parameters:

    + +
    + Attribute + + Description +
    encoding +

    Name of the character encoding which should be set.

    +
    ignore +

    Determines if any character encoding specified by the user agent is + ignored. If this attribute is true, any value provided by + the user agent is ignored. If false, the encoding is only + set if the user agent did not specify an encoding. The default value + is false.

    +
    + +
    + +

    WebDAV Fix Filter

    + +

    Introduction

    + +

    Microsoft operating systems have two WebDAV clients. One is used with + port 80, the other is used for all other ports. The implementation used with + port 80 does not adhere to the WebDAV specification and fails when trying to + communicate with the Tomcat WebDAV Servlet. This Filter provides a fix for + this by forcing the use of the WebDAV implementation that works, even when + connecting via port 80.

    + +
    + +

    Filter Class Name

    + +

    The filter class name for the WebDAV Fix Filter is + org.apache.catalina.filters.WebdavFixFilter + .

    + +
    + +

    Initialisation parameters

    + +

    The WebDAV Fix Filter does not support any initialization parameters.

    + +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/globalresources.html b/tomcat/docs/config/globalresources.html new file mode 100644 index 0000000..ea231ba --- /dev/null +++ b/tomcat/docs/config/globalresources.html @@ -0,0 +1,262 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - The GlobalNamingResources Component

    The GlobalNamingResources Component

    Table of Contents

    Introduction

    + +

    The GlobalNamingResources element defines the global + JNDI resources for the Server.

    + +

    These resources are listed in the server's global JNDI resource context. + This context is distinct from the per-web-application JNDI contexts + described in + the JNDI Resources How-To. + The resources defined in this element are not visible in + the per-web-application contexts unless you explicitly link them with + <ResourceLink> elements. +

    + +

    Attributes

    + +

    Nested Components

    + +

    Special Features

    + + +

    Environment Entries

    + +

    You can configure named values that will be made visible to all + web applications as environment entry resources by nesting + <Environment> entries inside this element. For + example, you can create an environment entry like this:

    +
    <GlobalNamingResources ...>
    +  ...
    +  <Environment name="maxExemptions" value="10"
    +         type="java.lang.Integer" override="false"/>
    +  ...
    +</GlobalNamingResources>
    + +

    This is equivalent to the inclusion of the following element in the + web application deployment descriptor (/WEB-INF/web.xml): +

    +
    <env-entry>
    +  <env-entry-name>maxExemptions</env-entry-name>
    +  <env-entry-value>10</env-entry-value>
    +  <env-entry-type>java.lang.Integer</env-entry-type>
    +</env-entry>
    +

    but does not require modification of the deployment descriptor + to customize this value.

    + +

    The valid attributes for an <Environment> element + are as follows:

    + +
    + Attribute + + Description +
    description +

    Optional, human-readable description of this environment entry.

    +
    name +

    The name of the environment entry to be created, relative to the + java:comp/env context.

    +
    override +

    Set this to false if you do not want + an <env-entry> for the same environment entry name, + found in the web application deployment descriptor, to override the + value specified here. By default, overrides are allowed.

    +
    type +

    The fully qualified Java class name expected by the web application + for this environment entry. Must be a legal value for + <env-entry-type> in the web application deployment + descriptor.

    +
    value +

    The parameter value that will be presented to the application + when requested from the JNDI context. This value must be convertable + to the Java type defined by the type attribute.

    +
    + +
    + + +

    Resource Definitions

    + +

    You can declare the characteristics of resources + to be returned for JNDI lookups of <resource-ref> and + <resource-env-ref> elements in the web application + deployment descriptor by defining them in this element and then linking + them with <ResourceLink> + elements + in the <Context> element. + + You MUST also define any other needed parameters using + attributes on the Resource element, to configure + the object factory to be used (if not known to Tomcat already), and + the properties used to configure that object factory.

    + +

    For example, you can create a resource definition like this:

    +
    <GlobalNamingResources ...>
    +  ...
    +  <Resource name="jdbc/EmployeeDB" auth="Container"
    +            type="javax.sql.DataSource"
    +     description="Employees Database for HR Applications"/>
    +  ...
    +</GlobalNamingResources>
    + +

    This is equivalent to the inclusion of the following element in the + web application deployment descriptor (/WEB-INF/web.xml):

    +
    <resource-ref>
    +  <description>Employees Database for HR Applications</description>
    +  <res-ref-name>jdbc/EmployeeDB</res-ref-name>
    +  <res-ref-type>javax.sql.DataSource</res-ref-type>
    +  <res-auth>Container</res-auth>
    +</resource-ref>
    + +

    but does not require modification of the deployment + descriptor to customize this value.

    + +

    The valid attributes for a <Resource> element + are as follows:

    + +
    + Attribute + + Description +
    auth +

    Specify whether the web Application code signs on to the + corresponding resource manager programmatically, or whether the + Container will sign on to the resource manager on behalf of the + application. The value of this attribute must be + Application or Container. This + attribute is required if the web application + will use a <resource-ref> element in the web + application deployment descriptor, but is optional if the + application uses a <resource-env-ref> instead.

    +
    closeMethod +

    Name of the zero-argument method to call on a singleton resource when + it is no longer required. This is intended to speed up clean-up of + resources that would otherwise happen as part of garbage collection. + This attribute is ignored if the singleton attribute is + false. If not specified, no default is defined and no close method will + be called.

    +

    For Apache Commons DBCP 2 and Apache Tomcat JDBC connection pools + you can use closeMethod="close". Note that Apache Commons + DBCP 2 requires this to be set for a clean shutdown. When using the + default Tomcat connection pool (based on DBCP 2) Tomcat will set this + attribute automatically unless it is explictly set to the empty + string.

    +
    description +

    Optional, human-readable description of this resource.

    +
    name +

    The name of the resource to be created, relative to the + java:comp/env context.

    +
    scope +

    Specify whether connections obtained through this resource + manager can be shared. The value of this attribute must be + Shareable or Unshareable. By default, + connections are assumed to be shareable.

    +
    singleton +

    Specify whether this resource definition is for a singleton resource, + i.e. one where there is only a single instance of the resource. If this + attribute is true, multiple JNDI lookups for this resource + will return the same object. If this attribute is false, + multiple JNDI lookups for this resource will return different objects. + This attribute must be true for + javax.sql.DataSource resources to enable JMX registration + of the DataSource. The value of this attribute must be true + or false. By default, this attribute is true. +

    +
    type +

    The fully qualified Java class name expected by the web + application when it performs a lookup for this resource.

    +
    + + +
    + +
    +

    Use <ResourceLink> + elements to link resources from the global context into + per-web-application contexts. Here is an example of making a custom + factory available to an application, based on the example definition in the + + JNDI Resource How-To: +

    + +
    <Context>
    +  <ResourceLink
    +    name="bean/MyBeanFactory"
    +    global="bean/MyBeanFactory"
    +    type="com.mycompany.MyBean"
    +  />
    +</Context>
    + +
    + +

    Transaction

    + +

    You can declare the characteristics of the UserTransaction + to be returned for JNDI lookup for java:comp/UserTransaction. + You MUST define an object factory class to instantiate + this object as well as the needed resource parameters as attributes of the + Transaction + element, and the properties used to configure that object factory.

    + +

    The valid attributes for the <Transaction> element + are as follows:

    + +
    + Attribute + + Description +
    factory +

    The class name for the JNDI object factory.

    +
    + +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/host.html b/tomcat/docs/config/host.html new file mode 100644 index 0000000..74d8d23 --- /dev/null +++ b/tomcat/docs/config/host.html @@ -0,0 +1,635 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - The Host Container

    The Host Container

    Table of Contents

    Introduction

    + +

    The Host element represents a virtual host, + which is an association of a network name for a server (such as + "www.mycompany.com") with the particular server on which Tomcat is running. + For clients to be able to connect to a Tomcat server using its network name, + this name must be registered in the Domain Name Service (DNS) server + that manages the Internet domain you belong to - contact your Network + Administrator for more information.

    + +

    In many cases, System Administrators wish to associate more than + one network name (such as www.mycompany.com and + company.com) with the same virtual host and applications. + This can be accomplished using the Host + Name Aliases feature discussed below.

    + +

    One or more Host elements are nested inside an + Engine element. Inside the Host element, you + can nest Context elements for the web + applications associated with this virtual host. Exactly one of the Hosts + associated with each Engine MUST have a name matching the + defaultHost attribute of that Engine.

    + +

    Clients normally use host names to identify the server they wish to connect + to. This host name is also included in the HTTP request headers. Tomcat + extracts the host name from the HTTP headers and looks for a + Host with a matching name. If no match is found, the request + is routed to the default host. The name of the default host does not have to + match a DNS name (although it can) since any request where the DNS name does + not match the name of a Host element will be routed to the + default host.

    + +

    The description below uses the variable name $CATALINA_BASE to refer the + base directory against which most relative paths are resolved. If you have + not configured Tomcat for multiple instances by setting a CATALINA_BASE + directory, then $CATALINA_BASE will be set to the value of $CATALINA_HOME, + the directory into which you have installed Tomcat.

    + +

    Attributes

    + +

    Common Attributes

    + +

    All implementations of Host + support the following attributes:

    + +
    + Attribute + + Description +
    appBase +

    The Application Base directory for this virtual host. + This is the pathname of a directory that may contain web applications + to be deployed on this virtual host. You may specify an + absolute pathname, or a pathname that is relative to the + $CATALINA_BASE directory. See + Automatic Application + Deployment for more information on automatic recognition and + deployment of web applications. If not specified, the default of + webapps will be used.

    +
    xmlBase +

    The XML Base directory for this virtual host. + This is the pathname of a directory that may contain context XML + descriptors to be deployed on this virtual host. You may specify an + absolute pathname for this directory, or a pathname that is relative + to the $CATALINA_BASE directory. See + Automatic Application + Deployment for more information on automatic recognition and + deployment of web applications. If not specified the default of + conf/<engine_name>/<host_name> will be used.

    +
    createDirs +

    If set to true, Tomcat will attempt to create the directories defined + by the attributes appBase and xmlBase during + the startup phase. The default value is true. If set to + true, and directory creation fails, an error message will be printed out + but will not halt the startup sequence.

    +
    autoDeploy +

    This flag value indicates if Tomcat should check periodically for new + or updated web applications while Tomcat is running. If true, Tomcat + periodically checks the appBase and xmlBase + directories and deploys any new web applications or context XML + descriptors found. Updated web applications or context XML descriptors + will trigger a reload of the web application. The flag's value defaults + to true. See + Automatic Application + Deployment for more information.

    +
    backgroundProcessorDelay +

    This value represents the delay in seconds between the + invocation of the backgroundProcess method on this host and + its child containers, including all contexts. + Child containers will not be invoked if their delay value is not + negative (which would mean they are using their own processing + thread). Setting this to a positive value will cause + a thread to be spawn. After waiting the specified amount of time, + the thread will invoke the backgroundProcess method on this host + and all its child containers. A host will use background processing to + perform live web application deployment related tasks. If not + specified, the default value for this attribute is -1, which means + the host will rely on the background processing setting of its parent + engine.

    +
    className +

    Java class name of the implementation to use. This class must + implement the org.apache.catalina.Host interface. + If not specified, the standard value (defined below) will be used.

    +
    deployIgnore +

    A regular expression defining paths to ignore when + autoDeploy and deployOnStartup are set. This + allows you to keep your configuration in a version control system, for + example, and not deploy a .svn or CVS folder that happens to be in the + appBase.

    +

    This regular expression is relative to appBase. It is + also anchored, meaning the match is performed against the + entire file/directory name. So, foo matches only a file or + directory named foo but not foo.war, + foobar, or myfooapp. To match anything with + "foo", you could use .*foo.*.

    +

    See Automatic Application + Deployment for more information.

    +
    deployOnStartup +

    This flag value indicates if web applications from this host should + be automatically deployed when Tomcat starts. The flag's value defaults + to true. See + Automatic Application + Deployment for more information.

    +
    failCtxIfServletStartFails +

    Set to true to have each child contexts fail its startup + if any of its servlet that has load-on-startup >=0 fails its own + startup.

    +

    Each child context may override this attribute.

    +

    If not specified, the default value of false is + used.

    +
    name +

    Usually the network name of this virtual host, as registered in your + Domain Name Service server. Regardless of the case used to + specify the host name, Tomcat will convert it to lower case internally. + One of the Hosts nested within an Engine MUST + have a name that matches the defaultHost setting for that + Engine. See Host Name Aliases for + information on how to assign more than one network name to the same + virtual host. If the name takes the form of *.domainname + (e.g. *.apache.org) then it will be treated as a match for + any host in that domain unless a host that has an exactly matching name + is found.

    +
    startStopThreads +

    The number of threads this Host will use to start + child Context elements in parallel. The same + thread pool will be used to deploy new + Contexts if automatic deployment is being + used. The special value of 0 will result in the value of + Runtime.getRuntime().availableProcessors() being used. + Negative values will result in + Runtime.getRuntime().availableProcessors() + value being + used unless this is less than 1 in which case 1 thread will be used. If + not specified, the default value of 1 will be used.

    +
    undeployOldVersions +

    This flag determines if Tomcat, as part of the auto deployment + process, will check for old, unused versions of web applications + deployed using parallel deployment and, if any are found, remove them. + This flag only applies if autoDeploy is true. If not + specified the default value of false will be used.

    +
    + +
    + + +

    Standard Implementation

    + +

    The standard implementation of Host is + org.apache.catalina.core.StandardHost. + It supports the following additional attributes (in addition to the + common attributes listed above):

    + +
    + Attribute + + Description +
    copyXML +

    Set to true if you want a context XML descriptor + embedded inside the application (located at + /META-INF/context.xml) to be copied to xmlBase + when the application is deployed. On subsequent starts, the copied + context XML descriptor will be used in preference to any context XML + descriptor embedded inside the application even if the descriptor + embedded inside the application is more recent. The flag's value + defaults to false. Note if deployXML + is false, this attribute will have no effect.

    +
    deployXML +

    Set to false if you want to disable parsing the context + XML descriptor embedded inside the application (located at + /META-INF/context.xml). Security conscious environments + should set this to false to prevent applications from + interacting with the container's configuration. The administrator will + then be responsible for providing an external context configuration + file, and putting it in the location defined by the + xmlBase attribute. If this flag is false, + a descriptor is located at /META-INF/context.xml and no + descriptor is present in xmlBase then the context will + fail to start in case the descriptor contains necessary configuration + for secure deployment (such as a RemoteAddrValve) which should not be + ignored. The flag's value defaults to true unless a + security manager is enabled when the default is false. + When running under a security manager this may be enabled on a per web + application basis by granting the + org.apache.catalina.security.DeployXmlPermission to the web + application. The Manager and Host Manager applications are granted this + permission by default so that they continue to work when running under a + security manager.

    +
    errorReportValveClass +

    Java class name of the error reporting valve which will be used + by this Host. The responsibility of this valve is to output error + reports. Setting this property allows to customize the look of the + error pages which will be generated by Tomcat. This class must + implement the + org.apache.catalina.Valve interface. If none is specified, + the value org.apache.catalina.valves.ErrorReportValve + will be used by default.

    +
    unpackWARs +

    Set to true if you want web applications that are + placed in the appBase directory as web application + archive (WAR) files to be unpacked into a corresponding disk directory + structure, false to run such web applications directly + from a WAR file. See + Automatic Application + Deployment for more information.

    +

    Note: If Tomcat expands the WAR file then it will add a file + (/META-INF/war-tracking) to the unpacked directory + structure which it uses to detect changes in the WAR file while Tomcat + is not running. Any such change will trigger the deletion of the + expanded directory and the deployment of the updated WAR file when + Tomcat next starts.

    +

    Note: Running with this option set to false will incur + a performance penalty. To avoid a significant performance penalty, the + web application should be configured such that class scanning for + Servlet 3.0+ pluggability features is not required. Users may also wish + to consider the ExtractingRoot + Resources implementation.

    +
    workDir +

    Pathname to a scratch directory to be used by applications for + this Host. Each application will have its own sub directory with + temporary read-write use. Configuring a Context workDir will override + use of the Host workDir configuration. This directory will be made + visible to servlets in the web application by a servlet context + attribute (of type java.io.File) named + javax.servlet.context.tempdir as described in the + Servlet Specification. If not specified, a suitable directory + underneath $CATALINA_BASE/work will be provided.

    +
    + +
    + + +

    Nested Components

    + +

    You can nest one or more Context elements + inside this Host element, each representing a different web + application associated with this virtual host.

    + +

    You can nest at most one instance of the following utility components + by nesting a corresponding element inside your Host + element:

    +
      +
    • Realm - + Configure a realm that will allow its + database of users, and their associated roles, to be shared across all + Contexts nested inside this Host (unless + overridden by a Realm configuration + at a lower level).
    • +
    + +

    Special Features

    + + +

    Logging

    + +

    A host is associated with the + org.apache.catalina.core.ContainerBase.[engine_name].[host_name] + log category. Note that the brackets are part of the name, + don't omit them.

    + +
    + + +

    Access Logs

    + +

    When you run a web server, one of the output files normally generated + is an access log, which generates one line of information for + each request processed by the server, in a standard format. Catalina + includes an optional Valve implementation that + can create access logs in the same standard format created by web servers, + or in any number of custom formats.

    + +

    You can ask Catalina to create an access log for all requests + processed by an Engine, + Host, or Context + by nesting a Valve element like this:

    + +
    <Host name="localhost" ...>
    +  ...
    +  <Valve className="org.apache.catalina.valves.AccessLogValve"
    +         prefix="localhost_access_log" suffix=".txt"
    +         pattern="common"/>
    +  ...
    +</Host>
    + +

    See Access Logging Valves + for more information on the configuration attributes that are + supported.

    + +
    + + +

    Automatic Application Deployment

    + +

    If you are using the standard Host implementation with + default settings then applications in the appBase or with context + files in the configBase are automatically deployed when Tomcat + starts (the deployOnStartup property defaults to + true) and reloaded or redeployed (as appropriate) when a change + is detected while Tomcat is running (the autoDeploy attribute + also defaults to true).

    + +

    deployOnStartup and autoDeploy trigger + execution of exactly the same code so the behaviour is very similar. + However, there is one key difference. When Tomcat starts it has no knowledge + of which files are the same, which have been changed and which are new. It + therefore treats all files as new. While Tomcat is running, it can + differentiate between unchanged, modified and new files. This leads to some + differences in behaviour between files being modified while Tomcat is + running and files being modified while Tomcat is stopped.

    + +

    When you use automatic deployment, related files (a web application may + have a context.xml file, a WAR and a directory) that exist in the + Host's appBase and/or configBase + must conform to the expected naming + convention. In short, this means files for the same web application must + share the same base name.

    + +

    The automatic deployment process identifies new and/or modified web + applications using the following search order:

    + +
      +
    1. Web applications with a context.xml file located in the Host's + configBase.
    2. +
    3. Web applications with a WAR file located in the Host's + appBase that have not already been identified during the scan for + context.xml files.
    4. +
    5. Web applications with a directory located in the Host's + appBase that have not already been identified during the scans + for context.xml and/or WAR files.
    6. +
    + +

    When autoDeploy is true, the automatic + deployment process will monitor the deployed web applications for changes. + Depending on exactly what changes, the web application will either be + re-deployed or reloaded. Re-deployment involves the creation of a new web + application and, if using the standard session manager, user sessions will + not be retained. Reloading uses the existing web application but re-parses + the web.xml and reloads any classes. If using the standard session manager, + user sessions will be persisted.

    + +

    Users may add to the files that the automatic deployment process monitors + for reloading (i.e. any change to one of these files triggers a reload of + the web application) by adding a WatchedResources element to the + context.xml file. See the + Context documentation for + further details.

    + +

    When using automatic deployment, the docBase defined by + an XML Context file should be outside of the + appBase directory. If this is not the case, difficulties + may be experienced deploying the web application or the application may + be deployed twice. The deployIgnore attribute can be used + to avoid this situation.

    + +

    Note that if you are defining contexts explicitly in server.xml, you + should probably turn off automatic application deployment or specify + deployIgnore carefully. Otherwise, the web applications + will each be deployed twice, and that may cause problems for the + applications.

    + +

    There are many possible combinations of settings, new files, changed + files and deleted files. A separate page describes the + expected behaviour of the automatic + deployment process in many of these scenarios.

    + +
    + + +

    Host Name Aliases

    + +

    In many server environments, Network Administrators have configured + more than one network name (in the Domain Name Service (DNS) + server), that resolve to the IP address of the same server. Normally, + each such network name would be configured as a separate + Host element in conf/server.xml, each + with its own set of web applications.

    + +

    However, in some circumstances, it is desirable that two or more + network names should resolve to the same virtual host, + running the same set of applications. A common use case for this + scenario is a corporate web site, where it is desirable that users + be able to utilize either www.mycompany.com or + company.com to access exactly the same content and + applications.

    + +

    This is accomplished by utilizing one or more Alias + elements nested inside your Host element. For + example:

    +
    <Host name="www.mycompany.com" ...>
    +  ...
    +  <Alias>mycompany.com</Alias>
    +  ...
    +</Host>
    + +

    In order for this strategy to be effective, all of the network names + involved must be registered in your DNS server to resolve to the + same computer that is running this instance of Catalina.

    + +

    Aliases may also use the wildcard form (*.domainname) + permitted for the name attribute of a + Host.

    + +
    + + +

    Lifecycle Listeners

    + +

    If you have implemented a Java object that needs to know when this + Host is started or stopped, you can declare it by + nesting a Listener element inside this element. The + class name you specify must implement the + org.apache.catalina.LifecycleListener interface, and + it will be notified about the occurrence of the corresponding + lifecycle events. Configuration of such a listener looks like this:

    + +
    <Host name="localhost" ...>
    +  ...
    +  <Listener className="com.mycompany.mypackage.MyListener" ... >
    +  ...
    +</Host>
    + +

    Note that a Listener can have any number of additional properties + that may be configured from this element. Attribute names are matched + to corresponding JavaBean property names using the standard property + method naming patterns.

    + +
    + + +

    Request Filters

    + +

    You can ask Catalina to check the IP address, or host name, on every + incoming request directed to the surrounding + Engine, Host, or + Context element. The remote address or name + will be checked against configured "accept" and/or "deny" + filters, which are defined using java.util.regex Regular + Expression syntax. Requests that come from locations that are + not accepted will be rejected with an HTTP "Forbidden" error. + Example filter declarations:

    + +
    <Host name="localhost" ...>
    +  ...
    +  <Valve className="org.apache.catalina.valves.RemoteHostValve"
    +         allow=".*\.mycompany\.com|www\.yourcompany\.com"/>
    +  <Valve className="org.apache.catalina.valves.RemoteAddrValve"
    +         deny="192\.168\.1\.\d+"/>
    +  ...
    +</Host>
    + +

    See Remote Address Filter + and Remote Host Filter for + more information about the configuration options that are supported.

    + +
    + + +

    Single Sign On

    + +

    In many environments, but particularly in portal environments, it + is desirable to have a user challenged to authenticate themselves only + once over a set of web applications deployed on a particular virtual + host. This can be accomplished by nesting an element like this inside + the Host element for this virtual host:

    + +
    <Host name="localhost" ...>
    +  ...
    +  <Valve className="org.apache.catalina.authenticator.SingleSignOn"/>
    +  ...
    +</Host>
    + +

    The Single Sign On facility operates according to the following rules: +

    +
      +
    • All web applications configured for this virtual host must share the + same Realm. In practice, that means you can + nest the Realm element inside this Host element (or the surrounding + Engine element), but not inside a + Context element for one of the involved + web applications.
    • +
    • As long as the user accesses only unprotected resources in any of the + web applications on this virtual host, they will not be challenged + to authenticate themselves.
    • +
    • As soon as the user accesses a protected resource in + any web application associated with this virtual + host, the user will be challenged to authenticate himself or herself, + using the login method defined for the web application currently + being accessed.
    • +
    • Once authenticated, the roles associated with this user will be + utilized for access control decisions across all + of the associated web applications, without challenging the user + to authenticate themselves to each application individually.
    • +
    • As soon as the user logs out of one web application (for example, + by invalidating the corresponding session if form + based login is used), the user's sessions in all + web applications will be invalidated. Any subsequent attempt to + access a protected resource in any application will require the + user to authenticate himself or herself again.
    • +
    • The Single Sign On feature utilizes HTTP cookies to transmit a token + that associates each request with the saved user identity, so it can + only be utilized in client environments that support cookies.
    • +
    + +
    + + +

    User Web Applications

    + +

    Many web servers can automatically map a request URI starting with + a tilde character ("~") and a username to a directory (commonly named + public_html) in that user's home directory on the server. + You can accomplish the same thing in Catalina by using a special + Listener element like this (on a Unix system that + uses the /etc/passwd file to identify valid users):

    + +
    <Host name="localhost" ...>
    +  ...
    +  <Listener className="org.apache.catalina.startup.UserConfig"
    +            directoryName="public_html"
    +            userClass="org.apache.catalina.startup.PasswdUserDatabase"/>
    +  ...
    +</Host>
    + +

    On a server where /etc/passwd is not in use, you can + request Catalina to consider all directories found in a specified base + directory (such as c:\Homes in this example) to be + considered "user home" directories for the purposes of this directive:

    + +
    <Host name="localhost" ...>
    +  ...
    +  <Listener className="org.apache.catalina.startup.UserConfig"
    +            directoryName="public_html"
    +            homeBase="c:\Homes"
    +            userClass="org.apache.catalina.startup.HomesUserDatabase"/>
    +  ...
    +</Host>
    + +

    If a user home directory has been set up for a user named + craigmcc, then its contents will be visible from a + client browser by making a request to a URL like:

    + +
    http://www.mycompany.com:8080/~craigmcc
    + +

    Successful use of this feature requires recognition of the following + considerations:

    +
      +
    • Each user web application will be deployed with characteristics + established by the global and host level default context settings.
    • +
    • It is legal to include more than one instance of this Listener + element. This would only be useful, however, in circumstances + where you wanted to configure more than one "homeBase" directory.
    • +
    • The operating system username under which Catalina is executed + MUST have read access to each user's web application directory, + and all of its contents.
    • +
    + +
    + +

    Custom context.xml and web.xml

    +

    You can override the default values found in conf/context.xml and + conf/web.xml files from $CATALINA_BASE for each virtual host. + Tomcat will look for files named context.xml.default and web.xml.default + in the directory specified by xmlBase and merge the files into + those found in the default ones.

    +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/http.html b/tomcat/docs/config/http.html new file mode 100644 index 0000000..796ac2d --- /dev/null +++ b/tomcat/docs/config/http.html @@ -0,0 +1,1682 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - The HTTP Connector

    The HTTP Connector

    Table of Contents

    Introduction

    + +

    The HTTP Connector element represents a + Connector component that supports the HTTP/1.1 protocol. + It enables Catalina to function as a stand-alone web server, in addition + to its ability to execute servlets and JSP pages. A particular instance + of this component listens for connections on a specific TCP port number + on the server. One or more such Connectors can be + configured as part of a single Service, each + forwarding to the associated Engine to perform + request processing and create the response.

    + +

    If you wish to configure the Connector that is used + for connections to web servers using the AJP protocol (such as the + mod_jk 1.2.x connector for Apache 1.3), please refer to the + AJP Connector documentation.

    + +

    Each incoming request requires + a thread for the duration of that request. If more simultaneous requests + are received than can be handled by the currently available request + processing threads, additional threads will be created up to the + configured maximum (the value of the maxThreads attribute). + If still more simultaneous requests are received, they are stacked up + inside the server socket created by the Connector, up to + the configured maximum (the value of the acceptCount + attribute). Any further simultaneous requests will receive "connection + refused" errors, until resources are available to process them.

    + +

    Attributes

    + +

    Common Attributes

    + +

    All implementations of Connector + support the following attributes:

    + +
    + Attribute + + Description +
    allowTrace +

    A boolean value which can be used to enable or disable the TRACE + HTTP method. If not specified, this attribute is set to false.

    +
    asyncTimeout +

    The default timeout for asynchronous requests in milliseconds. If not + specified, this attribute is set to the Servlet specification default of + 30000 (30 seconds).

    +
    defaultSSLHostConfigName +

    The name of the default SSLHostConfig that will be + used for secure connections (if this connector is configured for secure + connections) if the client connection does not provide SNI or if the SNI + is provided but does not match any configured + SSLHostConfig. If not specified the default value of + _default_ will be used.

    +
    enableLookups +

    Set to true if you want calls to + request.getRemoteHost() to perform DNS lookups in + order to return the actual host name of the remote client. Set + to false to skip the DNS lookup and return the IP + address in String form instead (thereby improving performance). + By default, DNS lookups are disabled.

    +
    maxHeaderCount +

    The maximum number of headers in a request that are allowed by the + container. A request that contains more headers than the specified limit + will be rejected. A value of less than 0 means no limit. + If not specified, a default of 100 is used.

    +
    maxParameterCount +

    The maximum number of parameter and value pairs (GET plus POST) which + will be automatically parsed by the container. Parameter and value pairs + beyond this limit will be ignored. A value of less than 0 means no limit. + If not specified, a default of 10000 is used. Note that + FailedRequestFilter filter can be + used to reject requests that hit the limit.

    +
    maxPostSize +

    The maximum size in bytes of the POST which will be handled by + the container FORM URL parameter parsing. The limit can be disabled by + setting this attribute to a value less than zero. If not specified, this + attribute is set to 2097152 (2 megabytes). Note that the + FailedRequestFilter + can be used to reject requests that exceed this limit.

    +
    maxSavePostSize +

    The maximum size in bytes of the POST which will be saved/buffered by + the container during FORM or CLIENT-CERT authentication. For both types + of authentication, the POST will be saved/buffered before the user is + authenticated. For CLIENT-CERT authentication, the POST is buffered for + the duration of the SSL handshake and the buffer emptied when the request + is processed. For FORM authentication the POST is saved whilst the user + is re-directed to the login form and is retained until the user + successfully authenticates or the session associated with the + authentication request expires. The limit can be disabled by setting this + attribute to -1. Setting the attribute to zero will disable the saving of + POST data during authentication. If not specified, this attribute is set + to 4096 (4 kilobytes).

    +
    parseBodyMethods +

    A comma-separated list of HTTP methods for which request + bodies using application/x-www-form-urlencoded will be parsed + for request parameters identically to POST. This is useful in RESTful + applications that want to support POST-style semantics for PUT requests. + Note that any setting other than POST causes Tomcat + to behave in a way that goes against the intent of the servlet + specification. + The HTTP method TRACE is specifically forbidden here in accordance + with the HTTP specification. + The default is POST

    +
    port +

    The TCP port number on which this Connector + will create a server socket and await incoming connections. Your + operating system will allow only one server application to listen + to a particular port number on a particular IP address. If the special + value of 0 (zero) is used, then Tomcat will select a free port at random + to use for this connector. This is typically only useful in embedded and + testing applications.

    +
    protocol +

    Sets the protocol to handle incoming traffic. The default value is + HTTP/1.1 which uses an auto-switching mechanism to select + either a Java NIO based connector or an APR/native based connector. + If the PATH (Windows) or LD_LIBRARY_PATH (on + most unix systems) environment variables contain the Tomcat native + library, and the AprLifecycleListener that is used to + initialize APR has its useAprConnector attribute set to + true, the APR/native connector will be used. If the native library + cannot be found or the attribute is not configured, the Java NIO based + connector will be used. Note that the APR/native connector has different + settings for HTTPS than the Java connectors.
    + To use an explicit protocol rather than rely on the auto-switching + mechanism described above, the following values may be used:
    + org.apache.coyote.http11.Http11NioProtocol - + non blocking Java NIO connector
    + org.apache.coyote.http11.Http11Nio2Protocol - + non blocking Java NIO2 connector
    + org.apache.coyote.http11.Http11AprProtocol - + the APR/native connector.
    + Custom implementations may also be used.
    + Take a look at our Connector + Comparison chart. The configuration for both Java connectors is + identical, for http and https.
    + For more information on the APR connector and APR specific SSL settings + please visit the APR documentation +

    +
    proxyName +

    If this Connector is being used in a proxy + configuration, configure this attribute to specify the server name + to be returned for calls to request.getServerName(). + See Proxy Support for more + information.

    +
    proxyPort +

    If this Connector is being used in a proxy + configuration, configure this attribute to specify the server port + to be returned for calls to request.getServerPort(). + See Proxy Support for more + information.

    +
    redirectPort +

    If this Connector is supporting non-SSL + requests, and a request is received for which a matching + <security-constraint> requires SSL transport, + Catalina will automatically redirect the request to the port + number specified here.

    +
    scheme +

    Set this attribute to the name of the protocol you wish to have + returned by calls to request.getScheme(). For + example, you would set this attribute to "https" + for an SSL Connector. The default value is "http". +

    +
    secure +

    Set this attribute to true if you wish to have + calls to request.isSecure() to return true + for requests received by this Connector. You would want this on an + SSL Connector or a non SSL connector that is receiving data from a + SSL accelerator, like a crypto card, a SSL appliance or even a webserver. + The default value is false.

    +
    sendReasonPhrase +

    Set this attribute to true if you wish to have + a reason phrase in the response. + The default value is false.

    +

    Note: This option is deprecated and will be removed + in Tomcat 9. The reason phrase will not be sent.

    +
    URIEncoding +

    This specifies the character encoding used to decode the URI bytes, + after %xx decoding the URL. If not specified, UTF-8 will be used unless + the org.apache.catalina.STRICT_SERVLET_COMPLIANCE + system property is set to true + in which case ISO-8859-1 will be used.

    +
    useBodyEncodingForURI +

    This specifies if the encoding specified in contentType should be used + for URI query parameters, instead of using the URIEncoding. This + setting is present for compatibility with Tomcat 4.1.x, where the + encoding specified in the contentType, or explicitly set using + Request.setCharacterEncoding method was also used for the parameters from + the URL. The default value is false. +

    +

    Notes: 1) This setting is applied only to the + query string of a request. Unlike URIEncoding it does not + affect the path portion of a request URI. 2) If request character + encoding is not known (is not provided by a browser and is not set by + SetCharacterEncodingFilter or a similar filter using + Request.setCharacterEncoding method), the default encoding is always + "ISO-8859-1". The URIEncoding setting has no effect on + this default. +

    +
    useIPVHosts +

    Set this attribute to true to cause Tomcat to use + the IP address that the request was received on to determine the Host + to send the request to. The default value is false.

    +
    xpoweredBy +

    Set this attribute to true to cause Tomcat to advertise + support for the Servlet specification using the header recommended in the + specification. The default value is false.

    +
    + +
    + +

    Standard Implementation

    + +

    The standard HTTP connectors (NIO, NIO2 and APR/native) all support the + following attributes in addition to the common Connector attributes listed + above.

    + +
    + Attribute + + Description +
    acceptCount +

    The maximum queue length for incoming connection requests when + all possible request processing threads are in use. Any requests + received when the queue is full will be refused. The default + value is 100.

    +
    acceptorThreadCount +

    The number of threads to be used to accept connections. Increase this + value on a multi CPU machine, although you would never really need more + than 2. Also, with a lot of non keep alive connections, you + might want to increase this value as well. Default value is + 1.

    +
    acceptorThreadPriority +

    The priority of the acceptor threads. The threads used to accept + new connections. The default value is 5 (the value of the + java.lang.Thread.NORM_PRIORITY constant). See the JavaDoc + for the java.lang.Thread class for more details on what + this priority means.

    +
    address +

    For servers with more than one IP address, this attribute specifies + which address will be used for listening on the specified port. By + default, the connector will listen all local addresses. Unless the JVM is + configured otherwise using system properties, the Java based connectors + (NIO, NIO2) will listen on both IPv4 and IPv6 addresses when configured + with either 0.0.0.0 or ::. The APR/native + connector will only listen on IPv4 addresses if configured with + 0.0.0.0 and will listen on IPv6 addresses (and optionally + IPv4 addresses depending on the setting of ipv6onlyv6) if + configured with ::.

    +
    allowHostHeaderMismatch +

    By default Tomcat will allow requests that specify a host in the + request line but specify a different host in the host header. This + check can be enabled by setting this attribute to false. If + not specified, the default is true.

    +
    allowedTrailerHeaders +

    By default Tomcat will ignore all trailer headers when processing + chunked input. For a header to be processed, it must be added to this + comma-separated list of header names.

    +
    bindOnInit +

    Controls when the socket used by the connector is bound. By default it + is bound when the connector is initiated and unbound when the connector is + destroyed. If set to false, the socket will be bound when the + connector is started and unbound when it is stopped.

    +
    clientCertProvider +

    When client certificate information is presented in a form other than + instances of java.security.cert.X509Certificate it needs to + be converted before it can be used and this property controls which JSSE + provider is used to perform the conversion. For example it is used with + the AJP connectors, the HTTP APR connector and + with the + org.apache.catalina.valves.SSLValve. If not specified, the default + provider will be used.

    +
    compressibleMimeType +

    The value is a comma separated list of MIME types for which HTTP + compression may be used. + The default value is + + text/html,text/xml,text/plain,text/css,text/javascript,application/javascript,application/json,application/xml + . +

    +
    compression +

    The Connector may use HTTP/1.1 GZIP compression in + an attempt to save server bandwidth. The acceptable values for the + parameter is "off" (disable compression), "on" (allow compression, which + causes text data to be compressed), "force" (forces compression in all + cases), or a numerical integer value (which is equivalent to "on", but + specifies the minimum amount of data before the output is compressed). If + the content-length is not known and compression is set to "on" or more + aggressive, the output will also be compressed. If not specified, this + attribute is set to "off".

    +

    Note: There is a tradeoff between using compression (saving + your bandwidth) and using the sendfile feature (saving your CPU cycles). + If the connector supports the sendfile feature, e.g. the NIO connector, + using sendfile will take precedence over compression. The symptoms will + be that static files greater that 48 Kb will be sent uncompressed. + You can turn off sendfile by setting useSendfile attribute + of the connector, as documented below, or change the sendfile usage + threshold in the configuration of the + DefaultServlet in the default + conf/web.xml or in the web.xml of your web + application. +

    +
    compressionMinSize +

    If compression is set to "on" then this attribute + may be used to specify the minimum amount of data before the output is + compressed. If not specified, this attribute is defaults to "2048".

    +
    connectionLinger +

    The number of seconds during which the sockets used by this + Connector will linger when they are closed. The default + value is -1 which disables socket linger.

    +
    connectionTimeout +

    The number of milliseconds this Connector will wait, + after accepting a connection, for the request URI line to be + presented. Use a value of -1 to indicate no (i.e. infinite) timeout. + The default value is 60000 (i.e. 60 seconds) but note that the standard + server.xml that ships with Tomcat sets this to 20000 (i.e. 20 seconds). + Unless disableUploadTimeout is set to false, + this timeout will also be used when reading the request body (if any).

    +
    connectionUploadTimeout +

    Specifies the timeout, in milliseconds, to use while a data upload is + in progress. This only takes effect if + disableUploadTimeout is set to false. +

    +
    disableUploadTimeout +

    This flag allows the servlet container to use a different, usually + longer connection timeout during data upload. If not specified, this + attribute is set to true which disables this longer timeout. +

    +
    executor +

    A reference to the name in an Executor + element. If this attribute is set, and the named executor exists, the + connector will use the executor, and all the other thread attributes will + be ignored. Note that if a shared executor is not specified for a + connector then the connector will use a private, internal executor to + provide the thread pool.

    +
    executorTerminationTimeoutMillis +

    The time that the private internal executor will wait for request + processing threads to terminate before continuing with the process of + stopping the connector. If not set, the default is 5000 (5 + seconds).

    +
    keepAliveTimeout +

    The number of milliseconds this Connector will wait + for another HTTP request before closing the connection. The default value + is to use the value that has been set for the + connectionTimeout attribute. + Use a value of -1 to indicate no (i.e. infinite) timeout.

    +
    maxConnections +

    The maximum number of connections that the server will accept and + process at any given time. When this number has been reached, the server + will accept, but not process, one further connection. This additional + connection be blocked until the number of connections being processed + falls below maxConnections at which point the server will + start accepting and processing new connections again. Note that once the + limit has been reached, the operating system may still accept connections + based on the acceptCount setting. The default value varies by + connector type. For NIO and NIO2 the default is 10000. + For APR/native, the default is 8192.

    +

    Note that for APR/native on Windows, the configured value will be + reduced to the highest multiple of 1024 that is less than or equal to + maxConnections. This is done for performance reasons.
    + If set to a value of -1, the maxConnections feature is disabled + and connections are not counted.

    +
    maxCookieCount +

    The maximum number of cookies that are permitted for a request. A value + of less than zero means no limit. If not specified, a default value of 200 + will be used.

    +
    maxExtensionSize +

    Limits the total length of chunk extensions in chunked HTTP requests. + If the value is -1, no limit will be imposed. If not + specified, the default value of 8192 will be used.

    +
    maxHttpHeaderSize +

    The maximum size of the request and response HTTP header, specified + in bytes. If not specified, this attribute is set to 8192 (8 KB).

    +
    maxKeepAliveRequests +

    The maximum number of HTTP requests which can be pipelined until + the connection is closed by the server. Setting this attribute to 1 will + disable HTTP/1.0 keep-alive, as well as HTTP/1.1 keep-alive and + pipelining. Setting this to -1 will allow an unlimited amount of + pipelined or keep-alive HTTP requests. + If not specified, this attribute is set to 100.

    +
    maxSwallowSize +

    The maximum number of request body bytes (excluding transfer encoding + overhead) that will be swallowed by Tomcat for an aborted upload. An + aborted upload is when Tomcat knows that the request body is going to be + ignored but the client still sends it. If Tomcat does not swallow the body + the client is unlikely to see the response. If not specified the default + of 2097152 (2 megabytes) will be used. A value of less than zero indicates + that no limit should be enforced.

    +
    maxThreads +

    The maximum number of request processing threads to be created + by this Connector, which therefore determines the + maximum number of simultaneous requests that can be handled. If + not specified, this attribute is set to 200. If an executor is associated + with this connector, this attribute is ignored as the connector will + execute tasks using the executor rather than an internal thread pool. Note + that if an executor is configured any value set for this attribute will be + recorded correctly but it will be reported (e.g. via JMX) as + -1 to make clear that it is not used.

    +
    maxTrailerSize +

    Limits the total length of trailing headers in the last chunk of + a chunked HTTP request. If the value is -1, no limit will be + imposed. If not specified, the default value of 8192 will be + used.

    +
    minSpareThreads +

    The minimum number of threads always kept running. This includes both + active and idle threads. If not specified, the default of 10 + is used. If an executor is associated with this connector, this attribute + is ignored as the connector will execute tasks using the executor rather + than an internal thread pool. Note that if an executor is configured any + value set for this attribute will be recorded correctly but it will be + reported (e.g. via JMX) as -1 to make clear that it is not + used.

    +
    noCompressionUserAgents +

    The value is a regular expression (using java.util.regex) + matching the user-agent header of HTTP clients for which + compression should not be used, + because these clients, although they do advertise support for the + feature, have a broken implementation. + The default value is an empty String (regexp matching disabled).

    +
    processorCache +

    The protocol handler caches Processor objects to speed up performance. + This setting dictates how many of these objects get cached. + -1 means unlimited, default is 200. If not using + Servlet 3.0 asynchronous processing, a good default is to use the same as + the maxThreads setting. If using Servlet 3.0 asynchronous processing, a + good default is to use the larger of maxThreads and the maximum number of + expected concurrent requests (synchronous and asynchronous).

    +
    rejectIllegalHeaderName +

    If an HTTP request is received that contains an illegal header name + (i.e. the header name is not a token) this setting determines if the + request will be rejected with a 400 response (true) or if the + illegal header be ignored (false). The default value is + false which will cause the request to be processed but the + illegal header will be ignored.

    +
    relaxedPathChars +

    The HTTP/1.1 + specification requires that certain characters are %nn encoded when + used in URI paths. Unfortunately, many user agents including all the major + browsers are not compliant with this specification and use these + characters in unencoded form. To prevent Tomcat rejecting such requests, + this attribute may be used to specify the additional characters to allow. + If not specified, no additional characters will be allowed. The value may + be any combination of the following characters: + " < > [ \ ] ^ ` { | } . Any other characters + present in the value will be ignored.

    +
    relaxedQueryChars +

    The HTTP/1.1 + specification requires that certain characters are %nn encoded when + used in URI query strings. Unfortunately, many user agents including all + the major browsers are not compliant with this specification and use these + characters in unencoded form. To prevent Tomcat rejecting such requests, + this attribute may be used to specify the additional characters to allow. + If not specified, no additional characters will be allowed. The value may + be any combination of the following characters: + " < > [ \ ] ^ ` { | } . Any other characters + present in the value will be ignored.

    +
    restrictedUserAgents +

    The value is a regular expression (using java.util.regex) + matching the user-agent header of HTTP clients for which + HTTP/1.1 or HTTP/1.0 keep alive should not be used, even if the clients + advertise support for these features. + The default value is an empty String (regexp matching disabled).

    +
    server +

    Overrides the Server header for the http response. If set, the value + for this attribute overrides any Server header set by a web application. + If not set, any value specified by the application is used. If the + application does not specify a value then no Server header is set.

    +
    serverRemoveAppProvidedValues +

    If true, any Server header set by a web + application will be removed. Note that if server is set, + this attribute is effectively ignored. If not set, the default value of + false will be used.

    +
    SSLEnabled +

    Use this attribute to enable SSL traffic on a connector. + To turn on SSL handshake/encryption/decryption on a connector + set this value to true. + The default value is false. + When turning this value true you will want to set the + scheme and the secure attributes as well + to pass the correct request.getScheme() and + request.isSecure() values to the servlets + See SSL Support for more information. +

    +
    tcpNoDelay +

    If set to true, the TCP_NO_DELAY option will be + set on the server socket, which improves performance under most + circumstances. This is set to true by default.

    +
    threadPriority +

    The priority of the request processing threads within the JVM. + The default value is 5 (the value of the + java.lang.Thread.NORM_PRIORITY constant). See the JavaDoc + for the java.lang.Thread class for more details on what + this priority means. If an executor is associated + with this connector, this attribute is ignored as the connector will + execute tasks using the executor rather than an internal thread pool. Note + that if an executor is configured any value set for this attribute will be + recorded correctly but it will be reported (e.g. via JMX) as + -1 to make clear that it is not used.

    +
    + +
    + +

    Java TCP socket attributes

    + +

    The NIO and NIO2 implementation support the following Java TCP + socket attributes in addition to the common Connector and HTTP attributes + listed above.

    + +
    + Attribute + + Description +
    socket.rxBufSize +

    (int)The socket receive buffer (SO_RCVBUF) size in bytes. JVM default + used if not set.

    +
    socket.txBufSize +

    (int)The socket send buffer (SO_SNDBUF) size in bytes. JVM default + used if not set.

    +
    socket.tcpNoDelay +

    (bool)This is equivalent to standard attribute + tcpNoDelay.

    +
    socket.soKeepAlive +

    (bool)Boolean value for the socket's keep alive setting + (SO_KEEPALIVE). JVM default used if not set.

    +
    socket.ooBInline +

    (bool)Boolean value for the socket OOBINLINE setting. JVM default + used if not set.

    +
    socket.soReuseAddress +

    (bool)Boolean value for the sockets reuse address option + (SO_REUSEADDR). JVM default used if not set.

    +
    socket.soLingerOn +

    (bool)Boolean value for the sockets so linger option (SO_LINGER). + A value for the standard attribute connectionLinger + that is >=0 is equivalent to setting this to true. + A value for the standard attribute connectionLinger + that is <0 is equivalent to setting this to false. + Both this attribute and soLingerTime must be set else the + JVM defaults will be used for both.

    +
    socket.soLingerTime +

    (int)Value in seconds for the sockets so linger option (SO_LINGER). + This is equivalent to standard attribute + connectionLinger. + Both this attribute and soLingerOn must be set else the + JVM defaults will be used for both.

    +
    socket.soTimeout +

    This is equivalent to standard attribute + connectionTimeout.

    +
    socket.performanceConnectionTime +

    (int)The first value for the performance settings. See + Socket Performance Options. + All three performance attributes must be set else the JVM defaults will + be used for all three.

    +
    socket.performanceLatency +

    (int)The second value for the performance settings. See + Socket Performance Options. + All three performance attributes must be set else the JVM defaults will + be used for all three.

    +
    socket.performanceBandwidth +

    (int)The third value for the performance settings. See + Socket Performance Options. + All three performance attributes must be set else the JVM defaults will + be used for all three.

    +
    socket.unlockTimeout +

    (int) The timeout for a socket unlock. When a connector is stopped, it will try to release the acceptor thread by opening a connector to itself. + The default value is 250 and the value is in milliseconds

    +
    +
    + +

    NIO specific configuration

    + +

    The following attributes are specific to the NIO connector.

    + +
    + Attribute + + Description +
    pollerThreadCount +

    (int)The number of threads to be used to run for the polling events. + Default value is 1 per processor but not more than 2.
    + When accepting a socket, the operating system holds a global lock. So the benefit of + going above 2 threads diminishes rapidly. Having more than one thread is for + system that need to accept connections very rapidly. However usually just + increasing acceptCount will solve that problem. + Increasing this value may also be beneficial when a large amount of send file + operations are going on. +

    +
    pollerThreadPriority +

    (int)The priority of the poller threads. + The default value is 5 (the value of the + java.lang.Thread.NORM_PRIORITY constant). See the JavaDoc + for the java.lang.Thread class for more details on what + this priority means.

    +
    selectorTimeout +

    (int)The time in milliseconds to timeout on a select() for the + poller. This value is important, since connection clean up is done on + the same thread, so do not set this value to an extremely high one. The + default value is 1000 milliseconds.

    +
    useSendfile +

    (bool)Use this attribute to enable or disable sendfile capability. + The default value is true. Note that the use of sendfile + will disable any compression that Tomcat may otherwise have performed on + the response.

    +
    socket.directBuffer +

    (bool)Boolean value, whether to use direct ByteBuffers or java mapped + ByteBuffers. If true then + java.nio.ByteBuffer.allocateDirect() is used to allocate + the buffers, if false then + java.nio.ByteBuffer.allocate() is used. The default value + is false.
    + When you are using direct buffers, make sure you allocate the + appropriate amount of memory for the direct memory space. On Sun's JDK + that would be something like -XX:MaxDirectMemorySize=256m. +

    +
    socket.directSslBuffer +

    (bool)Boolean value, whether to use direct ByteBuffers or java mapped + ByteBuffers for the SSL buffers. If true then + java.nio.ByteBuffer.allocateDirect() is used to allocate + the buffers, if false then + java.nio.ByteBuffer.allocate() is used. The default value + is false.
    + When you are using direct buffers, make sure you allocate the + appropriate amount of memory for the direct memory space. On Oracle's JDK + that would be something like -XX:MaxDirectMemorySize=256m. +

    +
    socket.appReadBufSize +

    (int)Each connection that is opened up in Tomcat get associated with + a read ByteBuffer. This attribute controls the size of this buffer. By + default this read buffer is sized at 8192 bytes. For lower + concurrency, you can increase this to buffer more data. For an extreme + amount of keep alive connections, decrease this number or increase your + heap size.

    +
    socket.appWriteBufSize +

    (int)Each connection that is opened up in Tomcat get associated with + a write ByteBuffer. This attribute controls the size of this buffer. By + default this write buffer is sized at 8192 bytes. For low + concurrency you can increase this to buffer more response data. For an + extreme amount of keep alive connections, decrease this number or + increase your heap size.
    + The default value here is pretty low, you should up it if you are not + dealing with tens of thousands concurrent connections.

    +
    socket.bufferPool +

    (int)The NIO connector uses a class called NioChannel that holds + elements linked to a socket. To reduce garbage collection, the NIO + connector caches these channel objects. This value specifies the size of + this cache. The default value is 500, and represents that + the cache will hold 500 NioChannel objects. Other values are + -1 for unlimited cache and 0 for no cache.

    +
    socket.bufferPoolSize +

    (int)The NioChannel pool can also be size based, not used object + based. The size is calculated as follows:
    + NioChannel + buffer size = read buffer size + write buffer size
    + SecureNioChannel buffer size = application read buffer size + + application write buffer size + network read buffer size + + network write buffer size
    + The value is in bytes, the default value is 1024*1024*100 + (100MB).

    +
    socket.processorCache +

    (int)Tomcat will cache SocketProcessor objects to reduce garbage + collection. The integer value specifies how many objects to keep in the + cache at most. The default is 500. Other values are + -1 for unlimited cache and 0 for no cache.

    +
    socket.keyCache +

    (int)Tomcat will cache KeyAttachment objects to reduce garbage + collection. The integer value specifies how many objects to keep in the + cache at most. The default is 500. Other values are + -1 for unlimited cache and 0 for no cache.

    +
    socket.eventCache +

    (int)Tomcat will cache PollerEvent objects to reduce garbage + collection. The integer value specifies how many objects to keep in the + cache at most. The default is 500. Other values are + -1 for unlimited cache and 0 for no cache.

    +
    selectorPool.maxSelectors +

    (int)The max selectors to be used in the pool, to reduce selector + contention. Use this option when the command line + org.apache.tomcat.util.net.NioSelectorShared value is set + to false. Default value is 200.

    +
    selectorPool.maxSpareSelectors +

    (int)The max spare selectors to be used in the pool, to reduce + selector contention. When a selector is returned to the pool, the system + can decide to keep it or let it be GC'd. Use this option when the + command line org.apache.tomcat.util.net.NioSelectorShared + value is set to false. Default value is -1 (unlimited).

    +
    useInheritedChannel +

    (bool)Defines if this connector should inherit an inetd/systemd network socket. + Only one connector can inherit a network socket. This can option can be + used to automatcially start Tomcat once a connection request is made to + the systemd super daemon's port. + The default value is false. See the JavaDoc + for the java.nio.channels.spi.SelectorProvider class for + more details.

    +
    command-line-options +

    The following command line options are available for the NIO + connector:
    + -Dorg.apache.tomcat.util.net.NioSelectorShared=true|false + - default is true. Set this value to false if you wish to + use a selector for each thread. When you set it to false, you can + control the size of the pool of selectors by using the + selectorPool.maxSelectors attribute.

    +
    +
    + +

    NIO2 specific configuration

    + +

    The following attributes are specific to the NIO2 connector.

    + +
    + Attribute + + Description +
    useSendfile +

    (bool)Use this attribute to enable or disable sendfile capability. + The default value is true. Note that the use of sendfile + will disable any compression that Tomcat may otherwise have performed on + the response.

    +
    socket.directBuffer +

    (bool)Boolean value, whether to use direct ByteBuffers or java mapped + ByteBuffers. If true then + java.nio.ByteBuffer.allocateDirect() is used to allocate + the buffers, if false then + java.nio.ByteBuffer.allocate() is used. The default value + is false.
    + When you are using direct buffers, make sure you allocate the + appropriate amount of memory for the direct memory space. On Sun's JDK + that would be something like -XX:MaxDirectMemorySize=256m. +

    +
    socket.directSslBuffer +

    (bool)Boolean value, whether to use direct ByteBuffers or java mapped + ByteBuffers for the SSL buffers. If true then + java.nio.ByteBuffer.allocateDirect() is used to allocate + the buffers, if false then + java.nio.ByteBuffer.allocate() is used. The default value + is false.
    + When you are using direct buffers, make sure you allocate the + appropriate amount of memory for the direct memory space. On Oracle's JDK + that would be something like -XX:MaxDirectMemorySize=256m. +

    +
    socket.appReadBufSize +

    (int)Each connection that is opened up in Tomcat get associated with + a read ByteBuffer. This attribute controls the size of this buffer. By + default this read buffer is sized at 8192 bytes. For lower + concurrency, you can increase this to buffer more data. For an extreme + amount of keep alive connections, decrease this number or increase your + heap size.

    +
    socket.appWriteBufSize +

    (int)Each connection that is opened up in Tomcat get associated with + a write ByteBuffer. This attribute controls the size of this buffer. By + default this write buffer is sized at 8192 bytes. For low + concurrency you can increase this to buffer more response data. For an + extreme amount of keep alive connections, decrease this number or + increase your heap size.
    + The default value here is pretty low, you should up it if you are not + dealing with tens of thousands concurrent connections.

    +
    socket.bufferPool +

    (int)The NIO2 connector uses a class called Nio2Channel that holds + elements linked to a socket. To reduce garbage collection, the NIO2 + connector caches these channel objects. This value specifies the size of + this cache. The default value is 500, and represents that + the cache will hold 500 Nio2Channel objects. Other values are + -1 for unlimited cache and 0 for no cache.

    +
    socket.processorCache +

    (int)Tomcat will cache SocketProcessor objects to reduce garbage + collection. The integer value specifies how many objects to keep in the + cache at most. The default is 500. Other values are + -1 for unlimited cache and 0 for no cache.

    +
    +
    + +

    APR/native specific configuration

    + +

    The following attributes are specific to the APR/native connector.

    + +
    + Attribute + + Description +
    deferAccept +

    Sets the TCP_DEFER_ACCEPT flag on the listening socket + for this connector. The default value is true where + TCP_DEFER_ACCEPT is supported by the operating system, + otherwise it is false.

    +
    ipv6v6only +

    If listening on an IPv6 address on a dual stack system, should the + connector only listen on the IPv6 address? If not specified the default + is false and the connector will listen on the IPv6 address + and the equivalent IPv4 address if present.

    +
    pollerThreadCount +

    Number of threads used to poll kept alive connections. On Windows the + default is chosen so that the sockets managed by each thread is + less than 1024. For Linux the default is 1. Changing the default on + Windows is likely to have a negative performance impact.

    +
    pollTime +

    Duration of a poll call in microseconds. Lowering this value will + slightly decrease latency of connections being kept alive in some cases, + but will use more CPU as more poll calls are being made. The default + value is 2000 (2ms).

    +
    sendfileSize +

    Amount of sockets that the poller responsible for sending static + files asynchronously can hold at a given time. Extra connections will be + closed right away without any data being sent (resulting in a zero + length file on the client side). Note that in most cases, sendfile is a + call that will return right away (being taken care of "synchronously" by + the kernel), and the sendfile poller will not be used, so the amount of + static files which can be sent concurrently is much larger than the + specified amount. The default value is 1024.

    +
    threadPriority +

    (int)The priority of the acceptor and poller threads. + The default value is 5 (the value of the + java.lang.Thread.NORM_PRIORITY constant). See the JavaDoc + for the java.lang.Thread class for more details on what + this priority means.

    +
    useSendfile +

    (bool)Use this attribute to enable or disable sendfile capability. + The default value is true. Note that the use of sendfile + will disable any compression that Tomcat may otherwise have performed on + the response.

    +
    + +
    + +

    Nested Components

    + +

    First implemented in Tomcat 9 and back-ported to 8.5, Tomcat now supports + Server Name Indication (SNI). This allows multiple SSL configurations to be + associated with a single secure connector with the configuration used for any + given connection determined by the host name requested by the client. To + facilitate this, the SSLHostConfig element was added which + can be used to define one of these configurations. Any number of + SSLHostConfig may be nested in a Connector. + At the same time, support was added for multiple certificates to be associated + with a single SSLHostConfig. Each SSL certificate is + therefore configured in a Certificate element with in an + SSLHostConfig. For further information, see the SSL Support + section below.

    + +

    Special Features

    + + +

    HTTP/1.1 and HTTP/1.0 Support

    + +

    This Connector supports all of the required features + of the HTTP/1.1 protocol, as described in RFCs 7230-7235, including persistent + connections, pipelining, expectations and chunked encoding. If the client + supports only HTTP/1.0 or HTTP/0.9, the + Connector will gracefully fall back to supporting this + protocol as well. No special configuration is required to enable this + support. The Connector also supports HTTP/1.0 + keep-alive.

    + +

    RFC 7230 requires that HTTP servers always begin their responses with + the highest HTTP version that they claim to support. Therefore, this + Connector will always return HTTP/1.1 at + the beginning of its responses.

    + +
    + +

    HTTP/2 Support

    + +

    HTTP/2 is support is provided for TLS (h2), non-TLS via HTTP upgrade (h2c) + and direct HTTP/2 (h2c) connections. To enable HTTP/2 support for an HTTP + connector the following UpgradeProtocol element must be + nested within the Connector with a + className attribute of + org.apache.coyote.http2.Http2Protocol.

    + +
    <Connector ... >
    +  <UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" />
    +</Connector>
    + +

    Because Java 8's TLS implementation does not support ALPN (which is + required for HTTP/2 over TLS), you must be using an OpenSSL based TLS + implementation to enable HTTP/2 support. See the + sslImplementationName attribute of the + Connector.

    + +

    Additional configuration attributes are available. See the + HTTP/2 Upgrade Protocol documentation for details.

    + +
    + +

    Proxy Support

    + +

    The proxyName and proxyPort attributes can + be used when Tomcat is run behind a proxy server. These attributes + modify the values returned to web applications that call the + request.getServerName() and request.getServerPort() + methods, which are often used to construct absolute URLs for redirects. + Without configuring these attributes, the values returned would reflect + the server name and port on which the connection from the proxy server + was received, rather than the server name and port to whom the client + directed the original request.

    + +

    For more information, see the + Proxy Support How-To.

    + +
    + + +

    SSL Support

    + +

    You can enable SSL support for a particular instance of this + Connector by setting the SSLEnabled attribute to + true.

    + +

    You will also need to set the scheme and secure + attributes to the values https and true + respectively, to pass correct information to the servlets.

    + +

    The NIO and NIO2 connectors use either the JSSE Java SSL implementation or + an OpenSSL implementation, whereas the APR/native connector uses OpenSSL only. + Prior to Tomcat 8.5, different configuration attributes were used for JSSE and + OpenSSL. From Tomcat 8.5 onwards, and as far as possible, common configuration + attributes are used for both JSSE and OpenSSL. Also if using the JSSE OpenSSL + implementation, configuration can be set using either the JSSE or APR + attributes (note: but not both types within the same configuration). This is + to aid simpler switching between connector implementations for SSL + connectors.

    + +

    Each secure connector must define at least one + SSLHostConfig. The names of the + SSLHostConfig elements must be unique and one of them must + match the defaultSSLHostConfigName attribute of the + Connector.

    + +

    Each SSLHostConfig must in turn define at least one + Certificate. The types of the Certificates + must be unique.

    + +

    As of Tomcat 8.5, the majority of the SSL configuration attributes in the + Connector are deprecated. If specified, they will be used to + configure a SSLHostConfig and Certificate + for the defaultSSLHostConfigName. Note that if an explicit + SSLHostConfig element also exists for the + defaultSSLHostConfigName then that will be treated as a configuration + error. It is expected that Tomcat 10 will drop support for the SSL + configuration attributes in the Connector.

    + +

    For more information, see the + SSL Configuration How-To.

    + +
    + +

    SSL Support - SSLHostConfig

    + +

    + +
    + Attribute + + Description +
    certificateRevocationListFile +

    Name of the file that contains the concatenated certificate revocation + lists for the certificate authorities. The format is PEM-encoded. If not + defined, client certificates will not be checked against a certificate + revocation list (unless an OpenSSL based connector is used and + certificateRevocationListPath is defined). Relative paths + will be resolved against $CATALINA_BASE. JSSE based + connectors may also specify a URL for this attribute.

    +
    certificateRevocationListPath +

    OpenSSL only.

    +

    Name of the directory that contains the certificate revocation lists + for the certificate authorities. The format is PEM-encoded. Relative paths + will be resolved against $CATALINA_BASE.

    +
    certificateVerification +

    Set to required if you want the SSL stack to require a + valid certificate chain from the client before accepting a connection. + Set to optional if you want the SSL stack to request a client + Certificate, but not fail if one isn't presented. Set to + optionalNoCA if you want client certificates to be optional + and you don't want Tomcat to check them against the list of trusted CAs. + If the TLS provider doesn't support this option (OpenSSL does, JSSE does + not) it is treated as if optional was specified. A + none value (which is the default) will not require a + certificate chain unless the client requests a resource protected by a + security constraint that uses CLIENT-CERT authentication.

    +
    certificateVerificationDepth +

    The maximum number of intermediate certificates that will be allowed + when validating client certificates. If not specified, the default value + of 10 will be used.

    +
    caCertificateFile +

    OpenSSL only.

    +

    Name of the file that contains the concatenated certificates for the + trusted certificate authorities. The format is PEM-encoded.

    +
    caCertificatePath +

    OpenSSL only.

    +

    Name of the directory that contains the certificates for the trusted + certificate authorities. The format is PEM-encoded.

    +
    ciphers +

    The ciphers to enable using the OpenSSL syntax. (See the OpenSSL + documentation for the list of ciphers supported and the syntax). + Alternatively, a comma separated list of ciphers using the standard + OpenSSL cipher names or the standard JSSE cipher names may be used.

    +

    When converting from OpenSSL syntax to JSSE ciphers for JSSE based + connectors, the behaviour of the OpenSSL syntax parsing is kept aligned + with the behaviour of the OpenSSL 1.1.0 development branch.

    +

    Only the ciphers that are supported by the SSL implementation will be + used.

    +

    If not specified, a default (using the OpenSSL notation) of + HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!kRSA will be + used.

    +

    Note that, by default, the order in which ciphers are defined is + treated as an order of preference. See honorCipherOrder.

    +
    disableCompression +

    OpenSSL only.

    +

    Configures if compression is disabled. The default is + true. If the OpenSSL version used does not support disabling + compression then the default for that OpenSSL version will be used.

    +
    disableSessionTickets +

    OpenSSL only.

    +

    Disables use of TLS session tickets (RFC 5077) if set to + true. Default is false. Note that when TLS + session tickets are in use, the full peer certificate chain will only be + available on the first connection. Subsequent connections (that use a + ticket to estrablish the TLS session) will only have the peer certificate, + not the full chain.

    +
    honorCipherOrder +

    Set to true to enforce the server's cipher order + (from the ciphers setting) instead of allowing + the client to choose the cipher. The default is false. + Use of this feature requires Java 8 or later.

    +
    hostName +

    The name of the SSL Host. This should either be the fully qualified + domain name (e.g. tomcat.apache.org) or a wild card domain + name (e.g. *.apache.org). If not specified, the default value + of _default_ will be used.

    +
    insecureRenegotiation +

    OpenSSL only.

    +

    Configures if insecure renegotiation is allowed. The default is + false. If the OpenSSL version used does not support + configuring if insecure renegotiation is allowed then the default for that + OpenSSL version will be used.

    +
    keyManagerAlgorithm +

    JSSE only.

    +

    The KeyManager algorithm to be used. This defaults to + KeyManagerFactory.getDefaultAlgorithm() which returns + SunX509 for Sun JVMs. IBM JVMs return + IbmX509. For other vendors, consult the JVM + documentation for the default value.

    +
    protocols +

    The names of the protocols to support when communicating with clients. + This should be a list of any combination of the following: +

    +
    • SSLv2Hello
    • SSLv3
    • TLSv1
    • TLSv1.1
    • +
    • TLSv1.2
    • TLSv1.3
    • all
    +

    Each token in the list can be prefixed with a plus sign ("+") + or a minus sign ("-"). A plus sign adds the protocol, a minus sign + removes it form the current list. The list is built starting from + an empty list.

    +

    The token all is an alias for + SSLv2Hello,TLSv1,TLSv1.1,TLSv1.2,TLSv1.3.

    +

    Note that TLSv1.3 is only supported for JSSE when using a + JVM that implements TLSv1.3.

    +

    Note that SSLv2Hello will be ignored for OpenSSL based + secure connectors. If more than one protocol is specified for an OpenSSL + based secure connector it will always support SSLv2Hello. If a + single protocol is specified it will not support + SSLv2Hello.

    +

    Note that SSLv2 and SSLv3 are inherently + unsafe.

    +

    If not specified, the default value of all will be + used.

    +
    revocationEnabled +

    JSSE only.

    +

    Should the JSSE provider enable certificate revocation checks? If + certificateRevocationListFile is set then this attribute + is ignored and revocation checks are always enabled. This attribute is + intended to enable revocation checks that have been configured for the + current JSSE provider via other means. If not specified, a default of + false is used.

    +
    sessionCacheSize +

    The number of SSL sessions to maintain in the session cache. Use 0 to + specify an unlimited cache size. If not specified, a default of 0 is + used.

    +
    sessionTimeout +

    The time, in seconds, after the creation of an SSL session that it will + timeout. Use 0 to specify an unlimited timeout. If not specified, a + default of 86400 (24 hours) is used.

    +
    sslProtocol +

    JSSE only.

    +

    The SSL protocol(s) to use (a single value may enable multiple + protocols - see the JVM documentation for details). If not specified, the + default is TLS. The permitted values may be obtained from the + JVM documentation for the allowed values for algorithm when creating an + SSLContext instance e.g. + + Oracle Java 7. Note: There is overlap between this attribute and + protocols.

    +
    trustManagerClassName +

    JSSE only.

    +

    The name of a custom trust manager class to use to validate client + certificates. The class must have a zero argument constructor and must + also implement javax.net.ssl.X509TrustManager. If this + attribute is set, the trust store attributes may be ignored.

    +
    truststoreAlgorithm +

    JSSE only.

    +

    The algorithm to use for truststore. If not specified, the default + value returned by + javax.net.ssl.TrustManagerFactory.getDefaultAlgorithm() is + used.

    +
    truststoreFile +

    JSSE only.

    +

    The trust store file to use to validate client certificates. The + default is the value of the javax.net.ssl.trustStore system + property. If neither this attribute nor the default system property is + set, no trust store will be configured. Relative paths + will be resolved against $CATALINA_BASE. A URL may also be + used for this attribute.

    +
    truststorePassword +

    JSSE only.

    +

    The password to access the trust store. The default is the value of the + javax.net.ssl.trustStorePassword system property. If that + property is null, no trust store password will be configured. If an + invalid trust store password is specified, a warning will be logged and an + attempt will be made to access the trust store without a password which + will skip validation of the trust store contents.

    +
    truststoreProvider +

    JSSE only.

    +

    The name of the truststore provider to be used for the server + certificate. The default is the value of the + javax.net.ssl.trustStoreProvider system property. If + that property is null, the value of keystoreProvider is used + as the default. If neither this attribute, the default system property nor + keystoreProvider is set, the list of registered providers is + traversed in preference order and the first provider that supports the + truststoreType is used. +

    +
    truststoreType +

    JSSE only.

    +

    The type of key store used for the trust store. The default is the + value of the javax.net.ssl.trustStoreType system property. If + that property is null, a single certificate has been configured for this + TLS virtual host and that certificate has a keystoreType that + is not PKCS12 then the default will be the + keystoreType of the single certificate. If none of these + identify a default, the default will be JKS.

    +
    + +
    + +

    SSL Support - Certificate

    + +

    + +
    + Attribute + + Description +
    certificateFile +

    Name of the file that contains the server certificate. The format is + PEM-encoded. Relative paths will be resolved against + $CATALINA_BASE.

    +

    In addition to the certificate, the file can also contain as optional + elements DH parameters and/or an EC curve name for ephemeral keys, as + generated by openssl dhparam and openssl ecparam, + respectively. The output of the respective OpenSSL command can simply + be concatenated to the certificate file.

    +
    certificateChainFile +

    Name of the file that contains the certificate chain associated with + the server certificate used. The format is + PEM-encoded. Relative paths will be resolved against + $CATALINA_BASE.

    +

    The certificate chain used for Tomcat should not include the server + certificate as its first element.

    +

    Note that when using more than one certificate for different types, + they all must use the same certificate chain.

    +
    certificateKeyAlias +

    JSSE only.

    +

    The alias used for the server key and certificate in the keystore. If + not specified, the first key read from the keystore will be used. The + order in which keys are read from the keystore is implementation + dependent. It may not be the case that keys are read from the keystore in + the same order as they were added. If more than one key is present in the + keystore it is strongly recommended that a keyAlias is configured to + ensure that the correct key is used.

    +
    certificateKeyFile +

    Name of the file that contains the server private key. The format is + PEM-encoded. The default value is the value of + certificateFile and in this case both certificate and + private key have to be in this file (NOT RECOMMENDED). Relative paths will + be resolved against $CATALINA_BASE.

    +
    certificateKeyPassword +

    The password used to access the private key associated with the server + certificate from the specified file.

    +

    If not specified, the default behaviour for JSSE is to use the + certificateKeystorePassword. For OpenSSL the default + behaviour is not to use a password.

    +
    certificateKeystoreFile +

    JSSE only.

    +

    The pathname of the keystore file where you have stored the server + certificate and key to be loaded. By default, the pathname is the file + .keystore in the operating system home directory of the user + that is running Tomcat. If your keystoreType doesn't need a + file use "" (empty string) or NONE for this + parameter. Relative paths will be resolved against + $CATALINA_BASE. A URI may also be used for this attribute. + When using a domain keystore (keystoreType of + DKS), this parameter should be the URI to the domain + keystore.

    +
    certificateKeystorePassword +

    JSSE only.

    +

    The password to use to access the keystore containing the server's + private key and certificate. If not specified, a default of + changeit will be used.

    +
    certificateKeystoreProvider +

    JSSE only.

    +

    The name of the keystore provider to be used for the server + certificate. If not specified, the value of the system property + javax.net.ssl.keyStoreProvider is used. If neither this + attribute nor the system property are set, the list of registered + providers is traversed in preference order and the first provider that + supports the keystoreType is used. +

    +
    certificateKeystoreType +

    JSSE only.

    +

    The type of keystore file to be used for the server certificate. + If not specified, the value of the system property + javax.net.ssl.keyStoreType is used. If neither this attribute + nor the system property are set, a default value of "JKS". is + used.

    +
    type +

    The type of certificate. This is used to identify the ciphers that are + compatible with the certificate. It must be one of UNDEFINED, + RSA, DSS or EC. If only one + Certificate is nested within a SSLHostConfig + then this attribute is not required and will default to + UNDEFINED. If multiple Certificates are + nested within a SSLHostConfig then this attribute is required + and each Certificate must have a unique type.

    +
    + +
    + +

    SSL Support - Connector - NIO and NIO2

    + +

    When APR/native is enabled, the connectors will default to using OpenSSL through JSSE, + which may be more optimized than the JSSE Java implementation depending on the processor being used, + and can be complemented with many commercial accelerator components.

    + +

    The following NIO and NIO2 SSL configuration attributes are not specific to + a virtual host and, therefore, must be configured on the connector.

    + +
    + Attribute + + Description +
    sniParseLimit +

    In order to implement SNI support, Tomcat has to parse the first TLS + message received on a new TLS connection (the client hello) to extract the + requested server name. The message needs to be buffered so it can then be + passed to the JSSE implementation for normal TLS processing. In theory, + this first message could be very large although in practice it is + typically a few hundred bytes. This attribute sets the maximum message + size that Tomcat will buffer. If a message exceeds this size, the + connection will be configured as if no server name was indicated by the + client. If not specified a default of 65536 (64k) will be + used.

    +
    sslImplementationName +

    The class name of the SSL implementation to use. If not specified and + the tomcat-native library is not installed, the + default of org.apache.tomcat.util.net.jsse.JSSEImplementation + will be used which wraps JVM's default JSSE provider. Note that the + JVM can be configured to use a different JSSE provider as the default. + Tomcat also bundles a special SSL implementation for JSSE that is backed + by OpenSSL. To enable it, the native library should be enabled as if + intending to use the APR connector, and Tomcat will automatically enable it + and the default value of this attribute becomes + org.apache.tomcat.util.net.openssl.OpenSSLImplementation. + In that case, the attributes from either JSSE and OpenSSL + configuration styles can be used, as long as the two types are not mixed + (for example, it is not allowed to define use of a Java keystore and + specify a separate pem private key using the OpenSSL attribute).

    +
    + +
    + +

    SSL Support - Connector - NIO and NIO2 (deprecated)

    + +

    The following NIO and NIO2 SSL configuration attributes have been + deprecated in favor of the default + SSLHostConfig element with + the hostName of _default_. If this + SSLHostConfig element is not + explicitly defined, it will be created.. +

    + +
    + Attribute + + Description +
    algorithm +

    This is an alias for the keyManagerAlgorithm attribute of + the SSLHostConfig element with + the hostName of _default_. If this + SSLHostConfig element is not + explicitly defined, it will be created.

    +
    ciphers +

    This is an alias for the ciphers attribute of the + SSLHostConfig element with the + hostName of _default_. If this + SSLHostConfig element is not + explicitly defined, it will be created.

    +
    clientAuth +

    This is an alias for the certificateVerification attribute + of the SSLHostConfig element + with the hostName of _default_. If this + SSLHostConfig element is not + explicitly defined, it will be created.

    +
    crlFile +

    This is an alias for the certificateRevocationListFile + attribute of the SSLHostConfig + element with the hostName of _default_. If this + SSLHostConfig element is not + explicitly defined, it will be created.

    +
    keyAlias +

    This is an alias for the certificateKeyAlias attribute of + the first Certificate element + nested in the SSLHostConfig + element with the hostName of _default_. If this + Certificate and/or + SSLHostConfig element is not + explicitly defined, they will be created.

    +
    keyPass +

    This is an alias for the certificateKeyPassword attribute + of the first Certificate element + nested in the SSLHostConfig + element with the hostName of _default_. If this + Certificate and/or + SSLHostConfig element is not + explicitly defined, they will be created.

    +
    keystoreFile +

    This is an alias for the certificateKeystoreFile attribute + of the first Certificate element + nested in the SSLHostConfig + element with the hostName of _default_. If this + Certificate and/or + SSLHostConfig element is not + explicitly defined, they will be created.

    +
    keystorePass +

    This is an alias for the certificateKeystorePassword + attribute of the first + Certificate element nested in the + SSLHostConfig + element with the hostName of _default_. If this + Certificate and/or + SSLHostConfig element is not + explicitly defined, they will be created.

    +
    keystoreProvider +

    This is an alias for the certificateKeystoreProvider + attribute of the first + Certificate element nested in the + SSLHostConfig + element with the hostName of _default_. If this + Certificate and/or + SSLHostConfig element is not + explicitly defined, they will be created.

    +
    keystoreType +

    This is an alias for the certificateKeystoreType attribute + of the first Certificate element + nested in the SSLHostConfig + element with the hostName of _default_. If this + Certificate and/or + SSLHostConfig element is not + explicitly defined, they will be created.

    +
    sessionCacheSize +

    This is an alias for the sessionCacheSize attribute of the + SSLHostConfig element with + the hostName of _default_. If this + SSLHostConfig element is not + explicitly defined, it will be created.

    +
    sessionTimeout +

    This is an alias for the sessionTimeout attribute of the + SSLHostConfig element with + the hostName of _default_. If this + SSLHostConfig element is not + explicitly defined, it will be created.

    +
    sslEnabledProtocols +

    This is an alias for the protocols attribute of the + SSLHostConfig element with + the hostName of _default_. If this + SSLHostConfig element is not + explicitly defined, it will be created.

    +
    sslProtocol +

    This is an alias for the sslProtocol attribute of the + SSLHostConfig element with + the hostName of _default_. If this + SSLHostConfig element is not + explicitly defined, it will be created.

    +
    trustManagerClassName +

    This is an alias for the trustManagerClassName attribute + of the SSLHostConfig element + with the hostName of _default_. If this + SSLHostConfig element is not + explicitly defined, it will be created.

    +
    trustMaxCertLength +

    This is an alias for the certificateVerificationDepth + attribute of the SSLHostConfig + element with the hostName of _default_. If this + SSLHostConfig element is not + explicitly defined, it will be created.

    +
    truststoreAlgorithm +

    This is an alias for the truststoreAlgorithm attribute of + SSLHostConfig element with + the hostName of _default_. If this + SSLHostConfig element is not + explicitly defined, it will be created.

    +
    truststoreFile +

    This is an alias for the truststoreFile attribute of + SSLHostConfig element with + the hostName of _default_. If this + SSLHostConfig element is not + explicitly defined, it will be created.

    +
    truststorePass +

    This is an alias for the truststorePassword attribute of + SSLHostConfig element with + the hostName of _default_. If this + SSLHostConfig element is not + explicitly defined, it will be created.

    +
    truststoreProvider +

    This is an alias for the truststoreProvider attribute of + SSLHostConfig element with + the hostName of _default_. If this + SSLHostConfig element is not + explicitly defined, it will be created.

    +
    truststoreType +

    This is an alias for the truststoreType attribute of + SSLHostConfig element with + the hostName of _default_. If this + SSLHostConfig element is not + explicitly defined, it will be created.

    +
    useServerCipherSuitesOrder +

    This is an alias for the honorCipherOrder attribute of the + SSLHostConfig element with + hostName of _default_. If this + SSLHostConfig element is not + explicitly defined, it will be created.

    +
    + +
    + +

    SSL Support - Connector - APR/Native (deprecated)

    + +

    When APR/native is enabled, the HTTPS connector will use a socket poller + for keep-alive, increasing scalability of the server. It also uses OpenSSL, + which may be more optimized than JSSE depending on the processor being used, + and can be complemented with many commercial accelerator components. Unlike + the HTTP connector, the HTTPS connector cannot use sendfile to optimize static + file processing.

    + +

    The HTTPS APR/native connector has the same attributes than the HTTP + APR/native connector, but adds OpenSSL specific ones. For the full details on + using OpenSSL, please refer to OpenSSL documentations and the many books + available for it (see the Official OpenSSL + website). The SSL specific attributes for the APR/native connector are: +

    + +
    + Attribute + + Description +
    SSLCACertificateFile +

    This is an alias for the caCertificateFile attribute of + the SSLHostConfig element with + the hostName of _default_. If this + SSLHostConfig element is not + explicitly defined, it will be created.

    +
    SSLCACertificatePath +

    This is an alias for the caCertificatePath attribute of + the SSLHostConfig element with + the hostName of _default_. If this + SSLHostConfig element is not + explicitly defined, it will be created.

    +
    SSLCARevocationFile +

    This is an alias for the certificateRevocationListFile + attribute of the SSLHostConfig + element with the hostName of _default_. If this + SSLHostConfig element is not + explicitly defined, it will be created.

    +
    SSLCARevocationPath +

    This is an alias for the certificateRevocationListPath + attribute of the SSLHostConfig + element with the hostName of _default_. If this + SSLHostConfig element is not + explicitly defined, it will be created.

    +
    SSLCertificateFile +

    This is an alias for the certificateFile attribute of the + first Certificate element nested + in the SSLHostConfig element + with the hostName of _default_. If this + Certificate and/or + SSLHostConfig element is not + explicitly defined, they will be created.

    +
    SSLCertificateKeyFile +

    This is an alias for the certificateKeyFile attribute of + the first Certificate element + nested in the SSLHostConfig + element with the hostName of _default_. If this + Certificate and/or + SSLHostConfig element is not + explicitly defined, they will be created.

    +
    SSLCipherSuite +

    This is an alias for the ciphers attribute of the + SSLHostConfig element with the + hostName of _default_. If this + SSLHostConfig element is not + explicitly defined, it will be created.

    +
    SSLDisableCompression +

    This is an alias for the disableCompression attribute of + the SSLHostConfig element with + the hostName of _default_. If this + SSLHostConfig element is not + explicitly defined, it will be created.

    +
    SSLHonorCipherOrder +

    This is an alias for the honorCipherOrder attribute of the + SSLHostConfig element with the + hostName of _default_. If this + SSLHostConfig element is not + explicitly defined, it will be created.

    +
    SSLPassword +

    This is an alias for the certificateKeyPassword attribute + of the first Certificate element + nested in the SSLHostConfig + element with the hostName of _default_. If this + Certificate and/or + SSLHostConfig element is not + explicitly defined, they will be created.

    +
    SSLProtocol +

    This is an alias for the protocols attribute of the + SSLHostConfig element with the + hostName of _default_. If this + SSLHostConfig element is not + explicitly defined, it will be created.

    +
    SSLVerifyClient +

    This is an alias for the certificateVerification attribute + of the SSLHostConfig element + with the hostName of _default_. If this + SSLHostConfig element is not + explicitly defined, it will be created.

    +
    SSLVerifyDepth +

    This is an alias for the certificateVerificationDepth + attribute of the SSLHostConfig + element with the hostName of _default_. If this + SSLHostConfig element is not + explicitly defined, it will be created.

    +
    SSLDisableSessionTickets +

    This is an alias for the disableSessionTickets attribute + of the SSLHostConfig element + with the hostName of _default_. If this + SSLHostConfig element is not + explicitly defined, it will be created.

    +
    + +
    + +

    Connector Comparison

    + +

    Below is a small chart that shows how the connectors differ.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Java Nio Connector
    NIO
    Java Nio2 Connector
    NIO2
    APR/native Connector
    APR
    ClassnameHttp11NioProtocolHttp11Nio2ProtocolHttp11AprProtocol
    Tomcat Version6.x onwards8.x onwards5.5.x onwards
    Support PollingYESYESYES
    Polling SizemaxConnectionsmaxConnectionsmaxConnections
    Read Request HeadersNon BlockingNon BlockingNon Blocking
    Read Request BodyBlockingBlockingBlocking
    Write Response Headers and BodyBlockingBlockingBlocking
    Wait for next RequestNon BlockingNon BlockingNon Blocking
    SSL SupportJava SSL or OpenSSLJava SSL or OpenSSLOpenSSL
    SSL HandshakeNon blockingNon blockingBlocking
    Max ConnectionsmaxConnectionsmaxConnectionsmaxConnections
    + +
    +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/http2.html b/tomcat/docs/config/http2.html new file mode 100644 index 0000000..65cf08e --- /dev/null +++ b/tomcat/docs/config/http2.html @@ -0,0 +1,236 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - The HTTP2 Upgrade Protocol

    The HTTP2 Upgrade Protocol

    Table of Contents

    Introduction

    + +

    The HTTP Upgrade Protocol element represents an + Upgrade Protocol component that supports the HTTP/2 protocol. + An instance of this component must be associated with an existing + HTTP/1.1 Connector.

    + +

    HTTP/2 connectors use non-blocking I/O, only utilising a container thread + from the thread pool when there is data to read and write. However, because + the Servlet API is fundamentally blocking, each HTTP/2 stream requires a + dedicated container thread for the duration of that stream.

    + +

    Attributes

    + +

    Common Attributes

    + +

    All implementations of Upgrade Protocol support the + following attributes:

    + +
    + Attribute + + Description +
    className +

    This must be org.apache.coyote.http2.Http2Protocol.

    +
    + +
    + +

    Standard Implementation

    + +

    The HTTP/2 Upgrade Protocol implementation supports the + following attributes in addition to the common attributes listed above.

    + +
    + Attribute + + Description +
    allowedTrailerHeaders +

    By default Tomcat will ignore all trailer headers when processing + HTTP/2 connections. For a header to be processed, it must be added to this + comma-separated list of header names.

    +
    compressibleMimeType +

    The value is a comma separated list of MIME types for which HTTP + compression may be used. + The default value is + + text/html,text/xml,text/plain,text/css,text/javascript,application/javascript,application/json,application/xml + . +

    +
    compression +

    The HTTP/2 protocol may use compression in an attempt to save server + bandwidth. The acceptable values for the parameter is "off" (disable + compression), "on" (allow compression, which causes text data to be + compressed), "force" (forces compression in all cases), or a numerical + integer value (which is equivalent to "on", but specifies the minimum + amount of data before the output is compressed). If the content-length is + not known and compression is set to "on" or more aggressive, the output + will also be compressed. If not specified, this attribute is set to + "off".

    +

    Note: There is a tradeoff between using compression (saving + your bandwidth) and using the sendfile feature (saving your CPU cycles). + If the connector supports the sendfile feature, e.g. the NIO2 connector, + using sendfile will take precedence over compression. The symptoms will + be that static files greater that 48 Kb will be sent uncompressed. + You can turn off sendfile by setting useSendfile attribute + of the protocol, as documented below, or change the sendfile usage + threshold in the configuration of the + DefaultServlet in the default + conf/web.xml or in the web.xml of your web + application. +

    +
    compressionMinSize +

    If compression is set to "on" then this attribute + may be used to specify the minimum amount of data before the output is + compressed. If not specified, this attribute is defaults to "2048".

    +
    initialWindowSize +

    Controls the initial size of the flow control window for streams that + Tomcat advertises to clients. If not specified, the default value of + 65535 is used.

    +
    keepAliveTimeout +

    The time, in milliseconds, that Tomcat will wait between HTTP/2 frames + when there is no active Stream before closing the connection. Negative + values will be treated as an infinite timeout. If not specified, a default + value of 20000 will be used.

    +
    maxConcurrentStreamExecution +

    The controls the maximum number of streams for any one connection that + can be allocated threads from the container thread pool. If more streams + are active than threads are available, those streams will have to wait + for a stream to become available. If not specified, the default value of + 20 will be used.

    +
    maxConcurrentStreams +

    The controls the maximum number of active streams permitted for any one + connection. If a client attempts to open more active streams than this + limit, the stream will be reset with a STREAM_REFUSED error. + If not specified, the default value of 100 will be used.

    +
    maxHeaderCount +

    The maximum number of headers in a request that is allowed by the + container. A request that contains more headers than the specified limit + will be rejected. A value of less than 0 means no limit. + If not specified, a default of 100 is used.

    +
    maxHeaderSize +

    The maximum total size for all headers in a request that is allowed by + the container. Total size for a header is calculated as the uncompressed + size of the header name in bytes, plus the uncompressed size of the header + value in bytes plus an HTTP/2 overhead of 3 bytes per header. A request + that contains a set of headers that requires more than the specified limit + will be rejected. A value of less than 0 means no limit. If not specified, + a default of 8192 is used.

    +
    maxTrailerCount +

    The maximum number of trailer headers in a request that is allowed by + the container. A request that contains more trailer headers than the + specified limit will be rejected. A value of less than 0 means no limit. + If not specified, a default of 100 is used.

    +
    maxTrailerSize +

    The maximum total size for all trailer headers in a request that is + allowed by the container. Total size for a header is calculated as the + uncompressed size of the header name in bytes, plus the uncompressed size + of the header value in bytes plus an HTTP/2 overhead of 3 bytes per + header. A request that contains a set of trailer headers that requires + more than the specified limit will be rejected. A value of less than 0 + means no limit. If not specified, a default of 8192 is used.

    +
    noCompressionUserAgents +

    The value is a regular expression (using java.util.regex) + matching the user-agent header of HTTP clients for which + compression should not be used, + because these clients, although they do advertise support for the + feature, have a broken implementation. + The default value is an empty String (regexp matching disabled).

    +
    overheadCountFactor +

    The factor to apply when counting overhead frames to determine if a + connection has too high an overhead and should be closed. The overhead + count starts at -10. The count is decreased for each + data frame sent or received and each headers frame received. The count is + increased by the overheadCountFactorfor each setting + received, priority frame received and ping received. If the overhead count + exceeds zero, the connection is closed. A value of less than + 1 disables this protection. In normal usage a value of + 3 or more will close the connection before any streams can + complete. If not specified, a default value of 1 will be + used.

    +
    readTimeout +

    The time, in milliseconds, that Tomcat will wait for additional data + when a partial HTTP/2 frame has been received. Negative values will be + treated as an infinite timeout. If not specified, a default value of + 5000 will be used.

    +
    streamReadTimeout +

    The time, in milliseconds, that Tomcat will wait for additional data + frames to arrive for the stream when an application is performing a + blocking I/O read and additional data is required. Negative values will be + treated as an infinite timeout. If not specified, a default value of + 20000 will be used.

    +
    streamWriteTimeout +

    The time, in milliseconds, that Tomcat will wait for additional window + update frames to arrive for the stream and/or conenction when an + application is performing a blocking I/O write and the stream and/or + connection flow control window is too small for the write to complete. + Negative values will be treated as an infinite timeout. If not specified, + a default value of 20000 will be used.

    +
    writeTimeout +

    The time, in milliseconds, that Tomcat will wait to write additional + data when an HTTP/2 frame has been partially written. Negative values will + be treated as an infinite timeout. If not specified, a default value of + 5000 will be used.

    +
    + +

    The HTTP/2 upgrade protocol will also inherit the following limits from the + HTTP Connector it is nested with:

    + +
      +
    • maxCookieCount
    • +
    • maxParameterCount
    • +
    • maxPostSize
    • +
    • maxSavePostSize
    • +
    + +
    + +

    Nested Components

    + +

    This component does not support any nested components.

    + +

    Special Features

    + +

    This component does not support any special features.

    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/index.html b/tomcat/docs/config/index.html new file mode 100644 index 0000000..b0a32ca --- /dev/null +++ b/tomcat/docs/config/index.html @@ -0,0 +1,107 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - Overview

    Overview

    Overview

    + +

    This manual contains reference information about all of the configuration +directives that can be included in a conf/server.xml file to +configure the behavior of the Tomcat Servlet/JSP container. It does not +attempt to describe which configuration directives should be used to perform +specific tasks - for that, see the various How-To documents on the +main index page.

    + +

    Tomcat configuration files are formatted as schemaless XML; elements and +attributes are case-sensitive. Apache Ant-style variable substitution +is supported; a system property with the name propname may be +used in a configuration file using the syntax ${propname}. All +system properties are available including those set using the -D +syntax, those automatically made available by the JVM and those configured in +the $CATALINA_BASE/conf/catalina.properties file. +

    + +

    The configuration element descriptions are organized into the following +major categories:

    +
      +
    • Top Level Elements - <Server> is the + root element of the entire configuration file, while + <Service> represents a group of Connectors that is + associated with an Engine.
    • +
    • Connectors - Represent the interface between external + clients sending requests to (and receiving responses from) a particular + Service.
    • +
    • Containers - Represent components whose function is to + process incoming requests, and create the corresponding responses. + An Engine handles all requests for a Service, a Host handles all requests + for a particular virtual host, and a Context handles all requests for a + specific web application.
    • +
    • Nested Components - Represent elements that can be + nested inside the element for a Container. Some elements can be nested + inside any Container, while others can only be nested inside a + Context.
    • +
    + +

    For each element, the corresponding documentation follows this general +outline:

    +
      +
    • Introduction - Overall description of this particular + component. There will be a corresponding Java interface (in + the org.apache.catalina package) that is implemented by one + or more standard implementations.
    • +
    • Attributes - The set of attributes that are legal for + this element. Generally, this will be subdivided into Common + attributes that are supported by all implementations of the corresponding + Java interface, and Standard Implementation attributes that are + specific to a particular Java class that implements this interface. + The names of required attributes are bolded.
    • +
    • Nested Components - Enumerates which of the Nested + Components can be legally nested within this element.
    • +
    • Special Features - Describes the configuration of a large + variety of special features (specific to each element type) that are + supported by the standard implementation of this interface.
    • +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/jar-scan-filter.html b/tomcat/docs/config/jar-scan-filter.html new file mode 100644 index 0000000..e0d2f24 --- /dev/null +++ b/tomcat/docs/config/jar-scan-filter.html @@ -0,0 +1,183 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - The Jar Scan Filter Component

    The Jar Scan Filter Component

    Table of Contents

    Introduction

    + +

    The Jar Scan Filter element represents the component that + filters results from the Jar Scanner before + they are passed back to the application. It is typically used to skip the + scanning of JARs that are known not to be relevant to some or all types of + scan.

    + +

    A Jar Scan Filter element MAY be nested inside a + Jar Scanner component.

    + +

    For example you can specify additional jar files when scanning for pluggable + features:

    +
    <Context>
    +  ...
    +  <JarScanner>
    +    <JarScanFilter
    +        pluggabilityScan="${tomcat.util.scan.StandardJarScanFilter.jarsToScan},
    +                       my_pluggable_feature.jar"/>
    +  </JarScanner>
    +  ...
    +</Context>
    + +

    If a Jar Scan Filter element is not included, a default Jar Scan Filter + configuration will be created automatically, which is sufficient for most + requirements.

    + +

    Attributes

    + +

    Common Attributes

    + +

    All implementations of Jar Scan Filter + support the following attributes:

    + +
    + Attribute + + Description +
    className +

    Java class name of the implementation to use. This class must + implement the org.apache.tomcat.JarScanFilter interface. + If not specified, the standard value (defined below) will be used.

    +
    + +
    + + +

    Standard Implementation

    + +

    The standard implementation of Jar Scan Filter is + org.apache.tomcat.util.scan.StandardJarScanFilter. + Additional attributes that it supports (in addition to the common attributes + listed above) are listed in the table.

    + +

    The values for pluggabilitySkip, + pluggabilityScan, tldSkip, + tldScan attributes are lists of file name pattern. The + patterns are separated by comma (','). The leading and trailing whitespace + characters in a pattern are ignored. The patterns are matched + case-sensitively. The following two special characters are supported:

    + +
      +
    • '*' - means zero or more characters,
    • +
    • '?' - means one and only one character.
    • +
    + +

    Note that excluding a JAR from the pluggability scan will prevent a + ServletContainerInitializer from being loaded from a web application JAR + (i.e. one located in /WEB-INF/lib) but it will not prevent + a ServletContainerInitializer from being loaded from the container (Tomcat). + To prevent a ServletContainerInitializer provided by container from being + loaded, use the containerSciFilter property of the + Context.

    + +
    + Attribute + + Description +
    pluggabilitySkip +

    The comma separated list of JAR file name patterns + to skip when scanning for pluggable features introduced by Servlet 3.0 + specification. If not specified, the default is obtained from the + tomcat.util.scan.StandardJarScanFilter.jarsToSkip system + property.

    +
    pluggabilityScan +

    The comma separated list of JAR file name patterns + to scan when scanning for pluggable features introduced by Servlet 3.0 + specification. If not specified, the default is obtained from the + tomcat.util.scan.StandardJarScanFilter.jarsToScan system + property.

    +
    defaultPluggabilityScan +

    Controls if JARs are scanned or skipped by default when scanning + for the pluggable features. + If true, a JAR is scanned when its name either matches + none of pluggabilitySkip patterns or + any of pluggabilityScan patterns. + If false, a JAR is scanned when its name matches + any of pluggabilityScan patterns and + none of pluggabilitySkip patterns. + If not specified, the default value is true.

    +
    tldSkip +

    The comma separated list of JAR file name patterns + to skip when scanning for tag libraries (TLDs). + If not specified, the default is obtained + from the tomcat.util.scan.StandardJarScanFilter.jarsToSkip + system property.

    +
    tldScan +

    The comma separated list of JAR file name patterns + to scan when scanning for tag libraries (TLDs). + If not specified, the default is obtained + from the tomcat.util.scan.StandardJarScanFilter.jarsToScan + system property.

    +
    defaultTldScan +

    Controls if JARs are scanned or skipped by default when scanning + for TLDs. + If true, a JAR is scanned when its name either matches + none of tldSkip patterns or + any of tldScan patterns. + If false, a JAR is scanned when its name matches + any of tldScan patterns and + none of tldSkip patterns. + If not specified, the default value is true.

    +
    + +
    + + +

    Nested Components

    +

    No components may be nested inside a Jar Scan Filter element. +

    +

    Special Features

    +

    No special features are associated with a Jar Scan Filter + element.

    +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/jar-scanner.html b/tomcat/docs/config/jar-scanner.html new file mode 100644 index 0000000..71ad6ae --- /dev/null +++ b/tomcat/docs/config/jar-scanner.html @@ -0,0 +1,141 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - The Jar Scanner Component

    The Jar Scanner Component

    Table of Contents

    Introduction

    + +

    The Jar Scanner element represents the component that is + used to scan the web application for JAR files and directories of class files. + It is typically used during web application start to identify configuration + files such as TLDs or web-fragment.xml files that must be processed as part of + the web application initialisation.

    + +

    A Jar Scanner element MAY be nested inside a + Context component.

    + +

    For example you can include the bootstrap classpath when scanning for jar + files:

    +
    <Context>
    +  ...
    +  <JarScanner scanBootstrapClassPath="true"/>
    +  ...
    +</Context>
    + +

    If a Jar Scanner element is not included, a default Jar Scanner configuration + will be created automatically, which is sufficient for most requirements.

    + +

    Attributes

    + +

    Common Attributes

    + +

    All implementations of Jar Scanner + support the following attributes:

    + +
    + Attribute + + Description +
    className +

    Java class name of the implementation to use. This class must + implement the org.apache.tomcat.JarScanner interface. + If not specified, the standard value (defined below) will be used.

    +
    + +
    + + +

    Standard Implementation

    + +

    The standard implementation of Jar Scanner is + org.apache.tomcat.util.scan.StandardJarScanner. + It supports the following additional attributes (in addition to the + common attributes listed above):

    + +
    + Attribute + + Description +
    scanAllDirectories +

    If true, any directories found on the classpath will be + checked to see if they are expanded JAR files. + The default is false.

    +

    Tomcat determines if a directory is an expanded JAR file by looking + for a META-INF sub-directory. Only if the META-INF sub-directory exists, + the directory is assumed to be an expanded JAR file. Note that for scans + for matches to @HandlesTypes annotations, all directories + will be scanned irrespective of the presence or not of a META-INF + sub-directory.

    +
    scanAllFiles +

    If true, any files found on the classpath will be checked + to see if they are Jar files rather than relying on the file extension + being .jar. The default is false.

    +
    scanClassPath +

    If true, the full web application classpath, including + the shared and common classloaders and the system classpath (but not the + bootstrap classpath) will be scanned for Jar files in addition to the web + application. The default is true.

    +
    scanBootstrapClassPath +

    If scanClassPath is true and this is + true the bootstrap classpath will also be scanned for Jar + files. The default is false.

    +
    scanManifest +

    If true, the Manifest files of any JARs found will be + scanned for additional class path entries and those entries will be added + to the URLs to scan. The default is true.

    +
    + +
    + + +

    Nested Components

    +

    Only a Jar Scan Filter may be nested + inside a Jar Scanner element.

    +

    Special Features

    +

    No special features are associated with a Jar Scanner + element.

    +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/jaspic.html b/tomcat/docs/config/jaspic.html new file mode 100644 index 0000000..2b61d7e --- /dev/null +++ b/tomcat/docs/config/jaspic.html @@ -0,0 +1,191 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - JASPIC

    JASPIC

    Table of Contents

    Introduction

    + +

    Tomcat implements JASPIC 1.1 Maintenance Release B + (JSR 196). The + implementation is primarily intended to enable the integration of 3rd party + JASPIC authentication implementations with Tomcat.

    + +

    JASPIC may be configured dynamically by an application or statically via + the $CATALINA_BASE/conf/jaspic-providers.xml configuration file. + If present, a JASPIC configuration will over-ride any + <login-config> present in web.xml.

    + +

    Static configuration

    + +

    AuthConfigProvider

    + +

    If the 3rd party implementation includes an + AuthConfigProvider then a web application can be configured to + use it by nesting the following inside the + <jaspic-providers> element in + $CATALINA_BASE/conf/jaspic-providers.xml.

    +
    <provider name="any"
    +          className="fully.qualified.implementation.class.Name"
    +          layer="HttpServlet"
    +          appContext="Catalina/localhost /contextPath"
    +          description="any">
    +  <property name="see-provider-documentation"
    +            value="see-provider-documentation" />
    +</provider>
    + +

    The name and description attributes are not + used by Tomcat.

    + +

    The className attribute must be the fully qualified class + name of the AuthConfigProvider. The implementation may be + packaged with the web application or in Tomcat's + $CATALINA_BASE/lib directory.

    + +

    The layer attribute must be HttpServlet.

    + +

    The appContext attribute must be exactly the concatenation + of:

    +
      +
    • The engine name
    • +
    • The forward slash character
    • +
    • The host name
    • +
    • A single space
    • +
    • The context path
    • +
    + +

    If the AuthConfigProvider supports configuration via + properties these may be specified via <property> elements + nesting inside the <provide> element.

    + +
    + +

    ServerAuthModule

    + +

    If the 3rd party implementation only provides an + ServerAuthModule then it will be necessary to provide a number + of supporting classes. These may be a custom implementation or, + alternatively, Tomcat provides a simple wrapper implementation for + ServerAuthModules. +

    + +

    Tomcat's wrapper for ServerAuthModule can be configured + by nesting the following inside the + <jaspic-providers> element in + $CATALINA_BASE/conf/jaspic-providers.xml.

    +
    <provider name="any"
    +          className="org.apache.catalina.authenticator.jaspic.SimpleAuthConfigProvider"
    +          layer="HttpServlet"
    +          appContext="Catalina/localhost /contextPath"
    +          description="any">
    +  <property name="org.apache.catalina.authenticator.jaspic.ServerAuthModule.1"
    +            value="fully.qualified.implementation.class.Name" />
    +  <property name="see-provider-documentation"
    +            value="see-provider-documentation" />
    +</provider>
    + +

    The configuration is similar to the AuthConfigProvider in + the previous section but with some key differences.

    + +

    The className attribute must be + org.apache.catalina.authenticator.jaspic.SimpleAuthConfigProvider.

    + +

    The ServerAuthModule(s) are specified via properties. The + property name must be + org.apache.catalina.authenticator.jaspic.ServerAuthModule.n + where n is the index of the module. The index must start at 1 + an increment in steps of 1 until all modules are defined. The value of the + property must be the fully qualified class name of the module.

    +
    + +

    Dynamic configuration

    + +

    JASPIC modules and configuration can be packaged within a WAR file with the + web application. The web application can then register the required JASPIC + configuration when it starts using the standard JASPIC APIs.

    + +

    If parallel deployment is being used then dynamic configuration should not + be used. The JASPIC API assumes that a context path is unique for any given + host which is not the case when using parallel deployment. When using parallel + deployment, static JASPIC configuration should be used. This will require that + all versions of the application use the same JASPIC configuration.

    + +

    3rd party modules

    + +

    This is not an exhaustive list. The Tomcat community welcomes contributions + that add to this section.

    + +

    Philip Green II's module for Google OAuth 2

    + +

    The source code for this module along with the + documentation + which includes details of the necessary Google API configuration is + available on GitHub.

    + +

    A sample configuration for using this module with Tomcat would look like + this:

    +
    <jaspic-providers xmlns="https://tomcat.apache.org/xml"
    +                  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    +                  xsi:schemaLocation="https://tomcat.apache.org/xml jaspic-providers.xsd"
    +                  version="1.0">
    +  <provider name="google-oauth"
    +            className="org.apache.catalina.authenticator.jaspic.SimpleAuthConfigProvider"
    +            layer="HttpServlet"
    +            appContext="Catalina/localhost /contextPath"
    +            description="Google OAuth test">
    +    <property name="org.apache.catalina.authenticator.jaspic.ServerAuthModule.1"
    +              value="com.idmworks.security.google.GoogleOAuthServerAuthModule" />
    +    <property name="oauth.clientid"
    +              value="obtained-from-Google-console" />
    +    <property name="oauth.clientsecret"
    +              value="obtained-from-Google-console" />
    +    <property name="ignore_missing_login_context"
    +              value="true" />
    +  </provider>
    +</jaspic-providers>
    +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/listeners.html b/tomcat/docs/config/listeners.html new file mode 100644 index 0000000..78a6872 --- /dev/null +++ b/tomcat/docs/config/listeners.html @@ -0,0 +1,601 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - The LifeCycle Listener Component

    The LifeCycle Listener Component

    Table of Contents

    Introduction

    + +

    A Listener element defines a component that performs + actions when specific events occur, usually Tomcat starting or Tomcat + stopping.

    + +

    Listeners may be nested inside a Server, + Engine, Host or + Context. Some Listeners are only intended to be + nested inside specific elements. These constraints are noted in the + documentation below.

    + +

    Attributes

    + +

    Common Attributes

    + +

    All implementations of Listener + support the following attributes:

    + +
    + Attribute + + Description +
    className +

    Java class name of the implementation to use. This class must + implement the org.apache.catalina.LifecycleListener + interface.

    +
    + +
    + +

    Nested Components

    + +

    No element may be nested inside a Listener.

    + +

    Standard Implementations

    + +

    Unlike most Catalina components, there are several standard + Listener implementations available. As a result, + the className attribute MUST be used to select the + implementation you wish to use.

    + +

    APR Lifecycle Listener - org.apache.catalina.core.AprLifecycleListener

    + +

    The APR Lifecycle Listener checks for the presence of + the APR/native library and loads the library if it is present. For more + information see the APR/native guide.

    + +

    This listener must only be nested within Server + elements.

    + +

    The following additional attributes are supported by the APR + Lifecycle Listener:

    + +
    + Attribute + + Description +
    SSLEngine +

    Name of the SSLEngine to use. off: do not use SSL, + on: use SSL but no specific ENGINE.

    +

    The default value is on. This initializes the + native SSL engine, which must be enabled in the APR/native connector by + the use of the SSLEnabled attribute.

    +

    See the Official OpenSSL website + for more details on supported SSL hardware engines and manufacturers. +

    +
    SSLRandomSeed +

    Entropy source used to seed the SSLEngine's PRNG. The default value + is builtin. On development systems, you may want to set + this to /dev/urandom to allow quicker start times.

    +
    FIPSMode +

    Set to on to request that OpenSSL be in FIPS mode + (if OpenSSL is already in FIPS mode, it will remain in FIPS mode). + Set to enter to force OpenSSL to enter FIPS mode (an error + will occur if OpenSSL is already in FIPS mode). + Set to require to require that OpenSSL already be + in FIPS mode (an error will occur if OpenSSL is not already in FIPS + mode).

    +

    FIPS mode requires you to have a FIPS-capable OpenSSL library which + you must build yourself. + If this attribute is set to any of the above values, the SSLEngine + must be enabled as well.

    +

    The default value is off.

    +
    useAprConnector +

    This attribute controls the auto-selection of the connector + implementation. When the protocol is specified as + HTTP/1.1 or AJP/1.3 then if this attribute is + true the APR/native connector will be used but if this + attribute is false the NIO connector will be used.

    +
    useOpenSSL +

    This attribute controls the auto-selection of the OpenSSL JSSE + implementation. The default is true which will use OpenSSL + if the native library is available and a NIO or NIO2 connector is used.

    +
    + +
    + +

    Global Resources Lifecycle Listener - org.apache.catalina.mbeans.GlobalResourcesLifecycleListener

    + +

    The Global Resources Lifecycle Listener initializes the + Global JNDI resources defined in server.xml as part of the Global Resources element. Without this + listener, none of the Global Resources will be available.

    + +

    This listener must only be nested within Server + elements.

    + +

    No additional attributes are supported by the Global Resources + Lifecycle Listener.

    + +
    + +

    JNI Library Loading Listener - org.apache.catalina.core.JniLifecycleListener

    + +

    The JNI Library Loading Listener makes it possible + for multiple Webapps to use a native library, by loading the native + library using a shared class loader (typically the Common class loader but + may vary in some configurations)

    + +

    The listener supports two mutually exclusive attributes, so one of them must be used, but you can not use both together:

    + +
    + Attribute + + Description +
    libraryName +

    The name of the native library, as defined in + java.lang.System.loadLibrary() +

    +
    libraryPath +

    The absolute path of the native library, as defined in + java.lang.System.load() +

    +
    +
    + +

    JRE Memory Leak Prevention Listener - org.apache.catalina.core.JreMemoryLeakPreventionListener

    + +

    The JRE Memory Leak Prevention Listener provides + work-arounds for known places where the Java Runtime environment uses + the context class loader to load a singleton as this will cause a memory + leak if a web application class loader happens to be the context class + loader at the time. The work-around is to initialise these singletons when + this listener starts as Tomcat's common class loader is the context class + loader at that time. It also provides work-arounds for known issues that + can result in locked JAR files.

    + +

    This listener must only be nested within Server + elements.

    + +

    The following additional attributes are supported by the JRE + Memory Leak Prevention Listener:

    + +
    + Attribute + + Description +
    appContextProtection +

    Enables protection so that calls to + sun.awt.AppContext.getAppContext() triggered by a web + application do not result in a memory leak. Note that enabling this + protection will trigger a requirement for a graphical environment unless + Java is started in head-less mode. The default is false. + This protection is disabled if running on Java 8 onwards since the leak + has been fixed for Java 8 onwards. +

    +
    AWTThreadProtection +

    Enables protection so that calls to + java.awt.Toolkit.getDefaultToolkit() triggered by a web + application do not result in a memory leak. + Defaults to false because an AWT thread is launched. This + protection is disabled if running on Java 9 onwards since the leak has + been fixed for Java 9 onwards.

    +
    classesToInitialize +

    List of comma-separated fully qualified class names to load and initialize + during the startup of this Listener. This allows to pre-load classes that are + known to provoke classloader leaks if they are loaded during a request + processing. Non-JRE classes may be referenced, like + oracle.jdbc.driver.OracleTimeoutThreadPerVM. + The default value is empty, but specific JRE classes are loaded by other leak + protection features managed by other attributes of this Listener.

    +
    driverManagerProtection +

    The first use of java.sql.DriverManager will trigger the + loading of JDBC Drivers visible to the current class loader and its + parents. The web application level memory leak protection can take care + of this in most cases but triggering the loading here has fewer + side-effects. The default is true.

    +
    forkJoinCommonPoolProtection +

    Enables protection so the threads created for + ForkJoinPool.commonPool() do not result in a memory leak. + The protection is enabled by setting the + java.util.concurrent.ForkJoinPool.common.threadFactory + system property. If this property is set when Tomcat starts, Tomcat will + not over-ride it even if this protection is explicitly enabled. The + default is true. This protection is only used when running + on Java 8. The common pool does not exist in earlier versions and the + leak has been fixed for Java 9 onwards.

    +
    gcDaemonProtection +

    Enables protection so that calls to + sun.misc.GC.requestLatency(long) triggered by a web + application do not result in a memory leak. Use of RMI is likely to + trigger a call to this method. A side effect of enabling this protection + is the creation of a thread named "GC Daemon". The protection uses + reflection to access internal Sun classes and may generate errors on + startup on non-Sun JVMs. The default is true. This + protection is disabled if running on Java 9 onwards since the leak has + been fixed for Java 9 onwards.

    +
    ldapPoolProtection +

    Enables protection so that the PoolCleaner thread started by + com.sun.jndi.ldap.LdapPoolManager does not result in a + memory leak. The thread is started the first time the + LdapPoolManager class is used if the system property + com.sun.jndi.ldap.connect.pool.timeout is set to a value + greater than 0. Without this protection, if a web application uses this + class the PoolCleaner thread will be configured with the thread's + context class loader set to the web application class loader which in + turn will trigger a memory leak on reload. Defaults to + true. This protection is disabled if running on Java 9 + onwards since the leak has been fixed for Java 9 onwards.

    +
    securityLoginConfigurationProtection +

    Enables protection so that usage of the + javax.security.auth.login.Configuration class by a web + application does not provoke a memory leak. The first access of this + class will trigger the initializer that will retain a static reference + to the context class loader. The protection loads the class with the + system class loader to ensure that the static initializer is not + triggered by a web application. Defaults to true. This + protection is disabled if running on Java 8 onwards since the leak has + been fixed for Java 8 onwards.

    +
    securityPolicyProtection +

    Enables protection so that usage of the deprecated + javax.security.auth.Policy class by a web application does + not result in a memory leak. The first access of this class will trigger + the static initializer that will retain a static reference to the + context class loader. The protection calls the getPolicy() + method of this class to ensure that the static initializer is not + triggered by a web application. Defaults to true.

    +

    Note: The underlying leak has been fixed in Java 7 update 51 onwards + and Java 8 onwards. This protection is therefor disabled if running on + Java 8 onwards.

    +
    tokenPollerProtection +

    Enables protection so that any token poller thread initialized by + sun.security.pkcs11.SunPKCS11.initToken() does not + result in a memory leak. The thread is started depending on various + conditions as part of the initialization of the Java Cryptography + Architecture. Without the protection this can happen during Webapp + deployment when the MessageDigest for generating session IDs is + initialized. As a result the thread has the Webapp class loader as its + thread context class loader. Enabling the protection initializes JCA + early during Tomcat startup. Defaults to true. This + protection is disabled if running on Java 9 onwards since the leak has + been fixed for Java 9 onwards.

    +
    urlCacheProtection +

    Enables protection so that reading resources from JAR files using + java.net.URLConnections does not result in the JAR file + being locked. Note that enabling this protection disables caching by + default for all resources obtained via + java.net.URLConnections. Caching may be re-enabled on a + case by case basis as required. Defaults to true.

    +
    xmlParsingProtection +

    Enables protection so that parsing XML files within a web application + does not result in a memory leak. Note that memory profilers may not + display the GC root associated with this leak making it particularly + hard to diagnose. Defaults to true. This protection is + disabled if running on Java 9 onwards since the leak has been fixed for + Java 9 onwards.

    +
    + +

    JreMemoryLeakPreventionListener Examples

    + +

    The following is an example of how to configure the + classesToInitialize attribute of this listener.

    + +

    If this listener was configured in server.xml as:

    + +
      <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener"
    +            classesToInitialize="oracle.jdbc.driver.OracleTimeoutThreadPerVM" />
    + +

    then the OracleTimeoutThreadPerVM class would be loaded + and initialized during listener startup instead of during request + processing.

    + +
    + +
    + +

    Security Lifecycle Listener - org.apache.catalina.security.SecurityListener

    + +

    The Security Lifecycle Listener performs a number of + security checks when Tomcat starts and prevents Tomcat from starting if they + fail. The listener is not enabled by default. To enabled it uncomment the + listener in $CATALINA_BASE/conf/server.xml. For Tomcat versions before 8.5.30, + if the operating system supports umask then the line in + $CATALINA_HOME/bin/catalina.sh that obtains the umask also needs to be + uncommented. For Tomcat 8.5.30 and later, the umask is automatically + passed-into Tomcat.

    + +

    This listener must only be nested within Server + elements.

    + +

    The following additional attributes are supported by the Security + Lifecycle Listener:

    + +
    + Attribute + + Description +
    checkedOsUsers +

    A comma separated list of OS users that must not be used to start + Tomcat. If not specified, the default value of root is used. To + disable this check, set the attribute to the empty string. Usernames + are checked in a case-insensitive manner.

    +
    minimumUmask +

    The least restrictive umask that must be configured before Tomcat + will start. If not specified, the default value of 0007 is used. + To disable this check, set the attribute to the empty string. The check + is not performed on Windows platforms.

    +
    + +
    + +

    StoreConfig Lifecycle Listener - org.apache.catalina.storeconfig.StoreConfigLifecycleListener

    + +

    The StoreConfig Lifecycle Listener configures a + StoreConfig MBean that may be used to save the current server configuration + in server.xml or the current configuration for a web application in a + context.xml file.

    + +

    This listener must only be nested within Server + elements.

    + +

    The following additional attributes are supported by the + StoreConfig Lifecycle Listener:

    + +
    + Attribute + + Description +
    storeConfigClass +

    The name of the IStoreConfig implementation to use. If + not specified the default of + org.apache.catalina.storeconfig.StoreConfig will be + used.

    +
    storeRegistry +

    The URL of the configuration file that configures how the + IStoreConfig is to save the configuration. If not specified + the built in resource + /org/apache/catalina/storeconfig/server-registry.xml will + be used.

    +
    + +
    + +

    ThreadLocal Leak Prevention Listener - org.apache.catalina.core.ThreadLocalLeakPreventionListener

    + +

    The ThreadLocal Leak Prevention Listener triggers the + renewal of threads in Executor pools when a + Context is being stopped to avoid thread-local + related memory leaks. Active threads will be renewed one by one when they + come back to the pool after executing their task. The renewal happens + only for contexts that have their renewThreadsWhenStoppingContext + attribute set to true.

    + +

    This listener must only be nested within Server + elements.

    + +

    No additional attributes are supported by the ThreadLocal Leak + Prevention Listener.

    + +
    + +

    UserConfig - org.apache.catalina.startup.UserConfig

    + +

    The UserConfig provides feature of User Web Applications. + User Web Applications map a request URI starting with a tilde character ("~") + and a username to a directory (commonly named public_html) in that user's + home directory on the server.

    + +

    See the User Web Applications + special feature on the Host element for more information.

    + +

    The following additional attributes are supported by the + UserConfig:

    + +
    + Attribute + + Description +
    directoryName +

    The directory name to be searched for within each user home directory. + The default is public_html.

    +
    userClass +

    The class name of the user database class. + There are currently two user database, the + org.apache.catalina.startup.PasswdUserDatabase is used on a + Unix system that uses the /etc/passwd file to identify valid users. + The org.apache.catalina.startup.HomesUserDatabase is used on + a server where /etc/passwd is not in use. HomesUserDatabase deploy all + directories found in a specified base directory.

    +
    homeBase +

    The base directory containing user home directories. This is effective + only when org.apache.catalina.startup.HomesUserDatabase is + used.

    +
    allow +

    A regular expression defining user who deployment is allowed. If this + attribute is specified, the user to deploy must match for this pattern. + If this attribute is not specified, all users will be deployed unless the + user matches a deny pattern.

    +
    deny +

    A regular expression defining user who deployment is denied. If this + attribute is specified, the user to deploy must not match for this + pattern. If this attribute is not specified, deployment of user will be + governed by a allow attribute.

    +
    + +
    + +

    Version Logging Lifecycle Listener - org.apache.catalina.startup.VersionLoggerListener

    + +

    The Version Logging Lifecycle Listener logs Tomcat, Java + and operating system information when Tomcat starts.

    + +

    This listener must only be nested within Server + elements and should be the first listener defined.

    + +

    The following additional attributes are supported by the Version + Logging Lifecycle Listener:

    + +
    + Attribute + + Description +
    logArgs +

    If true, the command line arguments passed to Java when + Tomcat started will be logged. If not specified, the default value of + true will be used.

    +
    logEnv +

    If true, the current environment variables when Tomcat + starts will be logged. If not specified, the default value of + false will be used.

    +
    logProps +

    If true, the current Java system properties will be + logged. If not specified, the default value of + false will be used.

    +
    + +
    + +

    Additional Implementations

    + +

    JMX Remote Lifecycle Listener - org.apache.catalina.mbeans.JmxRemoteLifecycleListener

    + +

    This listener requires catalina-jmx-remote.jar to be placed + in $CATALINA_HOME/lib. This jar may be found in the extras + directory of the binary download area.

    + +

    The JMX Remote Lifecycle Listener fixes the ports used by + the JMX/RMI Server making things much simpler if you need to connect + jconsole or a similar tool to a remote Tomcat instance that is running + behind a firewall. Only these ports are configured via the listener. The + remainder of the configuration is via the standard system properties for + configuring JMX. For further information on configuring JMX see + + Monitoring and Management Using JMX included with the Java SDK + documentation.

    + +

    This listener must only be nested within a Server + element.

    + +

    The following additional attributes are supported by the JMX Remote + Lifecycle Listener:

    + +
    + Attribute + + Description +
    rmiRegistryPortPlatform +

    The port to be used by the JMX/RMI registry for the Platform MBeans. + This replaces the use of the + com.sun.management.jmxremote.port system property that + should not be set when using this listener.

    +
    rmiServerPortPlatform +

    The port to be used by the Platform JMX/RMI server.

    +
    rmiBindAddress +

    The address of the interface to be used by JMX/RMI server.

    +
    useLocalPorts +

    Should any clients using these ports be forced to use local ports to + connect to the JMX/RMI server. This is useful when tunnelling + connections over SSH or similar. Defaults to false.

    +
    + +

    Using file-based Authentication and Authorisation

    + +

    If this listener was configured in server.xml as:

    +
      <Listener className="org.apache.catalina.mbeans.JmxRemoteLifecycleListener"
    +          rmiRegistryPortPlatform="10001" rmiServerPortPlatform="10002" />
    +

    with the following system properties set (e.g. in setenv.sh):

    +
      -Dcom.sun.management.jmxremote.password.file=$CATALINA_BASE/conf/jmxremote.password
    +  -Dcom.sun.management.jmxremote.access.file=$CATALINA_BASE/conf/jmxremote.access
    +  -Dcom.sun.management.jmxremote.ssl=false
    +

    $CATALINA_BASE/conf/jmxremote.password containing:

    +
    admin letmein
    +

    $CATALINA_BASE/conf/jmxremote.access containing:

    +
    admin readwrite
    +

    then opening ports 10001 (RMI Registry) and 10002 (JMX/RMI Server) in your + firewall would enable jconsole to connect to a Tomcat instance running + behind a firewall using a connection string of the form:

    +
    service:jmx:rmi://<hostname>:10002/jndi/rmi://<hostname>:10001/jmxrmi
    +

    + with a user name of admin and a password of + letmein. +

    + +

    Using JAAS

    + +

    If we use the following system properties instead:

    +
      -Dcom.sun.management.jmxremote.login.config=Tomcat
    +  -Djava.security.auth.login.config=$CATALINA_BASE/conf/login.config
    +  -Dcom.sun.management.jmxremote.access.file=$CATALINA_BASE/conf/jmxremote.access
    +  -Dcom.sun.management.jmxremote.ssl=false
    +

    $CATALINA_BASE/conf/login.config containing your choice of JAAS LoginModule implementation, for example:

    +
      Tomcat { /* should match to the com.sun.management.jmxremote.login.config property */
    +
    +    /* for illustration purposes only */
    +    com.sun.security.auth.module.LdapLoginModule REQUIRED
    +      userProvider="ldap://ldap-svr/ou=people,dc=example,dc=com"
    +      userFilter="(&(uid={USERNAME})(objectClass=inetOrgPerson))"
    +      authzIdentity="admin"
    +      debug=true;
    +  };
    +

    $CATALINA_BASE/conf/jmxremote.access containing:

    +
    admin readwrite
    +

    + then we would need to provide LDAP credentials instead. +

    + +

    Note that the examples above do not use SSL. JMX access should + be considered equivalent to administrative access and secured accordingly. +

    + +
    + +

    System property replacement - org.apache.catalina.util.SystemPropertyReplacerListener

    + +

    This listener performs system property replacement using the property + source configured on the digester. When ${parameter} + denoted parameters are found in the values of system properties, + the property source will be invoked to attempt to replace it.

    + +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/loader.html b/tomcat/docs/config/loader.html new file mode 100644 index 0000000..c06010b --- /dev/null +++ b/tomcat/docs/config/loader.html @@ -0,0 +1,161 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - The Loader Component

    The Loader Component

    Table of Contents

    Introduction

    + +

    The Loader element represents the web + application class loader that will be used to load Java + classes and resources for your web application. Such + a class loader must follow the requirements of the Servlet + Specification, and load classes from the following locations:

    +
      +
    • From the /WEB-INF/classes directory inside your + web application.
    • +
    • From JAR files in the /WEB-INF/lib directory + inside your web application.
    • +
    • From resources made available by Catalina to all web + applications globally.
    • +
    + +

    A Loader element MAY be nested inside a Context + component. If it is not included, a default Loader configuration will be + created automatically, which is sufficient for most requirements.

    + +

    For a more in-depth description of the class loader hierarchy + that is implemented by Catalina, see the ClassLoader HowTo.

    + +

    The description below uses the variable name $CATALINA_BASE to refer the + base directory against which most relative paths are resolved. If you have + not configured Tomcat for multiple instances by setting a CATALINA_BASE + directory, then $CATALINA_BASE will be set to the value of $CATALINA_HOME, + the directory into which you have installed Tomcat.

    + +

    Attributes

    + +

    Common Attributes

    + +

    All implementations of Loader + support the following attributes:

    + +
    + Attribute + + Description +
    className +

    Java class name of the implementation to use. This class must + implement the org.apache.catalina.Loader interface. + If not specified, the standard value (defined below) will be used.

    +
    delegate +

    Set to true if you want the class loader to follow + the standard Java2 delegation model, and attempt to load classes from + parent class loaders before looking inside the web + application. Set to false (the default) to have the + class loader look inside the web application first, before asking + parent class loaders to find requested classes or resources.

    +
    reloadable +

    Set to true if you want Catalina to monitor classes in + /WEB-INF/classes/ and /WEB-INF/lib for + changes, and automatically reload the web application if a change + is detected. This feature is very useful during application + development, but it requires significant runtime overhead and is + not recommended for use on deployed production applications. You + can use the Manager web + application, however, to trigger reloads of deployed applications + on demand.

    + +

    NOTE - The value for this property will be + inherited from the reloadable attribute you set on + the surrounding Context component, + and any value you explicitly set here will be replaced.

    +
    + +
    + + +

    Standard Implementation

    + +

    The standard implementation of Loader is + org.apache.catalina.loader.WebappLoader. + It supports the following additional attributes (in addition to the + common attributes listed above):

    + +
    + Attribute + + Description +
    loaderClass +

    Java class name of the java.lang.ClassLoader + implementation class to use. Custom implementations must extend + org.apache.catalina.loader.WebappClassLoaderBase. +

    + +

    If not specified, the default value is + org.apache.catalina.loader.ParallelWebappClassLoader. The + default loaderClass is parallel capable, which + means that multiple threads may load difference classes in parallel. + A non-parallel capable loaderClass is available and can + be used by specifying + org.apache.catalina.loader.WebappClassLoader.

    +
    + +
    + +

    Nested Components

    + +

    No components may be nested inside a Loader element.

    + +

    Special Features

    + +

    Logging

    + +

    A loader is associated with the log category based on its classname.

    + +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/manager.html b/tomcat/docs/config/manager.html new file mode 100644 index 0000000..1333f52 --- /dev/null +++ b/tomcat/docs/config/manager.html @@ -0,0 +1,492 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - The Manager Component

    The Manager Component

    Table of Contents

    Introduction

    + +

    The Manager element represents the session + manager that will be used to create and maintain HTTP sessions + as requested by the associated web application.

    + +

    A Manager element MAY be nested inside a + Context component. If it is not included, + a default Manager configuration will be created automatically, which + is sufficient for most requirements, — see + Standard Manager Implementation below for the details + of this configuration.

    + +

    Attributes

    + +

    Common Attributes

    + +

    All implementations of Manager + support the following attributes:

    + +
    + Attribute + + Description +
    className +

    Java class name of the implementation to use. This class must + implement the org.apache.catalina.Manager interface. + If not specified, the standard value (defined below) will be used.

    +
    maxActiveSessions +

    The maximum number of active sessions that will be created by + this Manager, or -1 (the default) for no limit.

    + +

    When the limit is reached, any attempt to create a new session + (e.g. with HttpServletRequest.getSession() call) + will fail with an IllegalStateException.

    +
    + +
    + + +

    Standard Implementation

    + +

    Tomcat provides two standard implementations of Manager + for use — the default one stores active sessions, while the optional one + stores active sessions that have been swapped out (in addition to saving + sessions across a restart of Tomcat) in a storage location that is selected + via the use of an appropriate Store nested element.

    + +

    Standard Manager Implementation

    + +

    The standard implementation of Manager is + org.apache.catalina.session.StandardManager. + It supports the following additional attributes (in addition to the + common attributes listed above):

    + +
    + Attribute + + Description +
    pathname +

    Absolute or relative (to the work directory for this Context) + pathname of the file in which session state will be preserved + across application restarts, if possible. The default is + "SESSIONS.ser".
    See + Persistence Across Restarts + for more information. This persistence may be + disabled by setting this attribute to an empty string.

    +
    processExpiresFrequency +

    Frequency of the session expiration, and related manager operations. + Manager operations will be done once for the specified amount of + backgroundProcess calls (i.e., the lower the amount, the more often the + checks will occur). The minimum value is 1, and the default value is 6. +

    +
    secureRandomClass +

    Name of the Java class that extends + java.security.SecureRandom to use to generate session IDs. + If not specified, the default value is + java.security.SecureRandom.

    +
    secureRandomProvider +

    Name of the provider to use to create the + java.security.SecureRandom instances that generate session + IDs. If an invalid algorithm and/or provider is specified, the Manager + will use the platform default provider and the default algorithm. If not + specified, the platform default provider will be used.

    +
    secureRandomAlgorithm +

    Name of the algorithm to use to create the + java.security.SecureRandom instances that generate session + IDs. If an invalid algorithm and/or provider is specified, the Manager + will use the platform default provider and the default algorithm. If not + specified, the default algorithm of SHA1PRNG will be used. If the + default algorithm is not supported, the platform default will be used. + To specify that the platform default should be used, do not set the + secureRandomProvider attribute and set this attribute to the empty + string.

    +
    sessionAttributeNameFilter +

    A regular expression used to filter which session attributes will be + distributed. An attribute will only be distributed if its name matches + this pattern. If the pattern is zero length or null, all + attributes are eligible for distribution. The pattern is anchored so the + session attribute name must fully match the pattern. As an example, the + value (userName|sessionHistory) will only distribute the + two session attributes named userName and + sessionHistory. If not specified, the default value of + null will be used.

    +
    sessionAttributeValueClassNameFilter +

    A regular expression used to filter which session attributes will be + distributed. An attribute will only be distributed if the implementation + class name of the value matches this pattern. If the pattern is zero + length or null, all attributes are eligible for + distribution. The pattern is anchored so the fully qualified class name + must fully match the pattern. If not specified, the default value of + null will be used unless a SecurityManager is + enabled in which case the default will be + java\\.lang\\.(?:Boolean|Integer|Long|Number|String).

    +
    warnOnSessionAttributeFilterFailure +

    If sessionAttributeNameFilter or + sessionAttributeValueClassNameFilter blocks an + attribute, should this be logged at WARN level? If + WARN level logging is disabled then it will be logged at + DEBUG. The default value of this attribute is + false unless a SecurityManager is enabled in + which case the default will be true.

    +
    + +

    Persistent Manager Implementation

    + +

    NOTE: You must set either the + org.apache.catalina.session.StandardSession.ACTIVITY_CHECK or + org.apache.catalina.STRICT_SERVLET_COMPLIANCE + system properties to true for + the persistent manager to work correctly.

    + +

    The persistent implementation of Manager is + org.apache.catalina.session.PersistentManager. In + addition to the usual operations of creating and deleting sessions, a + PersistentManager has the capability to swap active (but + idle) sessions out to a persistent storage mechanism, as well as to save + all sessions across a normal restart of Tomcat. The actual persistent + storage mechanism used is selected by your choice of a + Store element nested inside the Manager + element - this is required for use of PersistentManager.

    + +

    This implementation of Manager supports the following attributes in + addition to the Common Attributes + described earlier.

    + +
    + Attribute + + Description +
    className +

    It has the same meaning as described in the + Common Attributes above. + You must specify + org.apache.catalina.session.PersistentManager to use + this manager implementation.

    +
    maxIdleBackup +

    The time interval (in seconds) since the last access to a session + before it is eligible for being persisted to the session store, or + -1 to disable this feature. By default, this feature is + disabled.

    +
    maxIdleSwap +

    The maximum time a session may be idle before it is eligible to be + swapped to disk due to inactivity. Setting this to -1 means + sessions should not be swapped out just because of inactivity. If this + feature is enabled, the time interval specified here should be equal to + or longer than the value specified for maxIdleBackup. By + default, this feature is disabled.

    +
    minIdleSwap +

    The minimum time in seconds a session must be idle before it is + eligible to be swapped to disk to keep the active session count below + maxActiveSessions. Setting to -1 means sessions will not be + swapped out to keep the active session count down. If specified, this + value should be less than that specified by maxIdleSwap. + By default, this value is set to -1.

    +
    processExpiresFrequency +

    It is the same as described above for the + org.apache.catalina.session.StandardManager class. +

    +
    saveOnRestart +

    Should all sessions be persisted and reloaded when Tomcat is shut + down and restarted (or when this application is reloaded)? By default, + this attribute is set to true.

    +
    secureRandomClass +

    It is the same as described above for the + org.apache.catalina.session.StandardManager class. +

    +
    secureRandomProvider +

    It is the same as described above for the + org.apache.catalina.session.StandardManager class. +

    +
    secureRandomAlgorithm +

    It is the same as described above for the + org.apache.catalina.session.StandardManager class. +

    +
    sessionAttributeNameFilter +

    A regular expression used to filter which session attributes will be + distributed. An attribute will only be distributed if its name matches + this pattern. If the pattern is zero length or null, all + attributes are eligible for distribution. The pattern is anchored so the + session attribute name must fully match the pattern. As an example, the + value (userName|sessionHistory) will only distribute the + two session attributes named userName and + sessionHistory. If not specified, the default value of + null will be used.

    +
    sessionAttributeValueClassNameFilter +

    A regular expression used to filter which session attributes will be + distributed. An attribute will only be distributed if the implementation + class name of the value matches this pattern. If the pattern is zero + length or null, all attributes are eligible for + distribution. The pattern is anchored so the fully qualified class name + must fully match the pattern. If not specified, the default value of + null will be used unless a SecurityManager is + enabled in which case the default will be + java\\.lang\\.(?:Boolean|Integer|Long|Number|String).

    +
    warnOnSessionAttributeFilterFailure +

    If sessionAttributeNameFilter or + sessionAttributeValueClassNameFilter blocks an + attribute, should this be logged at WARN level? If + WARN level logging is disabled then it will be logged at + DEBUG. The default value of this attribute is + false unless a SecurityManager is enabled in + which case the default will be true.

    +
    + +

    In order to successfully use a PersistentManager, you must nest inside + it a <Store> element, as described below.

    + +
    + + +

    Nested Components

    + +

    All Manager Implementations

    + +

    All Manager implementations allow nesting of a + <SessionIdGenerator> element. It defines + the behavior of session id generation. All implementations + of the SessionIdGenerator allow the + following attributes: +

    + +
    + Attribute + + Description +
    sessionIdLength +

    The length of the session ID may be changed with the + sessionIdLength attribute. +

    +
    + +

    Persistent Manager Implementation

    + +

    If you are using the Persistent Manager Implementation + as described above, you MUST nest a + <Store> element inside, which defines the + characteristics of the persistent data storage. Two implementations + of the <Store> element are currently available, + with different characteristics, as described below.

    + +
    File Based Store
    + +

    The File Based Store implementation saves swapped out + sessions in individual files (named based on the session identifier) + in a configurable directory. Therefore, you are likely to encounter + scalability problems as the number of active sessions increases, and + this should primarily be considered a means to easily experiment.

    + +

    To configure this, add a <Store> nested inside + your <Manager> element with the following attributes: +

    + +
    + Attribute + + Description +
    className +

    Java class name of the implementation to use. This class must + implement the org.apache.catalina.Store interface. You + must specify + org.apache.catalina.session.FileStore + to use this implementation.

    +
    directory +

    Absolute or relative (to the temporary work directory for this web + application) pathname of the directory into which individual session + files are written. If not specified, the temporary work directory + assigned by the container is utilized.

    +
    + + +
    JDBC Based Store
    + +

    The JDBC Based Store implementation saves swapped out + sessions in individual rows of a preconfigured table in a database + that is accessed via a JDBC driver. With large numbers of swapped out + sessions, this implementation will exhibit improved performance over + the File Based Store described above.

    + +

    To configure this, add a <Store> nested inside + your <Manager> element with the following attributes: +

    + +
    + Attribute + + Description +
    className +

    Java class name of the implementation to use. This class must + implement the org.apache.catalina.Store interface. You + must specify + org.apache.catalina.session.JDBCStore + to use this implementation.

    +
    connectionName +

    The user name that will be handed to the configured JDBC driver to + establish a connection to the database containing the session table.

    +
    connectionPassword +

    The password that will be handed to the configured JDBC driver to + establish a connection to the database containing the session table.

    +
    connectionURL +

    The connection URL that will be handed to the configured JDBC + driver to establish a connection to the database containing our + session table.

    +
    dataSourceName +

    Name of the JNDI resource for a JDBC DataSource-factory. If this option + is given and a valid JDBC resource can be found, it will be used and any + direct configuration of a JDBC connection via connectionURL, + connectionName, connectionPassword and + driverName will be ignored. Since this code uses prepared + statements, you might want to configure pooled prepared statements as + shown in the JNDI resources + How-To.

    +
    driverName +

    Java class name of the JDBC driver to be used.

    +
    localDataSource +

    This allows the Store to use a DataSource defined for the Context + rather than a global DataSource. If not specified, the default is + false: use a global DataSource.

    +
    sessionAppCol +

    Name of the database column, contained in the specified session table, + that contains the Engine, Host, and Web Application Context name in the + format /Engine/Host/Context. If not specified the default + value of app will be used.

    +
    sessionDataCol +

    Name of the database column, contained in the specified session table, + that contains the serialized form of all session attributes for a swapped + out session. The column type must accept a binary object (typically called + a BLOB). If not specified the default value of data will be + used.

    +
    sessionIdCol +

    Name of the database column, contained in the specified session table, + that contains the session identifier of the swapped out session. The + column type must accept character string data of at least as many + characters as are contained in session identifiers created by Tomcat + (typically 32). If not specified the default value of id will + be used.

    +
    sessionLastAccessedCol +

    Name of the database column, contained in the specified session table, + that contains the lastAccessedTime property of this session. + The column type must accept a Java long (64 bits). If not + specified the default value of maxinactive will be used.

    +
    sessionMaxInactiveCol +

    Name of the database column, contained in the specified session table, + that contains the maxInactiveInterval property of this + session. The column type must accept a Java integer (32 + bits). If not specified, the default value of maxinactive + will be used.

    +
    sessionTable +

    Name of the database table to be used for storing swapped out sessions. + This table must contain (at least) the database columns that are + configured by the other attributes of this element. If not specified the + default value of tomcat$sessions will be used.

    +
    sessionValidCol +

    Name of the database column, contained in the specified session table, + that contains a flag indicating whether this swapped out session is still + valid or not. The column type must accept a single character. If not + specified the default value of valid will be used.

    +
    + +

    Before attempting to use the JDBC Based Store for the first time, + you must create the table that will be used to store swapped out sessions. + Detailed SQL commands vary depending on the database you are using, but + a script like this will generally be required:

    + +
    create table tomcat_sessions (
    +  session_id     varchar(100) not null primary key,
    +  valid_session  char(1) not null,
    +  max_inactive   int not null,
    +  last_access    bigint not null,
    +  app_name       varchar(255),
    +  session_data   mediumblob,
    +  KEY kapp_name(app_name)
    +);
    + +

    Note: The SQL command above does not use the default names for either the + table or the columns so the JDBC Store would need to be configured to reflect + this.

    + +

    In order for the JDBC Based Store to successfully connect to your + database, the JDBC driver you configure must be visible to Tomcat's + internal class loader. Generally, that means you must place the JAR + file containing this driver into the $CATALINA_HOME/lib + directory.

    + +

    Special Features

    + + +

    Persistence Across Restarts

    + +

    Whenever Apache Tomcat is shut down normally and restarted, or when an + application reload is triggered, the standard Manager implementation + will attempt to serialize all currently active sessions to a disk + file located via the pathname attribute. All such saved + sessions will then be deserialized and activated (assuming they have + not expired in the mean time) when the application reload is completed.

    + +

    In order to successfully restore the state of session attributes, + all such attributes MUST implement the java.io.Serializable + interface. You MAY cause the Manager to enforce this restriction by + including the <distributable> element in your web + application deployment descriptor (/WEB-INF/web.xml).

    + +

    The persistence across restarts provided by the + StandardManager is a simpler implementation than that + provided by the PersistentManager. If robust, production + quality persistence across restarts is required then the + PersistentManager should be used with an appropriate + configuration.

    + +
    + +

    Disable Session Persistence

    + +

    As documented above, every web application by default has + standard manager implementation configured, and it performs session + persistence across restarts. To disable this persistence feature, create + a Context configuration file for your web + application and add the following element there:

    + +
    <Manager pathname="" />
    +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/realm.html b/tomcat/docs/config/realm.html new file mode 100644 index 0000000..34e0ec4 --- /dev/null +++ b/tomcat/docs/config/realm.html @@ -0,0 +1,1016 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - The Realm Component

    The Realm Component

    Table of Contents

    Introduction

    + +

    A Realm element represents a "database" of usernames, + passwords, and roles (similar to Unix groups) assigned + to those users. Different implementations of Realm allow Catalina to be + integrated into environments where such authentication information is already + being created and maintained, and then utilize that information to implement + Container Managed Security as described in the Servlet + Specification.

    + +

    A Catalina container (Engine, + Host, or Context) may + contain no more than one Realm element (although if supported by the Realm + this one Realm may itself contain multiple nested Realms). In addition, the + Realm associated with an Engine or a Host is automatically inherited by + lower-level containers unless the lower level container explicitly defines its + own Realm. If no Realm is configured for the Engine, an instance of the + Null Realm + will be configured for the Engine automatically.

    + +

    For more in-depth information about container managed security in web + applications, as well as more information on configuring and using the + standard realm component implementations, please see the + Container-Managed Security Guide. +

    + +

    The description below uses the variable name $CATALINA_BASE to refer the + base directory against which most relative paths are resolved. If you have + not configured Tomcat for multiple instances by setting a CATALINA_BASE + directory, then $CATALINA_BASE will be set to the value of $CATALINA_HOME, + the directory into which you have installed Tomcat.

    + +

    Attributes

    + +

    Common Attributes

    + +

    All implementations of Realm + support the following attributes:

    + +
    + Attribute + + Description +
    className +

    Java class name of the implementation to use. This class must + implement the org.apache.catalina.Realm interface.

    +
    + +

    Unlike most Catalina components, there are several standard + Realm implementations available. As a result, + the className attribute MUST be used to select the + implementation you wish to use.

    + +
    + + +

    JDBC Database Realm - org.apache.catalina.realm.JDBCRealm

    + +

    The JDBC Database Realm connects Tomcat to + a relational database, accessed through an appropriate JDBC driver, + to perform lookups of usernames, passwords, and their associated + roles. Because the lookup is done each time that it is required, + changes to the database will be immediately reflected in the + information used to authenticate new logins.

    + +

    A rich set of additional attributes lets you configure the required + connection to the underlying database, as well as the table and + column names used to retrieve the required information:

    + +
    + Attribute + + Description +
    allRolesMode +

    This attribute controls how the special role name * is + handled when processing authorization constraints in web.xml. By + default, the specification compliant value of strict is + used which means that the user must be assigned one of the roles defined + in web.xml. The alternative values are authOnly which means + that the user must be authenticated but no check is made for assigned + roles and strictAuthOnly which means that the user must be + authenticated and no check will be made for assigned roles unless roles + are defined in web.xml in which case the user must be assigned at least + one of those roles.

    +

    When this attribute has the value of authOnly or + strictAuthOnly, the roleNameCol and + userRoleTable attributes become optional. If those two + attributes are omitted, the user's roles will not be loaded by this + Realm.

    +
    connectionName +

    The database username to use when establishing the JDBC + connection.

    +
    connectionPassword +

    The database password to use when establishing the JDBC + connection.

    +
    connectionURL +

    The connection URL to be passed to the JDBC driver when + establishing a database connection.

    +
    driverName +

    Fully qualified Java class name of the JDBC driver to be + used to connect to the authentication database.

    +
    roleNameCol +

    Name of the column, in the "user roles" table, which contains + a role name assigned to the corresponding user.

    +

    This attribute is required in majority of + configurations. See allRolesMode attribute for + a rare case when it can be omitted.

    +
    stripRealmForGss +

    When processing users authenticated via the GSS-API, this attribute + controls if any "@..." is removed from the end of the user + name. If not specified, the default is true.

    +
    transportGuaranteeRedirectStatus +

    The HTTP status code to use when the container needs to issue an HTTP + redirect to meet the requirements of a configured transport + guarantee. The provided status code is not validated. If not + specified, the default value of 302 is used.

    +
    userCredCol +

    Name of the column, in the "users" table, which contains + the user's credentials (i.e. password). If a + CredentialHandler is specified, this component + will assume that the passwords have been encoded with the + specified algorithm. Otherwise, they will be assumed to be + in clear text.

    +
    userNameCol +

    Name of the column, in the "users" and "user roles" table, + that contains the user's username.

    +
    userRoleTable +

    Name of the "user roles" table, which must contain columns + named by the userNameCol and roleNameCol + attributes.

    +

    This attribute is required in majority of + configurations. See allRolesMode attribute for + a rare case when it can be omitted.

    +
    userTable +

    Name of the "users" table, which must contain columns named + by the userNameCol and userCredCol + attributes.

    +
    X509UsernameRetrieverClassName +

    When using X509 client certificates, this specifies the class name + that will be used to retrieve the user name from the certificate. + The class must implement the + org.apache.catalina.realm.X509UsernameRetriever + interface. The default is to use the certificate's SubjectDN + as the username.

    +
    + +

    See the Container-Managed Security Guide for more + information on setting up container managed security using the + JDBC Database Realm component.

    + +
    + + +

    DataSource Database Realm - org.apache.catalina.realm.DataSourceRealm

    + +

    The DataSource Database Realm connects Tomcat to + a relational database, accessed through a JNDI named JDBC DataSource + to perform lookups of usernames, passwords, and their associated + roles. Because the lookup is done each time that it is required, + changes to the database will be immediately reflected in the + information used to authenticate new logins.

    + +

    The JDBC Realm uses a single db connection. This requires that + realm based authentication be synchronized, i.e. only one authentication + can be done at a time. This could be a bottleneck for applications + with high volumes of realm based authentications.

    + +

    The DataSource Database Realm supports simultaneous realm based + authentications and allows the underlying JDBC DataSource to + handle optimizations like database connection pooling.

    + +

    A rich set of additional attributes lets you configure the name + of the JNDI JDBC DataSource, as well as the table and + column names used to retrieve the required information:

    + +
    + Attribute + + Description +
    allRolesMode +

    This attribute controls how the special role name * is + handled when processing authorization constraints in web.xml. By + default, the specification compliant value of strict is + used which means that the user must be assigned one of the roles defined + in web.xml. The alternative values are authOnly which means + that the user must be authenticated but no check is made for assigned + roles and strictAuthOnly which means that the user must be + authenticated and no check will be made for assigned roles unless roles + are defined in web.xml in which case the user must be assigned at least + one of those roles.

    +

    When this attribute has the value of authOnly or + strictAuthOnly, the roleNameCol and + userRoleTable attributes become optional. If those two + attributes are omitted, the user's roles will not be loaded by this + Realm.

    +
    dataSourceName +

    The name of the JNDI JDBC DataSource for this Realm.

    +
    localDataSource +

    When the realm is nested inside a Context element, this allows the + realm to use a DataSource defined for the Context rather than a global + DataSource. If not specified, the default is false: use a + global DataSource.

    +
    roleNameCol +

    Name of the column, in the "user roles" table, which contains + a role name assigned to the corresponding user.

    +

    This attribute is required in majority of + configurations. See allRolesMode attribute for + a rare case when it can be omitted.

    +
    transportGuaranteeRedirectStatus +

    The HTTP status code to use when the container needs to issue an HTTP + redirect to meet the requirements of a configured transport + guarantee. The provided status code is not validated. If not + specified, the default value of 302 is used.

    +
    stripRealmForGss +

    When processing users authenticated via the GSS-API, this attribute + controls if any "@..." is removed from the end of the user + name. If not specified, the default is true.

    +
    userCredCol +

    Name of the column, in the "users" table, which contains + the user's credentials (i.e. password). If a + CredentialHandler is specified, this component + will assume that the passwords have been encoded with the + specified algorithm. Otherwise, they will be assumed to be + in clear text.

    +
    userNameCol +

    Name of the column, in the "users" and "user roles" table, + that contains the user's username.

    +
    userRoleTable +

    Name of the "user roles" table, which must contain columns + named by the userNameCol and roleNameCol + attributes.

    +

    This attribute is required in majority of + configurations. See allRolesMode attribute for + a rare case when it can be omitted.

    +
    userTable +

    Name of the "users" table, which must contain columns named + by the userNameCol and userCredCol + attributes.

    +
    X509UsernameRetrieverClassName +

    When using X509 client certificates, this specifies the class name + that will be used to retrieve the user name from the certificate. + The class must implement the + org.apache.catalina.realm.X509UsernameRetriever + interface. The default is to use the certificate's SubjectDN + as the username.

    +
    + +

    See the + DataSource Realm How-To for more information on setting up container + managed security using the DataSource Database Realm component.

    + +
    + + +

    JNDI Directory Realm - org.apache.catalina.realm.JNDIRealm

    + +

    The JNDI Directory Realm connects Tomcat to + an LDAP Directory, accessed through an appropriate JNDI driver, + that stores usernames, passwords, and their associated + roles. Changes to the directory are immediately reflected in the + information used to authenticate new logins.

    + + +

    The directory realm supports a variety of approaches to using + LDAP for authentication:

    + +
      +
    • The realm can either use a pattern to determine the + distinguished name (DN) of the user's directory entry, or search + the directory to locate that entry. +
    • + +
    • The realm can authenticate the user either by binding to the + directory with the DN of the user's entry and the password + presented by the user, or by retrieving the password from the + user's entry and performing a comparison locally. +
    • + +
    • Roles may be represented in the directory as explicit entries + found by a directory search (e.g. group entries of which the user + is a member), as the values of an attribute in the user's entry, + or both. +
    • +
    + +

    A rich set of additional attributes lets you configure the + required behaviour as well as the connection to the underlying + directory and the element and attribute names used to retrieve + information from the directory:

    + +
    + Attribute + + Description +
    adCompat +

    Microsoft Active Directory often returns referrals. + When iterating over NamingEnumerations these lead to + PartialResultExceptions. If you want us to ignore those exceptions, + set this attribute to "true". Unfortunately there's no stable way + to detect, if the Exceptions really come from an AD referral. + The default value is "false".

    +
    allRolesMode +

    This attribute controls how the special role name * is + handled when processing authorization constraints in web.xml. By + default, the specification compliant value of strict is + used which means that the user must be assigned one of the roles defined + in web.xml. The alternative values are authOnly which means + that the user must be authenticated but no check is made for assigned + roles and strictAuthOnly which means that the user must be + authenticated and no check will be made for assigned roles unless roles + are defined in web.xml in which case the user must be assigned at least + one of those roles.

    +
    alternateURL +

    If a socket connection cannot be made to the provider at + the connectionURL an attempt will be made to use the + alternateURL.

    +
    authentication +

    A string specifying the type of authentication to use. + "none", "simple", "strong" or a provider specific definition + can be used. If no value is given the providers default is used.

    +
    cipherSuites +

    Specify which cipher suites are allowed when trying to open + a secured connection using StartTLS. The allowed cipher suites + are specified by a comma separated list. The default is to use the + cipher suites of the JVM.

    +
    commonRole +

    A role name assigned to each successfully authenticated user in + addition to the roles retrieved from LDAP. If not specified, only + the roles retrieved via LDAP are used.

    +
    connectionName +

    The directory username to use when establishing a + connection to the directory for LDAP search operations. If not + specified an anonymous connection is made, which is often + sufficient unless you specify the userPassword + property.

    +
    connectionPassword +

    The directory password to use when establishing a + connection to the directory for LDAP search operations. If not + specified an anonymous connection is made, which is often + sufficient unless you specify the userPassword + property.

    +
    connectionTimeout +

    The timeout in milliseconds to use when establishing the connection + to the LDAP directory. If not specified, a value of 5000 (5 seconds) is + used.

    +
    connectionURL +

    The connection URL to be passed to the JNDI driver when + establishing a connection to the directory.

    +
    contextFactory +

    Fully qualified Java class name of the factory class used + to acquire our JNDI InitialContext. By default, + assumes that the standard JNDI LDAP provider will be utilized.

    +
    derefAliases +

    A string specifying how aliases are to be dereferenced during + search operations. The allowed values are "always", "never", + "finding" and "searching". If not specified, "always" is used.

    +
    forceDnHexEscape +

    A setting of true forces escaping in the String + representation of a distinguished name to use the \nn form. + This may avoid issues with realms using Active Directory which appears + to be more tolerant of optional escaping when the \nn form + is used. If not specified, the default of false will be + used.

    +
    hostnameVerifierClassName +

    The name of the class to use for hostname verification when + using StartTLS for securing the connection to the ldap server. + The default constructor will be used to construct an instance of + the verifier class. The default is to accept only those hostnames, + that are valid according to the peer certificate of the ldap + server.

    +
    protocol +

    A string specifying the security protocol to use. If not given + the providers default is used.

    +
    readTimeout +

    The timeout, in milliseconds, to use when trying to read from a + connection to the directory. If not specified, the default of 5000 + (5 seconds) is used.

    +
    referrals +

    How do we handle JNDI referrals? Allowed values are + "ignore", "follow", or "throw" (see javax.naming.Context.REFERRAL + for more information). + Microsoft Active Directory often returns referrals. + If you need to follow them set referrals to "follow". + Caution: if your DNS is not part of AD, the LDAP client lib might try + to resolve your domain name in DNS to find another LDAP server.

    +
    roleBase +

    The base directory entry for performing role searches. If not + specified the top-level element in the directory context will be used. + If specified it may optionally include pattern replacements + "{0}".."{n}" corresponding to the name parts of the + user's distinguished name (as returned by + javax.naming.Name.get()).

    +
    roleName +

    The name of the attribute that contains role names in the + directory entries found by a role search. In addition you can + use the userRoleName property to specify the name + of an attribute, in the user's entry, containing additional + role names.

    +

    If roleName is not specified a role + search does not take place, and roles are taken only from the + user's entry.

    +
    roleNested +

    Set to true if you want to nest roles into roles. + When a role search is performed and the value of this property is + true, the search will be repeated recursively to find + all the roles that belong to the user either directly or indirectly. + If not specified, the default value of false is used.

    +
    roleSearch +

    The LDAP filter expression used for performing role + searches.

    + +

    Use {0} to substitute the distinguished name (DN) + of the user, and/or {1} to substitute the username, + and/or {2} for the value of an attribute from the + user's directory entry, of the authenticated user. + The name of the attribute that provides the value for {2} + is configured by the userRoleAttribute property.

    + +

    When roleNested property is true, + this filter expression will be also used to recursively search for + other roles, which indirectly belong to this user. To find the + roles that match the newly found role, the following values + are used: + {0} is substituted by the distinguished name of the newly + found role, and both {1} and {2} are + substituted by the name of the role (see the roleName + property). The userRoleAttribute property is not + applicable to this search.

    + +

    If this property is not specified, a role search does not take + place and roles are taken only from the attribute in the user's entry + specified by the userRoleName property.

    +
    roleSearchAsUser +

    When searching for user roles, should the search be performed as the + user currently being authenticated? If false, + connectionName and connectionPassword will be + used if specified, else an anonymous. If not specified, the default + value of false is used. Note that when accessing the + directory using delegated credentials, this attribute is always ignored + and the search is performed using the delegated credentials.

    +
    roleSubtree +

    Set to true if you want to search the entire + subtree of the element specified by the roleBase + property for role entries associated with the user. The + default value of false causes only the top level + to be searched.

    +
    sizeLimit +

    Specifies the maximum number of records to return when using the + userSearch attribute. If not specified, the default of + 0 is used which indicates no limit.

    +
    spnegoDelegationQop +

    When the JNDI Realm is used with the SPNEGO authenticator and + useDelegatedCredential is true this attribute + controls the QOP (Quality of Protection) that should be used for + the connection to the LDAP + server after authentication. This value is used to set the + javax.security.sasl.qop environment property for the LDAP + connection. This attribute should be a comma-separated list of values + selected from auth-conf, auth-int and + auth. See Java documentation for more details.

    +

    The default value is auth-conf.

    +
    sslProtocol +

    Specifies which ssl protocol should be used, when connecting with + StartTLS. The default is to let the jre decide. If you need even more + control, you can specify the SSLSocketFactory to use.

    +
    sslSocketFactory +

    Specifies which SSLSocketFactory to use when connecting + to the ldap server using StartTLS. An instance of the class will be + constructed using the default constructor. If none class name is given + the default jre SSLSocketFactory will be used.

    +
    stripRealmForGss +

    When processing users authenticated via the GSS-API, this attribute + controls if any "@..." is removed from the end of the user + name. If not specified, the default is true.

    +
    timeLimit +

    Specifies the time (in milliseconds) to wait for records to be + returned when using the userSearch attribute. If not + specified, the default of 0 is used which indicates no + limit.

    +
    transportGuaranteeRedirectStatus +

    The HTTP status code to use when the container needs to issue an HTTP + redirect to meet the requirements of a configured transport + guarantee. The provided status code is not validated. If not + specified, the default value of 302 is used.

    +
    useDelegatedCredential +

    When the JNDIRealm is used with the SPNEGO authenticator, delegated + credentials for the user may be available. If such credentials are + present, this attribute controls whether or not they are used to + connect to the directory. If not specified, the default value of + true is used.

    +
    userBase +

    The base element for user searches performed using the + userSearch expression. Not used if you are using + the userPattern expression.

    +
    userPassword +

    Name of the attribute in the user's entry containing the + user's password. If you specify this value, JNDIRealm will + bind to the directory using the values specified by + connectionName and + connectionPassword properties, and retrieve the + corresponding attribute for comparison to the value specified + by the user being authenticated. If you do + not specify this value, JNDIRealm will + attempt a simple bind to the directory using the DN of the + user's entry and the password presented by the user, with a + successful bind being interpreted as an authenticated + user.

    +
    userPattern +

    Pattern for the distinguished name (DN) of the user's + directory entry, with {0} marking where the + actual username should be inserted. You can use this property + instead of userSearch, userSubtree + and userBase when the distinguished name contains + the username and is otherwise the same for all users. Note that + when accessing the directory using delegated credentials, this + attribute is always ignored and userSearch, + userSubtree and userBase are always + used instead.

    +
    userRoleName +

    The name of an attribute in the user's directory entry + containing zero or more values for the names of roles assigned + to this user. In addition you can use the + roleName property to specify the name of an + attribute to be retrieved from individual role entries found + by searching the directory. If userRoleName is + not specified all the roles for a user derive from the role + search.

    +
    userRoleAttribute +

    The name of an attribute in the user's directory entry + containing the value that you wish to use when you search for + roles. This is especially useful for RFC 2307 where + the role memberUid can be the uid or the + uidNumber of the user. This value will be + marked as {2} in your role search filter expression. + This value will NOT be available for nested role searches.

    +
    userSearch +

    The LDAP filter expression to use when searching for a + user's directory entry, with {0} marking where + the actual username should be inserted. Use this property + (along with the userBase and + userSubtree properties) instead of + userPattern to search the directory for the + user's entry.

    +
    userSearchAsUser +

    When searching for a user's entry, should the search be performed as + the user currently being authenticated? If false, + connectionName and connectionPassword will be + used if specified, else an anonymous. If not specified, the default + value of false is used. Note that when accessing the + directory using delegated credentials, this attribute is always ignored + and the search is performed using the delegated credentials.

    +
    userSubtree +

    Set to true if you want to search the entire + subtree of the element specified by the userBase + property for the user's entry. The default value of + false causes only the top level to be searched. + Not used if you are using the userPattern + expression.

    +
    useStartTls +

    Set to true if you want to use StartTLS for securing + the connection to the ldap server. The default value is false. +

    +
    X509UsernameRetrieverClassName +

    When using X509 client certificates, this specifies the class name + that will be used to retrieve the user name from the certificate. + The class must implement the + org.apache.catalina.realm.X509UsernameRetriever + interface. The default is to use the certificate's SubjectDN + as the username.

    +
    + +

    See the Container-Managed Security Guide for more + information on setting up container managed security using the + JNDI Directory Realm component.

    + +
    + + +

    UserDatabase Realm - org.apache.catalina.realm.UserDatabaseRealm

    + +

    The UserDatabase Realm is a Realm implementation + that is based on a UserDatabase resource made available through the global + JNDI resources configured for this Tomcat instance.

    + +

    The UserDatabase Realm implementation supports the following + additional attributes:

    + +
    + Attribute + + Description +
    allRolesMode +

    This attribute controls how the special role name * is + handled when processing authorization constraints in web.xml. By + default, the specification compliant value of strict is + used which means that the user must be assigned one of the roles defined + in web.xml. The alternative values are authOnly which means + that the user must be authenticated but no check is made for assigned + roles and strictAuthOnly which means that the user must be + authenticated and no check will be made for assigned roles unless roles + are defined in web.xml in which case the user must be assigned at least + one of those roles.

    +
    resourceName +

    The name of the global UserDatabase resource + that this realm will use for user, password and role information.

    +
    transportGuaranteeRedirectStatus +

    The HTTP status code to use when the container needs to issue an HTTP + redirect to meet the requirements of a configured transport + guarantee. The provided status code is not validated. If not + specified, the default value of 302 is used.

    +
    X509UsernameRetrieverClassName +

    When using X509 client certificates, this specifies the class name + that will be used to retrieve the user name from the certificate. + The class must implement the + org.apache.catalina.realm.X509UsernameRetriever + interface. The default is to use the certificate's SubjectDN + as the username.

    +
    + +

    See the + Container-Managed Security Guide for more + information on setting up container managed security using the UserDatabase + Realm component and the + JNDI resources how-to for more + information on how to configure a UserDatabase resource.

    + +
    + + +

    Memory Based Realm - org.apache.catalina.realm.MemoryRealm

    + +

    The Memory Based Realm is a simple Realm implementation + that reads user information from an XML format, and represents it as a + collection of Java objects in memory. This implementation is intended + solely to get up and running with container managed security - it is NOT + intended for production use. As such, there are no mechanisms for + updating the in-memory collection of users when the content of the + underlying data file is changed.

    + +

    The Memory Based Realm implementation supports the following + additional attributes:

    + +
    + Attribute + + Description +
    allRolesMode +

    This attribute controls how the special role name * is + handled when processing authorization constraints in web.xml. By + default, the specification compliant value of strict is + used which means that the user must be assigned one of the roles defined + in web.xml. The alternative values are authOnly which means + that the user must be authenticated but no check is made for assigned + roles and strictAuthOnly which means that the user must be + authenticated and no check will be made for assigned roles unless roles + are defined in web.xml in which case the user must be assigned at least + one of those roles.

    +
    pathname +

    URL, absolute path or relative path (to $CATALINA_BASE) for the XML + file containing our user information. See below for details on the + XML element format required. If no pathname is specified, the + default value is conf/tomcat-users.xml.

    +
    stripRealmForGss +

    When processing users authenticated via the GSS-API, this attribute + controls if any "@..." is removed from the end of the user + name. If not specified, the default is true.

    +
    transportGuaranteeRedirectStatus +

    The HTTP status code to use when the container needs to issue an HTTP + redirect to meet the requirements of a configured transport + guarantee. The provided status code is not validated. If not + specified, the default value of 302 is used.

    +
    X509UsernameRetrieverClassName +

    When using X509 client certificates, this specifies the class name + that will be used to retrieve the user name from the certificate. + The class must implement the + org.apache.catalina.realm.X509UsernameRetriever + interface. The default is to use the certificate's SubjectDN + as the username.

    +
    + +

    The XML document referenced by the pathname attribute must + conform to the following requirements:

    +
      +
    • The root (outer) element must be <tomcat-users>. +
    • +
    • Each authorized user must be represented by a single XML element + <user>, nested inside the root element.
    • +
    • Each <user> element must have the following + attributes: +
        +
      • username - Username of this user (must be unique + within this file).
        + For compatibility, it is allowed to use name as an + alternative name for this attribute.
      • +
      • password - Password of this user (in + clear text).
      • +
      • roles - Comma-delimited list of the role names + assigned to this user.
      • +
    • +
    + +

    See the Container-Managed Security Guide for more + information on setting up container managed security using the + Memory Based Realm component.

    + +
    + + +

    JAAS Realm - org.apache.catalina.realm.JAASRealm

    + +

    JAASRealm is an implementation of the Tomcat + Realm interface that authenticates users through the Java + Authentication & Authorization Service (JAAS) framework which is now + provided as part of the standard J2SE API.

    + +

    Using JAASRealm gives the developer the ability to combine practically + any conceivable security realm with Tomcat's CMA.

    + +

    JAASRealm is prototype for Tomcat of the JAAS-based J2EE authentication + framework for J2EE v1.4, based on the JCP Specification Request + 196 to enhance container-managed security and promote 'pluggable' + authentication mechanisms whose implementations would be + container-independent.

    + +

    Based on the JAAS login module and principal + (see javax.security.auth.spi.LoginModule and + javax.security.Principal), you can develop your own security + mechanism or wrap another third-party mechanism for integration with the CMA + as implemented by Tomcat.

    + +

    The JAAS Realm implementation supports the following additional + attributes:

    + +
    + Attribute + + Description +
    allRolesMode +

    This attribute controls how the special role name * is + handled when processing authorization constraints in web.xml. By + default, the specification compliant value of strict is + used which means that the user must be assigned one of the roles defined + in web.xml. The alternative values are authOnly which means + that the user must be authenticated but no check is made for assigned + roles and strictAuthOnly which means that the user must be + authenticated and no check will be made for assigned roles unless roles + are defined in web.xml in which case the user must be assigned at least + one of those roles.

    +
    appName +

    The name of the application as configured in your login configuration + file + (JAAS LoginConfig).

    +

    If not specified appName is derived from the Container's + name it is placed in, for example Catalina or ROOT. + If the realm is not placed in any Container, the default is Tomcat. +

    +
    userClassNames +

    A comma-separated list of the names of the classes that you have made + for your user Principals.

    +
    configFile +

    The name of a JAAS configuration file to use with this Realm. It will + be searched for using ClassLoader#getResource(String) so it + is possible for the configuration to be bundled within a web + application. If not specified, the default JVM global JAAS configuration + will be used.

    +
    roleClassNames +

    A comma-separated list of the names of the classes that you have made + for your role Principals.

    +
    stripRealmForGss +

    When processing users authenticated via the GSS-API, this attribute + controls if any "@..." is removed from the end of the user + name. If not specified, the default is true.

    +
    transportGuaranteeRedirectStatus +

    The HTTP status code to use when the container needs to issue an HTTP + redirect to meet the requirements of a configured transport + guarantee. The provided status code is not validated. If not + specified, the default value of 302 is used.

    +
    useContextClassLoader +

    Instructs JAASRealm to use the context class loader for loading the + user-specified LoginModule class and associated + Principal classes. The default value is true, + which is backwards-compatible with the way Tomcat 5 works. To load + classes using the container's classloader, specify + false.

    +
    X509UsernameRetrieverClassName +

    When using X509 client certificates, this specifies the class name + that will be used to retrieve the user name from the certificate. + The class must implement the + org.apache.catalina.realm.X509UsernameRetriever + interface. The default is to use the certificate's SubjectDN + as the username.

    +
    + +

    See the Container-Managed Security + Guide for more information on setting up container managed security + using the JAAS Realm component.

    + +
    + + +

    Combined Realm - org.apache.catalina.realm.CombinedRealm

    + +

    CombinedRealm is an implementation of the Tomcat + Realm interface that authenticates users through one or more + sub-Realms.

    + +

    Using CombinedRealm gives the developer the ability to combine multiple + Realms of the same or different types. This can be used to authenticate + against different sources, provide fall back in case one Realm fails or for + any other purpose that requires multiple Realms.

    + +

    Sub-realms are defined by nesting Realm elements inside the + Realm element that defines the CombinedRealm. Authentication + will be attempted against each Realm in the order they are + listed. Authentication against any Realm will be sufficient to authenticate + the user. The authenticated user, and their associated roles, will be taken + from the first Realm that successfully authenticates the user.

    + +

    See the Container-Managed Security + Guide for more information on setting up container managed security + using the CombinedRealm component.

    + +

    The CombinedRealm implementation supports the following additional + attributes.

    + +
    + Attribute + + Description +
    allRolesMode +

    This attribute controls how the special role name * is + handled when processing authorization constraints in web.xml. By + default, the specification compliant value of strict is + used which means that the user must be assigned one of the roles defined + in web.xml. The alternative values are authOnly which means + that the user must be authenticated but no check is made for assigned + roles and strictAuthOnly which means that the user must be + authenticated and no check will be made for assigned roles unless roles + are defined in web.xml in which case the user must be assigned at least + one of those roles.

    +
    transportGuaranteeRedirectStatus +

    The HTTP status code to use when the container needs to issue an HTTP + redirect to meet the requirements of a configured transport + guarantee. The provided status code is not validated. If not + specified, the default value of 302 is used.

    +
    +
    + + +

    LockOut Realm - org.apache.catalina.realm.LockOutRealm

    + +

    LockOutRealm is an implementation of the Tomcat + Realm interface that extends the CombinedRealm to provide lock + out functionality to provide a user lock out mechanism if there are too many + failed authentication attempts in a given period of time.

    + +

    To ensure correct operation, there is a reasonable degree of + synchronization in this Realm.

    + +

    This Realm does not require modification to the underlying Realms or the + associated user storage mechanisms. It achieves this by recording all failed + logins, including those for users that do not exist. To prevent a DOS by + deliberating making requests with invalid users (and hence causing this + cache to grow) the size of the list of users that have failed authentication + is limited.

    + +

    Sub-realms are defined by nesting Realm elements inside the + Realm element that defines the LockOutRealm. Authentication + will be attempted against each Realm in the order they are + listed. Authentication against any Realm will be sufficient to authenticate + the user.

    + +

    The LockOutRealm implementation supports the following additional + attributes.

    + +
    + Attribute + + Description +
    allRolesMode +

    This attribute controls how the special role name * is + handled when processing authorization constraints in web.xml. By + default, the specification compliant value of strict is + used which means that the user must be assigned one of the roles defined + in web.xml. The alternative values are authOnly which means + that the user must be authenticated but no check is made for assigned + roles and strictAuthOnly which means that the user must be + authenticated and no check will be made for assigned roles unless roles + are defined in web.xml in which case the user must be assigned at least + one of those roles.

    +
    cacheRemovalWarningTime +

    If a failed user is removed from the cache because the cache is too + big before it has been in the cache for at least this period of time (in + seconds) a warning message will be logged. Defaults to 3600 (1 hour).

    +
    cacheSize +

    Number of users that have failed authentication to keep in cache. Over + time the cache will grow to this size and may not shrink. Defaults to + 1000.

    +
    failureCount +

    The number of times in a row a user has to fail authentication to be + locked out. Defaults to 5.

    +
    lockOutTime +

    The time (in seconds) a user is locked out for after too many + authentication failures. Defaults to 300 (5 minutes). Further + authentication failures during the lock out time will cause the lock out + timer to reset to zero, effectively extending the lock out time. Valid + authentication attempts during the lock out period will not succeed but + will also not reset the lock out time.

    +
    transportGuaranteeRedirectStatus +

    The HTTP status code to use when the container needs to issue an HTTP + redirect to meet the requirements of a configured transport + guarantee. The provided status code is not validated. If not + specified, the default value of 302 is used.

    +
    + +

    See the Container-Managed Security + Guide for more information on setting up container managed security + using the LockOutRealm component.

    + +
    + +

    Null Realm - org.apache.catalina.realm.NullRealm

    + +

    NullRealm is a minimal implementation of the Tomcat + Realm interface that always returns null when an attempt is + made to validate a user name and associated credentials. It is intended to + be used as a default Realm implementation when no other Realm is + specified.

    + +

    The NullRealm implementation supports the following additional + attributes.

    + +
    + Attribute + + Description +
    transportGuaranteeRedirectStatus +

    The HTTP status code to use when the container needs to issue an HTTP + redirect to meet the requirements of a configured transport + guarantee. The provided status code is not validated. If not + specified, the default value of 302 is used.

    +
    + +
    + +

    Nested Components

    + +

    You can nest the following components by nesting the corresponding element + inside your Realm element:

    +
      +
    • CombinedRealm Implementation - If you are using the + CombinedRealm Implementation or a Realm + that extends the CombinedRealm, e.g. the LockOutRealm, one or more + <Realm> elements may be nested inside it.
    • +
    • CredentialHandler - + You may nest at most one instance of this element inside a Realm. This + configures the credential handler that will be used to validate provided + credentials with those stored by the Realm. If not specified a default + MessageDigestCredentialHandler will be configured.
    • +
    + +

    Special Features

    + +

    See Single Sign On for information about + configuring Single Sign On support for a virtual host.

    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/resources.html b/tomcat/docs/config/resources.html new file mode 100644 index 0000000..1a6022c --- /dev/null +++ b/tomcat/docs/config/resources.html @@ -0,0 +1,320 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - The Resources Component

    The Resources Component

    Table of Contents

    Introduction

    + +

    The Resources element represents all the resources + available to the web application. This includes classes, JAR files, HTML, JSPs + and any other files that contribute to the web application. Implementations + are provided to use directories, JAR files and WARs as the source of these + resources and the resources implementation may be extended to provide support + for files stored in other forms such as in a database or a versioned + repository.

    + +

    Resources are cached by default.

    + +

    Note: Running a webapp with non-filesystem based + Resources implementations is only possible when the webapp does not + rely on direct filesystem access to its own resources, and uses the methods + in the ServletContext interface to access them.

    + +

    A Resources element MAY be nested inside a + Context component. If it is not included, + a default filesystem based Resources will be created automatically, + which is sufficient for most requirements.

    + +

    Attributes

    + +

    Common Attributes

    + +

    All implementations of Resources support the following + attributes:

    + +
    + Attribute + + Description +
    allowLinking +

    If the value of this flag is true, symlinks will be + allowed inside the web application, pointing to resources inside or + outside the web application base path. If not specified, the default + value of the flag is false.

    +

    NOTE: This flag MUST NOT be set to true on the Windows platform + (or any other OS which does not have a case sensitive filesystem), + as it will disable case sensitivity checks, allowing JSP source code + disclosure, among other security problems.

    +
    cacheMaxSize +

    The maximum size of the static resource cache in kilobytes. + If not specified, the default value is 10240 + (10 megabytes). This value may be changed while the web application is + running (e.g. via JMX). If the cache is using more memory than the new + limit the cache will attempt to reduce in size over time to meet the + new limit. If necessary, cacheObjectMaxSize will be + reduced to ensure that it is no larger than + cacheMaxSize/20.

    +
    cacheObjectMaxSize +

    Maximum size of the static resource that will be placed in the cache. + If not specified, the default value is 512 + (512 kilobytes). If this value is greater than + cacheMaxSize/20 it will be reduced to + cacheMaxSize/20. This value may be changed while the web + application is running (e.g. via JMX).

    +
    cacheTtl +

    The amount of time in milliseconds between the revalidation of cache + entries. If not specified, the default value is 5000 (5 + seconds). This value may be changed while the web application is running + (e.g. via JMX). When a resource is cached it will inherit the TTL in + force at the time it was cached and retain that TTL until the resource + is evicted from the cache regardless of any subsequent changes that may + be made to this attribute.

    +
    cachingAllowed +

    If the value of this flag is true, the cache for static + resources will be used. If not specified, the default value + of the flag is true. This value may be changed while the + web application is running (e.g. via JMX). When the cache is disabled + any resources currently in the cache are cleared from the cache.

    +
    className +

    Java class name of the implementation to use. This class must + implement the org.apache.catalina.WebResourceRoot + interface. If not specified, the standard value (defined below) will be + used.

    +
    trackLockedFiles +

    Controls whether the track locked files feature is enabled. If + enabled, all calls to methods that return objects that lock a file and + need to be closed to release that lock (e.g. + ServletContext.getResourceAsStream()) will perform a number + of additional tasks.

    +
      +
    • The stack trace at the point where the method was called will be + recorded and associated with the returned object.
    • +
    • The returned object will be wrapped so that the point where + close() (or equivalent) is called to release the resources can be + detected. Tracking of the object will cease once the resources have + been released.
    • +
    • All remaining locked resources on web application shutdown will be + logged and then closed.
    • +
    +

    If not specified, the default value of false will be + used.

    +
    + +
    + + +

    Standard Implementation

    + +

    Standard Root Implementation

    + +

    The standard implementation of Resources is + org.apache.catalina.webresources.StandardRoot. It does not + support any additional attributes.

    + +

    Extracting Root Implementation

    + +

    The extracting implementation of Resources is + org.apache.catalina.webresources.ExtractingRoot. It does not + support any additional attributes.

    + +

    When deploying web applications as packed WAR files, the extracting root + will extract any JAR files from /WEB-INF/lib to a + application-jars directory located in the web + application's working directory. These extracted JARs will be removed + when the web application stops.

    + +

    Extracting JAR files from a packed WAR may provide a performance + improvement, particularly at web application start when JAR scanning is + required by the application.

    + +
    + +

    Nested Components

    + +

    A web application's main resources are defined by the + docBase defined for the Context. + Additional resources may be made available to the web application by defining + one or more nested components.

    + +

    PreResources

    + +

    PreResources are searched before the main resources. They will be searched + in the order they are defined. To configure PreResources, nest a + <PreResources> element inside the <Resources> element with the + following attributes:

    + +
    + Attribute + + Description +
    base +

    Identifies where the resources to be used are located. This attribute + is required by the org.apache.catalina.WebResourceSet + implementations provided by Tomcat and should specify the absolute path to + the file, directory or JAR where the resources are located. Custom + implementations may not require it.

    +
    className +

    Java class name of the implementation to use. This class must + implement the org.apache.catalina.WebResourceSet interface. + Tomcat provides three standard implementations: + org.apache.catalina.webresources.DirResourceSet, + org.apache.catalina.webresources.FileResourceSet and + org.apache.catalina.webresources.JarResourceSet. Custom + implementations may also be used. +

    +
    internalPath +

    Identifies the path within the base where the + resources are to be found. This is typically only used with JAR files when + the resources are not located at the root of the JAR as is the case with + resource JARs. This attribute is required by the + org.apache.catalina.WebResourceSet implementations provided + by Tomcat and must start with '/'. Custom implementations may not require + it. If not specified, the default value '/' will be used.

    +
    readOnly +

    If true, resources within this resource set may not be + deleted, created or modified. For instance of + org.apache.catalina.webresources.JarResourceSet, this + attribute is hard-coded to true and may not be changed. For + instances of org.apache.catalina.webresources.DirResourceSet + and org.apache.catalina.webresources.FileResourceSet the + default value of this attribute is false.

    +
    webAppMount +

    Identifies the path within the web application that these resources + will be made available. For the + org.apache.catalina.WebResourceSet implementations provided + by Tomcat, this attribute is required and must start with '/'. Custom + implementations may not require it. If not specified, the default value of + '/' will be used.

    +
    + +

    JAR resources

    + +

    JarResources are searched after the main resources but before the + PostResources. They will be searched in the order they are defined. To + configure JarResources, nest a <JarResources> element inside the + <Resources> element. The configuration attributes are the same as for + PreResources. +

    + +

    During web application start, the JAR scanning process checks scanned JARs + for content under /META-INF/resources. Where found, this static + content is added to the JarResources. +

    + +

    Post-resources

    + +

    PostResources are searched after the resource JARs. They will be searched + in the order they are defined. To configure PostResources, nest a + <PostResources> element inside the <Resources> element. The + configuration attributes are the same as for PreResources. +

    + +

    Ordering

    + +

    In addition to the sets of resources described above, the standard + implementation also maintains ClassResources which represent the classes + contained in the JAR files mapped to /WEB-INF/classes. This + allows other components to search for classes with a single call rather than + one call to search /WEB-INF/classes followed by another to search + the JARs in /WEB-INF/lib. The ClassResources are populated + from the JARs mapped to /WEB-INF/lib when the web application + starts.

    + +

    Therefore, the complete search order is:

    +
      +
    • PreResources
    • +
    • MainResources
    • +
    • ClassResources
    • +
    • JarResources
    • +
    • PostResources
    • +
    + +

    The population of ClassResources and JarResources at web application start + means that care needs to be taken to add JAR based resources correctly to + obtain the desired behaviour. Consider the following example:

    + +
    <Resources>
    +  <PostResources base="D:\Projects\external\classes"
    +                 className="org.apache.catalina.webresources.DirResourceSet"
    +                 webAppMount="/WEB-INF/classes"/>
    +  <PostResources base="D:\Projects\lib\library1.jar"
    +                 className="org.apache.catalina.webresources.FileResourceSet"
    +                 webAppMount="/WEB-INF/lib/library1.jar"/>
    +</Resources>
    + +

    Since both resources are PostResources, it might be expected that + D:\Projects\external\classes will be searched for classes before + D:\Projects\lib\library1.jar. However, by adding the JAR using a + FileResourceSet, the JAR is mapped to /WEB-INF/lib + and will be processed at application start along with the other JARs in + /WEB-INF/lib. The classes from the JAR file will be added to the + ClassResources which means they will be searched before the classes from + D:\Projects\external\classes. If the desired behaviour is that + D:\Projects\external\classes is searched before + D:\Projects\lib\library1.jar then a slightly different + configuration is required:

    + +
    <Resources>
    +  <PostResources base="D:\Projects\external\classes"
    +                 className="org.apache.catalina.webresources.DirResourceSet"
    +                 webAppMount="/WEB-INF/classes"/>
    +  <PostResources base="D:\Projects\lib\library1.jar"
    +                 className="org.apache.catalina.webresources.JarResourceSet"
    +                 webAppMount="/WEB-INF/classes"/>
    +</Resources>
    + +

    In short, the JAR file should be added as a JarResourceSet + mapped to /WEB-INF/classes rather than using a + FileResourceSet mapped to /WEB-INF/lib. +

    + +

    Special Features

    + +

    No special features are associated with a Resources + element.

    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/server.html b/tomcat/docs/config/server.html new file mode 100644 index 0000000..1f60fc4 --- /dev/null +++ b/tomcat/docs/config/server.html @@ -0,0 +1,123 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - The Server Component

    The Server Component

    Table of Contents

    Introduction

    + +

    A Server element represents the entire Catalina + servlet container. Therefore, it must be the single outermost element + in the conf/server.xml configuration file. Its attributes + represent the characteristics of the servlet container as a whole.

    + +

    Attributes

    + +

    Common Attributes

    + +

    All implementations of Server + support the following attributes:

    + +
    + Attribute + + Description +
    className +

    Java class name of the implementation to use. This class must + implement the org.apache.catalina.Server interface. + If no class name is specified, the standard implementation will + be used.

    +
    address +

    The TCP/IP address on which this server waits for a shutdown + command. If no address is specified, localhost is used.

    +
    port +

    The TCP/IP port number on which this server waits for a shutdown + command. Set to -1 to disable the shutdown port.

    +

    Note: Disabling the shutdown port works well when Tomcat is started + using Apache Commons Daemon + (running as a service on Windows or with jsvc on un*xes). It cannot be + used when running Tomcat with the standard shell scripts though, as it + will prevent shutdown.bat|.sh and catalina.bat|.sh from stopping it + gracefully.

    +
    shutdown +

    The command string that must be received via a TCP/IP connection + to the specified port number, in order to shut down Tomcat.

    +
    + +
    + +

    Standard Implementation

    + +

    The standard implementation of Server is + org.apache.catalina.core.StandardServer. + It supports the following additional attributes (in addition to the + common attributes listed above):

    + +
    + Attribute + + Description +
    + +
    + +

    Nested Components

    + +

    The following components may be nested inside a Server + element:

    + + +

    Special Features

    + +

    There are no special features associated with a Server. +

    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/service.html b/tomcat/docs/config/service.html new file mode 100644 index 0000000..d7c012c --- /dev/null +++ b/tomcat/docs/config/service.html @@ -0,0 +1,110 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - The Service Component

    The Service Component

    Table of Contents

    Introduction

    + +

    A Service element represents the combination of one or + more Connector components that share a single + Engine component for processing incoming + requests. One or more Service elements may be nested + inside a Server element.

    + +

    Attributes

    + +

    Common Attributes

    + +

    All implementations of Service + support the following attributes:

    + +
    + Attribute + + Description +
    className +

    Java class name of the implementation to use. This class must + implement the org.apache.catalina.Service interface. + If no class name is specified, the standard implementation will + be used.

    +
    name +

    The display name of this Service, which will + be included in log messages if you utilize standard Catalina + components. The name of each Service that is + associated with a particular Server + must be unique.

    +
    + +
    + +

    Standard Implementation

    + +

    The standard implementation of Service is + org.apache.catalina.core.StandardService. + It supports the following additional attributes (in addition to the + common attributes listed above):

    + +
    + Attribute + + Description +
    + +
    + +

    Nested Components

    + +

    The only components that may be nested inside a Service + element are one or more Connector elements, + followed by exactly one Engine element.

    + +

    Special Features

    + +

    There are no special features associated with a Service. +

    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/sessionidgenerator.html b/tomcat/docs/config/sessionidgenerator.html new file mode 100644 index 0000000..0423102 --- /dev/null +++ b/tomcat/docs/config/sessionidgenerator.html @@ -0,0 +1,131 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - The SessionIdGenerator Component

    The SessionIdGenerator Component

    Table of Contents

    Introduction

    + +

    The SessionIdGenerator element represents the session + id generator that will be used to create session ids used by + web application HTTP sessions.

    + +

    A SessionIdGenerator element MAY be nested inside a + Manager component. If it is not included, + a default SessionIdGenerator configuration will be created automatically, which + is sufficient for most requirements, — see + Standard SessionIdGenerator Implementation below for the details + of this configuration.

    + +

    Attributes

    + +

    Common Attributes

    + +

    All implementations of SessionIdGenerator + support the following attributes:

    + +
    + Attribute + + Description +
    className +

    Java class name of the implementation to use. This class must + implement the org.apache.catalina.SessionIdGenerator interface. + If not specified, the standard value (defined below) will be used.

    +
    jvmRoute +

    A routing identifier for this Tomcat instance. It will be added + to the session id to allow for stateless stickyness routing by + load balancers. The details on how the jvmRoute + will be included in the id are implementation dependent. + See Standard Implementation + for the default behavior.

    + +

    NOTE - The value for this property is inherited + automatically from the jvmRoute attribute of the + Engine element.

    +
    sessionIdLength +

    The length of session ids created by this SessionIdGenerator. + The details on how the sessionIdLength + influences the session id length are implementation dependent. + See Standard Implementation + for the default behavior.

    +
    + +
    + + +

    Standard Implementation

    + +

    Tomcat provides a standard implementations of SessionIdGenerator + for use.

    + +

    Standard SessionIdGenerator Implementation

    + +

    The standard implementation of SessionIdGenerator is + org.apache.catalina.util.StandardSessionIdGenerator. + It supports the following attributes:

    + +
    + Attribute + + Description +
    jvmRoute +

    A routing identifier for this Tomcat instance. It will be added + to the end of the session id separated by a ".".

    +
    sessionIdLength +

    The length of session ids created by this SessionIdGenerator. + More precisely the session id length is twice the value of + sessionIdLength plus the length of the trailing + jvmRoute if given. The factor 2 is because + the session id is constructed using sessionIdLength + random bytes, each byte being encoded in two hex characters + in the actual id. The default value is 16.

    +
    + +
    + + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/systemprops.html b/tomcat/docs/config/systemprops.html new file mode 100644 index 0000000..c8300b4 --- /dev/null +++ b/tomcat/docs/config/systemprops.html @@ -0,0 +1,557 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - System Properties

    System Properties

    Table of Contents

    Introduction

    +

    The following sections list the system properties that may be set to modify + the default Tomcat behaviour.

    +

    Property replacements

    +
    + Property + + Description +
    org.apache.tomcat.util.digester. PROPERTY_SOURCE +

    Set this to a fully qualified name of a class that implements + org.apache.tomcat.util.IntrospectionUtils.PropertySource. + Required to have a public constructor with no arguments.

    +

    Use this to add a property source, that will be invoked when ${parameter} + denoted parameters are found in the XML files that Tomcat parses.

    +

    Property replacement from the specified property source on the JVM + system properties can also be done using the + REPLACE_SYSTEM_PROPERTIES system property.

    +
    org.apache.tomcat.util.digester. REPLACE_SYSTEM_PROPERTIES +

    Set this boolean system property to true to cause + property replacement from the digester property source on the JVM + system properties.

    +
    + +

    Clustering

    +
    + Property + + Description +
    org.apache.catalina. tribes.dns_lookups +

    If true, the clustering module will attempt to use DNS to + resolve any host names provided in the cluster configuration.

    +

    If not specified, the default value of false will be used.

    +
    + +

    Expression Language

    +
    + Property + + Description +
    org.apache.el.BeanELResolver. CACHE_SIZE +

    The number of javax.el.BeanELResolver.BeanProperties objects that will + be cached by the EL Parser.

    +

    If not specified, the default of 1000 will be used.

    +
    org.apache.el.ExpressionBuilder. CACHE_SIZE +

    The number of parsed EL expressions that will be cached by the EL + Parser.

    +

    If not specified, the default of 5000 will be used.

    +
    org.apache.el.parser. COERCE_TO_ZERO +

    If true, when coercing nulls to objects of + type Number, Character or Boolean the result will be 0 for + Number and Character types and false for Boolean as required + by the EL 2.2 and earlier specifications. If this property is + false the result of the coercion will be null as + required by the EL 3.0 specification.

    +

    If not specified, the default value of false will be + used.

    +
    org.apache.el.parser. SKIP_IDENTIFIER_CHECK +

    If true, when parsing expressions, identifiers will not be + checked to ensure that they conform to the Java Language Specification for + Java identifiers.

    +

    If not specified, the default value of false will be used.

    +
    +

    Jasper

    +
    + Property + + Description +
    org.apache.jasper.compiler. Generator.POOL_TAGS_WITH_EXTENDS +

    By default, JSPs that use their own base class via the extends + attribute of the page directive, will have Tag pooling disabled since + Jasper cannot guarantee that the necessary initialisation will have taken + place. This can have a negative impact on performance. Providing the + alternative base class calls _jspInit() from Servlet.init(), setting this + property to true will enable pooling with an alternative base + class. If the alternative base class does not call _jspInit() and this + property is true, NPEs will occur when attempting to use + tags.

    +

    If not specified, the default value of false will be used. +

    +
    org.apache.jasper.compiler. Generator.STRICT_GET_PROPERTY +

    If true, the requirement to have the object referenced in + jsp:getProperty action to be previously "introduced" + to the JSP processor, as specified in the chapter JSP.5.3 of JSP 2.0 and + later specifications, is enforced.

    +

    If not specified, the specification compliant default of + true will be used.

    +
    org.apache.jasper.compiler. Generator.VAR_EXPRESSIONFACTORY +

    The name of the variable to use for the expression language expression + factory.

    +

    If not specified, the default value of _el_expressionfactory + will be used.

    +
    org.apache.jasper.compiler. Generator.VAR_INSTANCEMANAGER +

    The name of the variable to use for the instance manager factory.

    +

    If not specified, the default value of _jsp_instancemanager + will be used.

    +
    org.apache.jasper.compiler. Parser.STRICT_WHITESPACE +

    If false the requirements for whitespace before an + attribute name will be relaxed so that the lack of whitespace will not + cause an error.

    +

    If not specified, the specification compliant default of + true will be used.

    +
    org.apache.jasper.runtime. BodyContentImpl.BUFFER_SIZE +

    The size (in characters) to use when creating a tag buffer.

    +

    If not specified, the default value of + org.apache.jasper.Constants.DEFAULT_TAG_BUFFER_SIZE (512) + will be used.

    +
    org.apache.jasper.runtime. BodyContentImpl.LIMIT_BUFFER +

    If true, any tag buffer that expands beyond + org.apache.jasper.runtime.BodyContentImpl.BUFFER_SIZE will be + destroyed and a new buffer created.

    +

    If not specified, the default value of false will be used.

    +
    org.apache.jasper.runtime. JspFactoryImpl.USE_POOL +

    If true, a ThreadLocal PageContext pool will + be used.

    +

    If not specified, the default value of true will be used.

    +
    org.apache.jasper.runtime. JspFactoryImpl.POOL_SIZE +

    The size of the ThreadLocal PageContext.

    +

    If not specified, the default value of 8 will be used.

    +
    org.apache.jasper.Constants. JSP_SERVLET_BASE +

    The base class of the Servlets generated from the JSPs.

    +

    If not specified, the default value of + org.apache.jasper.runtime.HttpJspBase will be used.

    +
    org.apache.jasper.Constants. SERVICE_METHOD_NAME +

    The name of the service method called by the base class.

    +

    If not specified, the default value of _jspService + will be used.

    +
    org.apache.jasper.Constants. SERVLET_CLASSPATH +

    The name of the ServletContext attribute that provides the classpath + for the JSP.

    +

    If not specified, the default value of + org.apache.catalina.jsp_classpath will be used.

    +
    org.apache.jasper.Constants. JSP_FILE +

    The name of the request attribute for <jsp-file> + element of a servlet definition. If present on a request, this overrides + the value returned by request.getServletPath() to select the + JSP page to be executed.

    +

    If not specified, the default value of + org.apache.catalina.jsp_file will be used.

    +

    Deprecated: This will be removed in Tomcat 9.0.x + onwards. It is replaced by the use of the jspFile servlet initialisation + parameter

    +
    org.apache.jasper.Constants. PRECOMPILE +

    The name of the query parameter that causes the JSP engine to just + pregenerate the servlet but not invoke it.

    +

    If not specified, the default value of jsp_precompile + will be used, as defined by JSP specification (JSP.11.4.2).

    +
    org.apache.jasper.Constants. JSP_PACKAGE_NAME +

    The default package name for compiled JSPs.

    +

    If not specified, the default value of org.apache.jsp + will be used.

    +
    org.apache.jasper.Constants. TAG_FILE_PACKAGE_NAME +

    The default package name for tag handlers generated from tag files.

    +

    If not specified, the default value of org.apache.jsp.tag + will be used.

    +
    org.apache.jasper.Constants. ALT_DD_ATTR +

    The servlet context attribute under which the alternate deployment + descriptor for this web application is stored.

    +

    If not specified, the default value of + org.apache.catalina.deploy.alt_dd will be used.

    +
    org.apache.jasper.Constants. TEMP_VARIABLE_NAME_PREFIX +

    Prefix to use for generated temporary variable names.

    +

    If not specified, the default value of _jspx_temp + will be used.

    +
    org.apache.jasper.Constants. USE_INSTANCE_MANAGER_FOR_TAGS +

    If true, the instance manager is used to obtain tag + handler instances.

    +

    If not specified, the default value of false will be used.

    +
    + +

    Security

    + +
    + Property + + Description +
    org.apache.catalina.connector. RECYCLE_FACADES +

    If this is true or if a security manager is in use a new + facade object will be created for each request.

    +

    If not specified, the default value of false will be used.

    +
    org.apache.catalina.connector. CoyoteAdapter.ALLOW_BACKSLASH +

    If this is true the '\' character will be permitted as a + path delimiter.

    +

    If not specified, the default value of false will be used.

    +
    org.apache.tomcat.util.buf. UDecoder.ALLOW_ENCODED_SLASH +

    If this is true '%2F' and '%5C' will be permitted as path + delimiters.

    +

    If not specified, the default value of false will be used.

    +
    + +

    Specifications

    + +
    + Property + + Description +
    org.apache.catalina. STRICT_SERVLET_COMPLIANCE +

    The default value of this system property is false.

    +

    If this is true the default values will be changed for:

    +
      +
    • org.apache.catalina.core.
      ApplicationContext.GET_RESOURCE_REQUIRE_SLASH
    • +
    • org.apache.catalina.core.
      ApplicationDispatcher.WRAP_SAME_OBJECT
    • +
    • org.apache.catalina.core.
      StandardHostValve.ACCESS_SESSION
    • +
    • org.apache.catalina.session.
      StandardSession.ACTIVITY_CHECK
    • +
    • org.apache.catalina.session.
      StandardSession.LAST_ACCESS_AT_START
    • +
    • org.apache.tomcat.util.http.
      ServerCookie.STRICT_NAMING
    • +
    • The URIEncoding attribute of any + HTTP connector or + AJP connector element.
    • +
    • The resourceOnlyServlets attribute of any + Context element.
    • +
    • The tldValidation attribute of any + Context element.
    • +
    • The useRelativeRedirects attribute of any + Context element.
    • +
    • The xmlNamespaceAware attribute of any + Context element.
    • +
    • The xmlValidation attribute of any + Context element.
    • +
    +
    org.apache.catalina.connector. Response.ENFORCE_ENCODING_IN_GET_WRITER +

    If this is true then + a call to Response.getWriter() if no character encoding + has been specified will result in subsequent calls to + Response.getCharacterEncoding() returning + ISO-8859-1 and the Content-Type response header + will include a charset=ISO-8859-1 component. (SRV.15.2.22.1)

    +

    If not specified, the default specification compliant value of + true will be used.

    +
    org.apache.catalina.core.ApplicationContext .GET_RESOURCE_REQUIRE_SLASH +

    If this is true then the path passed to + ServletContext.getResource() or + ServletContext.getResourceAsStream() must start with + "/". If false, code like + getResource("myfolder/myresource.txt") will work as Tomcat + will prepend "/" to the provided path.

    +

    If org.apache.catalina.STRICT_SERVLET_COMPLIANCE is set to + true, the default of this setting will be true, + else the default value will be false.

    +
    org.apache.catalina.core. ApplicationDispatcher.WRAP_SAME_OBJECT +

    If this is true then any wrapped request or response + object passed to an application dispatcher will be checked to ensure that + it has wrapped the original request or response.

    +

    If org.apache.catalina.STRICT_SERVLET_COMPLIANCE is set to + true, the default of this setting will be true, + else the default value will be false.

    +
    org.apache.tomcat.websocket. STRICT_SPEC_COMPLIANCE +

    The default value of this system property is false.

    +

    If this is true the default values will be changed for:

    +
      +
    • org.apache.tomcat.websocket.server#isEnforceNoAddAfterHandshake + (default changes from false to true)
    • +
    +
    org.apache.tomcat.util.http. ServerCookie.STRICT_NAMING +

    If this is true then the requirements of the Servlet specification + that Cookie names must adhere to RFC2109 will be enforced. If this is + false the naming rules specified in RFC6265 (allow the leading "$") + will be used.

    +

    If org.apache.catalina.STRICT_SERVLET_COMPLIANCE is set to + true, the default of this setting will be true, + else the default value will be false.

    +
    + +

    Sessions

    + +
    + Property + + Description +
    org.apache.catalina.authenticator. Constants.SSO_SESSION_COOKIE_NAME +

    An alternative name for the single sign on session cookie. Defaults to + JSESSIONIDSSO.

    +
    org.apache.catalina.core. StandardHostValve.ACCESS_SESSION +

    If this is true, every request that is associated with a + session will cause the session's last accessed time to be updated + regardless of whether or not the request explicitly accesses the session.

    +

    If org.apache.catalina.STRICT_SERVLET_COMPLIANCE is set to + true, the default of this setting will be true, + else the default value will be false.

    +
    org.apache.catalina.session. StandardSession.ACTIVITY_CHECK +

    If this is true, Tomcat will track the number of active + requests for each session. When determining if a session is valid, any + session with at least one active request will always be considered valid.

    +

    If org.apache.catalina.STRICT_SERVLET_COMPLIANCE is set to + true, the default of this setting will be true, + else the default value will be false.

    +
    org.apache.catalina.session. StandardSession.LAST_ACCESS_AT_START +

    If this is true, the last accessed time for sessions will + be calculated from the beginning of the previous request. If + false, the last accessed time for sessions will be calculated + from the end of the previous request. This also affects how the idle time + is calculated.

    +

    If org.apache.catalina.STRICT_SERVLET_COMPLIANCE is set to + true, the default of this setting will be true, + else the default value will be false.

    +
    + +

    Logging

    + +
    + Property + + Description +
    org.apache.juli.formatter +

    If no logging configuration file is specified and no logging configuration class is specified + using the java.util.logging.config.class and java.util.logging.config.file + properties the default logging framework org.apache.juli will use the default + java.util.logging.SimpleFormatter for all console output. + To simply override the console output formatter, one can use the described property. Example: + -Dorg.apache.juli.formatter=org.apache.juli.OneLineFormatter

    +
    org.apache.juli. AsyncMaxRecordCount +

    The maximum number of log records that the JULI AsyncFileHandler will queue in memory. + New records are added to the queue and get asynchronously removed from the queue + and written to the files by a single writer thread. + When the queue is full and a new record is being logged + the log record will be handled based on the org.apache.juli.AsyncOverflowDropType setting.

    +

    The default value is 10000 records. + This number represents the global number of records, not on a per handler basis. +

    +
    org.apache.juli. AsyncOverflowDropType +

    When the queue of log records of the JULI AsyncFileHandler is full, + new log records are handled according to the following setting: +

    +
      +
    • 1 - the newest record in the queue will be dropped and not logged
    • +
    • 2 - the oldest record in the queue will be dropped and not logged
    • +
    • 3 - suspend the logging thread until older records got written to the log file and the queue is no longer full. + This is the only setting that ensures that no messages get lost.
    • +
    • 4 - drop the current log record
    • +
    +

    The default value is 1 (drop the newest record in the queue).

    +
    org.apache.juli. AsyncLoggerPollInterval +

    The poll interval in milliseconds for the asynchronous logger thread. + If the log queue is empty, the async thread will issue a poll(poll interval) + in order to not wake up too often.

    +

    The default value is 1000 milliseconds.

    +
    org.apache.juli.logging. UserDataHelper.CONFIG +

    The type of logging to use for errors generated by invalid input data. + The options are: DEBUG_ALL, INFO_THEN_DEBUG, + INFO_ALL and NONE. When + INFO_THEN_DEBUG is used, the period for which errors are + logged at DEBUG rather than INFO is controlled by the system property + org.apache.juli.logging.UserDataHelper.SUPPRESSION_TIME. +

    +

    The default value is INFO_THEN_DEBUG.

    +

    The errors currently logged using this system are:

    +
      +
    • invalid cookies;
    • +
    • invalid parameters;
    • +
    • too many headers, too many parameters (hitting + maxHeaderCount or maxParameterCount limits + of a connector).
    • +
    • invalid host names
    • +
    +

    Other errors triggered by invalid input data may be added to this + system in later versions.

    +
    org.apache.juli.logging. UserDataHelper.SUPPRESSION_TIME +

    When using INFO_THEN_DEBUG for + org.apache.juli.logging.UserDataHelper.CONFIG this system + property controls how long messages are logged at DEBUG after a message + has been logged at INFO. Once this period has elapsed, the next message + will be logged at INFO followed by a new suppression period where + messages are logged at DEBUG and so on. The value is measured + in seconds.

    +

    A value of 0 is equivalent to using INFO_ALL + for org.apache.juli.logging.UserDataHelper.CONFIG.

    +

    A negative value means an infinite suppression period.

    +

    The default value is 86400 (24 hours).

    +
    + +

    JAR Scanning

    + +
    + Property + + Description +
    tomcat.util.scan. StandardJarScanFilter.jarsToSkip +

    A list of comma-separated file name patters that is used as the default + value for pluggabilitySkip and tldSkip + attributes of the standard + JarScanFilter implementation.

    +

    The coded default is empty, however the system property is set in + a default Tomcat installation via the + $CATALINA_BASE/conf/catalina.properties file.

    +
    tomcat.util.scan. StandardJarScanFilter.jarsToScan +

    A list of comma-separated file name patters that is used as the default + value for pluggabilityScan and tldScan + attributes of the standard + JarScanFilter implementation.

    +

    The coded default is empty, however the system property is set in + a default Tomcat installation via the + $CATALINA_BASE/conf/catalina.properties file.

    +
    + +

    Websockets

    + +
    + Property + + Description +
    org.apache.tomcat. websocket.ALLOW_UNSUPPORTED_EXTENSIONS +

    If true, allow unknown extensions to be declared by + the user.

    +

    The default value is false.

    +
    org.apache.tomcat. websocket.DEFAULT_ORIGIN_HEADER_VALUE +

    Default value of the origin header that will be sent by the client + during the upgrade handshake.

    +

    The default is null so that no origin header is sent.

    +
    org.apache.tomcat. websocket.DEFAULT_PROCESS_PERIOD +

    The number of periodic ticks between periodic processing which + involves in particular session expiration checks.

    +

    The default value is 10 which corresponds to 10 + seconds.

    +
    org.apache.tomcat. websocket.DISABLE_BUILTIN_EXTENSIONS +

    If true, disable all built-in extensions provided by the + server, such as message compression.

    +

    The default value is false.

    +
    + +

    Other

    + +
    + Property + + Description +
    org.apache.coyote. USE_CUSTOM_STATUS_MSG_IN_HEADER

    If this is + true, custom HTTP status messages will be used within HTTP + headers. If a custom message is specified that is not valid for use in an + HTTP header (as defined by RFC2616) then the custom message will be + ignored and the default message used.

    +

    If not specified, the default value of false will be used.

    +

    Note: This option is deprecated and will be removed + in Tomcat 9. The reason phrase will not be sent.

    +
    catalina.useNaming +

    If this is false it will override the + useNaming attribute for all + Context elements.

    +
    javax.sql.DataSource.Factory +

    The class name of the factory to use to create resources of type + javax.sql.DataSource. If not specified the default of + org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory is used + which is a package renamed (to avoid conflicts) copy of + Apache Commons DBCP 2.

    +
    javax.mail.Session.Factory +

    The class name of the factory to use to create resources of type + javax.mail.Session. If not specified the default of + org.apache.naming.factory.MailSessionFactory is used.

    +
    jvmRoute +

    Provides a default value for the jvmRoute attribute of the + Engine element. It does not override the value + configured on the Engine element.

    +
    catalina.config +

    The URL for the catalina.properties configuration file.

    +
    tomcat.util.buf.StringCache.byte.enabled +

    If true, the String cache is enabled for + ByteChunk.

    +

    If not specified, the default value of false will be used.

    +
    tomcat.util.buf.StringCache.char.enabled +

    If true, the String cache is enabled for + CharChunk.

    +

    If not specified, the default value of false will be used.

    +
    tomcat.util.buf.StringCache.trainThreshold +

    The number of times toString() must be called before the + cache is activated.

    +

    If not specified, the default value of 20000 will be used.

    +
    tomcat.util.buf.StringCache.cacheSize +

    The size of the String cache.

    +

    If not specified, the default value of 200 will be used.

    +
    org.apache.tomcat.util.buf.UriUtil. WAR_SEPARATOR +

    The character to use to separate the WAR file and WAR content parts of + a WAR URL using the custom WAR scheme provided by Tomcat. This is + equivalent to how ! is used in JAR URLs.

    +

    If not specified, the default value of * will be used.

    +
    tomcat.util.buf.StringCache.maxStringSize +

    The maximum length of String that will be cached.

    +

    If not specified, the default value of 128 will be used.

    +
    org.apache.tomcat.util. http.FastHttpDateFormat.CACHE_SIZE +

    The size of the cache to use parsed and formatted date value.

    +

    If not specified, the default value of 1000 will be used.

    +
    org.apache.tomcat.util. net.NioSelectorShared +

    If true, use a shared selector for servlet write/read.

    +

    If not specified, the default value of true will be used.

    +
    org.apache.catalina.startup. EXIT_ON_INIT_FAILURE +

    If true, the server will exit if an exception happens + during the server initialization phase.

    +

    If not specified, the default value of false will be used.

    +
    org.apache.catalina.startup. RealmRuleSet.MAX_NESTED_REALM_LEVELS +

    The CombinedRealm allows nested Realms. This property controls the + maximum permitted number of levels of nesting.

    +

    If not specified, the default value of 3 will be used.

    +
    org.apache.catalina.startup. CredentialHandlerRuleSet.MAX_NESTED_LEVELS +

    The NestedCredentialHandler allows nested CredentialHandlers. This + property controls the maximum permitted number of levels of nesting.

    +

    If not specified, the default value of 3 will be used.

    +
    tomcat.util.http.parser.HttpParser. requestTargetAllow +

    This system property is deprecated. Use the + relaxedPathChars and relaxedQueryChars + attributes of the Connector instead. These attributes permit a wider range + of characters to be configured as valid.

    +

    A string comprised of characters the server should allow even when they are not encoded. + These characters would normally result in a 400 status.

    +

    The acceptable characters for this property are: |, { + , and }

    +

    WARNING: Use of this option may expose the server to CVE-2016-6816. +

    +

    If not specified, the default value of null will be used.

    +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/config/valve.html b/tomcat/docs/config/valve.html new file mode 100644 index 0000000..1b0410f --- /dev/null +++ b/tomcat/docs/config/valve.html @@ -0,0 +1,1804 @@ + +Apache Tomcat 8 Configuration Reference (8.5.43) - The Valve Component

    The Valve Component

    Table of Contents

    Introduction

    + +

    A Valve element represents a component that will be + inserted into the request processing pipeline for the associated + Catalina container (Engine, + Host, or Context). + Individual Valves have distinct processing capabilities, and are + described individually below.

    + +

    The description below uses the variable name $CATALINA_BASE to refer the + base directory against which most relative paths are resolved. If you have + not configured Tomcat for multiple instances by setting a CATALINA_BASE + directory, then $CATALINA_BASE will be set to the value of $CATALINA_HOME, + the directory into which you have installed Tomcat.

    + +

    Access Logging

    + +

    Access logging is performed by valves that implement +org.apache.catalina.AccessLog interface.

    + +

    Access Log Valve

    + +

    Introduction

    + +

    The Access Log Valve creates log files in the + same format as those created by standard web servers. These logs + can later be analyzed by standard log analysis tools to track page + hit counts, user session activity, and so on. This Valve + uses self-contained logic to write its log files, which can be + automatically rolled over at midnight each day. (The essential + requirement for access logging is to handle a large continuous + stream of data with low overhead. This Valve does not + use Apache Commons Logging, thus avoiding additional overhead and + potentially complex configuration).

    + +

    This Valve may be associated with any Catalina container + (Context, Host, or Engine), and + will record ALL requests processed by that container.

    + +

    Some requests may be handled by Tomcat before they are passed to a + container. These include redirects from /foo to /foo/ and the rejection of + invalid requests. Where Tomcat can identify the Context that + would have handled the request, the request/response will be logged in the + AccessLog(s) associated Context, Host + and Engine. Where Tomcat cannot identify the + Context that would have handled the request, e.g. in cases + where the URL is invalid, Tomcat will look first in the Engine, + then the default Host for the Engine and finally + the ROOT (or default) Context for the default Host + for an AccessLog implementation. Tomcat will use the first + AccessLog implementation found to log those requests that are + rejected before they are passed to a container.

    + +

    The output file will be placed in the directory given by the + directory attribute. The name of the file is composed + by concatenation of the configured prefix, timestamp and + suffix. The format of the timestamp in the file name can be + set using the fileDateFormat attribute. This timestamp will + be omitted if the file rotation is switched off by setting + rotatable to false.

    + +

    Warning: If multiple AccessLogValve instances + are used, they should be configured to use different output files.

    + +

    If sendfile is used, the response bytes will be written asynchronously + in a separate thread and the access log valve will not know how many bytes + were actually written. In this case, the number of bytes that was passed to + the sendfile thread for writing will be recorded in the access log valve. +

    +
    + +

    Attributes

    + +

    The Access Log Valve supports the following + configuration attributes:

    + +
    + Attribute + + Description +
    buffered +

    Flag to determine if logging will be buffered. + If set to false, then access logging will be written after each + request. Default value: true +

    +
    className +

    Java class name of the implementation to use. This MUST be set to + org.apache.catalina.valves.AccessLogValve to use the + default access log valve.

    +
    condition +

    The same as conditionUnless. This attribute is + provided for backwards compatibility. +

    +
    conditionIf +

    Turns on conditional logging. If set, requests will be + logged only if ServletRequest.getAttribute() is + not null. For example, if this value is set to + important, then a particular request will only be logged + if ServletRequest.getAttribute("important") != null. + The use of Filters is an easy way to set/unset the attribute + in the ServletRequest on many different requests. +

    +
    conditionUnless +

    Turns on conditional logging. If set, requests will be + logged only if ServletRequest.getAttribute() is + null. For example, if this value is set to + junk, then a particular request will only be logged + if ServletRequest.getAttribute("junk") == null. + The use of Filters is an easy way to set/unset the attribute + in the ServletRequest on many different requests. +

    +
    directory +

    Absolute or relative pathname of a directory in which log files + created by this valve will be placed. If a relative path is + specified, it is interpreted as relative to $CATALINA_BASE. If + no directory attribute is specified, the default value is "logs" + (relative to $CATALINA_BASE).

    +
    encoding +

    Character set used to write the log file. An empty string means + to use the system default character set. Default value: use the + system default character set. +

    +
    fileDateFormat +

    Allows a customized timestamp in the access log file name. + The file is rotated whenever the formatted timestamp changes. + The default value is .yyyy-MM-dd. + If you wish to rotate every hour, then set this value + to .yyyy-MM-dd.HH. + The date format will always be localized + using the locale en_US. +

    +
    locale +

    The locale used to format timestamps in the access log + lines. Any timestamps configured using an + explicit SimpleDateFormat pattern (%{xxx}t) + are formatted in this locale. By default the + default locale of the Java process is used. Switching the + locale after the AccessLogValve is initialized is not supported. + Any timestamps using the common log format + (CLF) are always formatted in the locale + en_US. +

    +
    maxDays +

    The maximum number of days rotated access logs will be retained for + before being deleted. If not specified, the default value of + -1 will be used which means never delete old files.

    +
    maxLogMessageBufferSize +

    Log message buffers are usually recycled and re-used. To prevent + excessive memory usage, if a buffer grows beyond this size it will be + discarded. The default is 256 characters. This should be + set to larger than the typical access log message size.

    +
    pattern +

    A formatting layout identifying the various information fields + from the request and response to be logged, or the word + common or combined to select a + standard format. See below for more information on configuring + this attribute.

    +
    prefix +

    The prefix added to the start of each log file's name. If not + specified, the default value is "access_log".

    +
    renameOnRotate +

    By default for a rotatable log the active access log file name + will contain the current timestamp in fileDateFormat. + During rotation the file is closed and a new file with the next + timestamp in the name is created and used. When setting + renameOnRotate to true, the timestamp + is no longer part of the active log file name. Only during rotation + the file is closed and then renamed to include the timestamp. + This is similar to the behavior of most log frameworks when + doing time based rotation. + Default value: false +

    +
    requestAttributesEnabled +

    Set to true to check for the existence of request + attributes (typically set by the RemoteIpValve and similar) that should + be used to override the values returned by the request for remote + address, remote host, server port and protocol. If the attributes are + not set, or this attribute is set to false then the values + from the request will be used. If not set, the default value of + false will be used.

    +
    resolveHosts +

    This attribute is no longer supported. Use the connector + attribute enableLookups instead.

    +

    If you have enableLookups on the connector set to + true and want to ignore it, use %a instead of + %h in the value of pattern.

    +
    rotatable +

    Flag to determine if log rotation should occur. + If set to false, then this file is never rotated and + fileDateFormat is ignored. + Default value: true +

    +
    suffix +

    The suffix added to the end of each log file's name. If not + specified, the default value is "" (a zero-length string), + meaning that no suffix will be added.

    +
    + +

    Values for the pattern attribute are made up of literal + text strings, combined with pattern identifiers prefixed by the "%" + character to cause replacement by the corresponding variable value from + the current request and response. The following pattern codes are + supported:

    +
      +
    • %a - Remote IP address
    • +
    • %A - Local IP address
    • +
    • %b - Bytes sent, excluding HTTP headers, or '-' if zero
    • +
    • %B - Bytes sent, excluding HTTP headers
    • +
    • %h - Remote host name (or IP address if + enableLookups for the connector is false)
    • +
    • %H - Request protocol
    • +
    • %l - Remote logical username from identd (always returns + '-')
    • +
    • %m - Request method (GET, POST, etc.)
    • +
    • %p - Local port on which this request was received. + See also %{xxx}p below.
    • +
    • %q - Query string (prepended with a '?' if it exists)
    • +
    • %r - First line of the request (method and request URI)
    • +
    • %s - HTTP status code of the response
    • +
    • %S - User session ID
    • +
    • %t - Date and time, in Common Log Format
    • +
    • %u - Remote user that was authenticated (if any), else '-'
    • +
    • %U - Requested URL path
    • +
    • %v - Local server name
    • +
    • %D - Time taken to process the request in millis. Note: In + httpd %D is microseconds. Behaviour will be aligned to httpd + in Tomcat 10 onwards.
    • +
    • %T - Time taken to process the request, in seconds. Note: This + value has millisecond resolution whereas in httpd it has + second resolution. Behaviour will be align to httpd + in Tomcat 10 onwards.
    • +
    • %F - Time taken to commit the response, in millis
    • +
    • %I - Current request thread name (can compare later with stacktraces)
    • +
    • %X - Connection status when response is completed: +
        +
      • X = Connection aborted before the response completed.
      • +
      • + = Connection may be kept alive after the response is sent.
      • +
      • - = Connection will be closed after the response is sent.
      • +
      +
    • +
    + +

    + There is also support to write information incoming or outgoing + headers, cookies, session or request attributes and special + timestamp formats. + It is modeled after the + Apache HTTP Server log configuration + syntax. Each of them can be used multiple times with different xxx keys: +

    +
      +
    • %{xxx}i write value of incoming header with name xxx
    • +
    • %{xxx}o write value of outgoing header with name xxx
    • +
    • %{xxx}c write value of cookie with name xxx
    • +
    • %{xxx}r write value of ServletRequest attribute with name xxx
    • +
    • %{xxx}s write value of HttpSession attribute with name xxx
    • +
    • %{xxx}p write local (server) port (xxx==local) or + remote (client) port (xxx=remote)
    • +
    • %{xxx}t write timestamp at the end of the request formatted using the + enhanced SimpleDateFormat pattern xxx
    • +
    + +

    All formats supported by SimpleDateFormat are allowed in %{xxx}t. + In addition the following extensions have been added:

    +
      +
    • sec - number of seconds since the epoch
    • +
    • msec - number of milliseconds since the epoch
    • +
    • msec_frac - millisecond fraction
    • +
    +

    These formats cannot be mixed with SimpleDateFormat formats in the same format + token.

    + +

    Furthermore one can define whether to log the timestamp for the request start + time or the response finish time:

    +
      +
    • begin or prefix begin: chooses + the request start time
    • +
    • end or prefix end: chooses + the response finish time
    • +
    +

    By adding multiple %{xxx}t tokens to the pattern, one can + also log both timestamps.

    + +

    The shorthand pattern pattern="common" + corresponds to the Common Log Format defined by + '%h %l %u %t "%r" %s %b'.

    + +

    The shorthand pattern pattern="combined" + appends the values of the Referer and User-Agent + headers, each in double quotes, to the common pattern.

    + +

    When Tomcat is operating behind a reverse proxy, the client information + logged by the Access Log Valve may represent the reverse proxy, the browser + or some combination of the two depending on the configuration of Tomcat and + the reverse proxy. For Tomcat configuration options see + Proxies Support and the + Proxy How-To. For reverse proxies that + use mod_jk, see the generic + proxy documentation. For other reverse proxies, consult their + documentation.

    +
    + +
    + + +

    Extended Access Log Valve

    + +

    Introduction

    + +

    The Extended Access Log Valve extends the + Access Log Valve class, and so + uses the same self-contained logging logic. This means it + implements many of the same file handling attributes. The main + difference to the standard AccessLogValve is that + ExtendedAccessLogValve creates log files which + conform to the Working Draft for the + Extended Log File Format + defined by the W3C.

    + +
    + +

    Attributes

    + +

    The Extended Access Log Valve supports all + configuration attributes of the standard + Access Log Valve. Only the + values used for className and pattern differ.

    + +
    + Attribute + + Description +
    className +

    Java class name of the implementation to use. This MUST be set to + org.apache.catalina.valves.ExtendedAccessLogValve to + use the extended access log valve.

    +
    pattern +

    A formatting layout identifying the various information fields + from the request and response to be logged. + See below for more information on configuring this attribute.

    +
    + +

    Values for the pattern attribute are made up of + format tokens. Some of the tokens need an additional prefix. Possible + prefixes are c for "client", s for "server", + cs for "client to server", sc for + "server to client" or x for "application specific". + Furthermore some tokens are completed by an additional selector. + See the W3C specification + for more information about the format.

    + +

    The following format tokens are supported:

    +
      +
    • bytes - Bytes sent, excluding HTTP headers, or '-' if zero
    • +
    • c-dns - Remote host name (or IP address if + enableLookups for the connector is false)
    • +
    • c-ip - Remote IP address
    • +
    • cs-method - Request method (GET, POST, etc.)
    • +
    • cs-uri - Request URI
    • +
    • cs-uri-query - Query string (prepended with a '?' if it exists)
    • +
    • cs-uri-stem - Requested URL path
    • +
    • date - The date in yyyy-mm-dd format for GMT
    • +
    • s-dns - Local host name
    • +
    • s-ip - Local IP address
    • +
    • sc-status - HTTP status code of the response
    • +
    • time - Time the request was served in HH:mm:ss format for GMT
    • +
    • time-taken - Time (in seconds as floating point) taken to serve the request
    • +
    • x-threadname - Current request thread name (can compare later with stacktraces)
    • +
    + +

    For any of the x-H(XXX) the following method will be called from the + HttpServletRequest object:

    +
      +
    • x-H(authType): getAuthType
    • +
    • x-H(characterEncoding): getCharacterEncoding
    • +
    • x-H(contentLength): getContentLength
    • +
    • x-H(locale): getLocale
    • +
    • x-H(protocol): getProtocol
    • +
    • x-H(remoteUser): getRemoteUser
    • +
    • x-H(requestedSessionId): getRequestedSessionId
    • +
    • x-H(requestedSessionIdFromCookie): + isRequestedSessionIdFromCookie
    • +
    • x-H(requestedSessionIdValid): + isRequestedSessionIdValid
    • +
    • x-H(scheme): getScheme
    • +
    • x-H(secure): isSecure
    • +
    + +

    + There is also support to write information about headers + cookies, context, request or session attributes and request + parameters. +

    +
      +
    • cs(XXX) for incoming request headers with name XXX
    • +
    • sc(XXX) for outgoing response headers with name XXX
    • +
    • x-A(XXX) for the servlet context attribute with name XXX
    • +
    • x-C(XXX) for the first cookie with name XXX
    • +
    • x-O(XXX) for a concatenation of all outgoing response headers with name XXX
    • +
    • x-P(XXX) for the URL encoded (using UTF-8) request parameter with name XXX
    • +
    • x-R(XXX) for the request attribute with name XXX
    • +
    • x-S(XXX) for the session attribute with name XXX
    • +
    + +
    + +
    + +

    Access Control

    + + +

    Remote Address Valve

    + +

    Introduction

    + +

    The Remote Address Valve allows you to compare the + IP address of the client that submitted this request against one or more + regular expressions, and either allow the request to continue + or refuse to process the request from this client. A Remote Address + Valve can be associated with any Catalina container + (Engine, Host, or + Context), and must accept any request + presented to this container for processing before it will be passed on.

    + +

    The syntax for regular expressions is different than that for + 'standard' wildcard matching. Tomcat uses the java.util.regex + package. Please consult the Java documentation for details of the + expressions supported.

    + +

    Optionally one can append the server connector port separated with a + semicolon (";") to allow different expressions for each connector.

    + +

    The behavior when a request is refused can be changed + to not deny but instead set an invalid authentication + header. This is useful in combination with the context attribute + preemptiveAuthentication="true".

    + +

    Note: There is a caveat when using this valve with + IPv6 addresses. Format of the IP address that this valve is processing + depends on the API that was used to obtain it. If the address was obtained + from Java socket using Inet6Address class, its format will be + x:x:x:x:x:x:x:x. That is, the IP address for localhost + will be 0:0:0:0:0:0:0:1 instead of the more widely used + ::1. Consult your access logs for the actual value.

    + +

    See also: Remote Host Valve, + Remote IP Valve.

    +
    + +

    Attributes

    + +

    The Remote Address Valve supports the following + configuration attributes:

    + +
    + Attribute + + Description +
    className +

    Java class name of the implementation to use. This MUST be set to + org.apache.catalina.valves.RemoteAddrValve.

    +
    allow +

    A regular expression (using java.util.regex) that the + remote client's IP address is compared to. If this attribute + is specified, the remote address MUST match for this request to be + accepted. If this attribute is not specified, all requests will be + accepted UNLESS the remote address matches a deny + pattern.

    +
    deny +

    A regular expression (using java.util.regex) that the + remote client's IP address is compared to. If this attribute + is specified, the remote address MUST NOT match for this request to be + accepted. If this attribute is not specified, request acceptance is + governed solely by the allow attribute.

    +
    denyStatus +

    HTTP response status code that is used when rejecting denied + request. The default value is 403. For example, + it can be set to the value 404.

    +
    addConnectorPort +

    Append the server connector port to the client IP address separated + with a semicolon (";"). If this is set to true, the + expressions configured with allow and + deny is compared against ADDRESS;PORT + where ADDRESS is the client IP address and + PORT is the Tomcat connector port which received the + request. The default value is false.

    +
    invalidAuthenticationWhenDeny +

    When a request should be denied, do not deny but instead + set an invalid authentication header. This only works + if the context has the attribute preemptiveAuthentication="true" + set. An already existing authentication header will not be + overwritten. In effect this will trigger authentication instead of deny + even if the application does not have a security constraint configured.

    +

    This can be combined with addConnectorPort to trigger authentication + depending on the client and the connector that is used to access an application.

    +
    + +
    + +

    Example 1

    +

    To allow access only for the clients connecting from localhost:

    +
    <Valve className="org.apache.catalina.valves.RemoteAddrValve"
    +   allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1"/>
    +
    + +

    Example 2

    +

    To allow unrestricted access for the clients connecting from localhost + but for all other clients only to port 8443:

    +
    <Valve className="org.apache.catalina.valves.RemoteAddrValve"
    +   addConnectorPort="true"
    +   allow="127\.\d+\.\d+\.\d+;\d*|::1;\d*|0:0:0:0:0:0:0:1;\d*|.*;8443"/>
    +
    + +

    Example 3

    +

    To allow unrestricted access to port 8009, but trigger basic + authentication if the application is accessed on another port:

    +
    <Context>
    +  ...
    +  <Valve className="org.apache.catalina.valves.RemoteAddrValve"
    +         addConnectorPort="true"
    +         invalidAuthenticationWhenDeny="true"
    +         allow=".*;8009"/>
    +  <Valve className="org.apache.catalina.authenticator.BasicAuthenticator" />
    +  ...
    +</Context>
    +
    + +
    + + +

    Remote Host Valve

    + +

    Introduction

    + +

    The Remote Host Valve allows you to compare the + hostname of the client that submitted this request against one or more + regular expressions, and either allow the request to continue + or refuse to process the request from this client. A Remote Host + Valve can be associated with any Catalina container + (Engine, Host, or + Context), and must accept any request + presented to this container for processing before it will be passed on.

    + +

    The syntax for regular expressions is different than that for + 'standard' wildcard matching. Tomcat uses the java.util.regex + package. Please consult the Java documentation for details of the + expressions supported.

    + +

    Optionally one can append the server connector port separated with a + semicolon (";") to allow different expressions for each connector.

    + +

    The behavior when a request is refused can be changed + to not deny but instead set an invalid authentication + header. This is useful in combination with the context attribute + preemptiveAuthentication="true".

    + +

    Note: This valve processes the value returned by + method ServletRequest.getRemoteHost(). To allow the method + to return proper host names, you have to enable "DNS lookups" feature on + a Connector.

    + +

    See also: Remote Address Valve, + HTTP Connector configuration.

    +
    + +

    Attributes

    + +

    The Remote Host Valve supports the following + configuration attributes:

    + +
    + Attribute + + Description +
    className +

    Java class name of the implementation to use. This MUST be set to + org.apache.catalina.valves.RemoteHostValve.

    +
    allow +

    A regular expression (using java.util.regex) that the + remote client's hostname is compared to. If this attribute + is specified, the remote hostname MUST match for this request to be + accepted. If this attribute is not specified, all requests will be + accepted UNLESS the remote hostname matches a deny + pattern.

    +
    deny +

    A regular expression (using java.util.regex) that the + remote client's hostname is compared to. If this attribute + is specified, the remote hostname MUST NOT match for this request to be + accepted. If this attribute is not specified, request acceptance is + governed solely by the allow attribute.

    +
    denyStatus +

    HTTP response status code that is used when rejecting denied + request. The default value is 403. For example, + it can be set to the value 404.

    +
    addConnectorPort +

    Append the server connector port to the client hostname separated + with a semicolon (";"). If this is set to true, the + expressions configured with allow and + deny is compared against HOSTNAME;PORT + where HOSTNAME is the client hostname and + PORT is the Tomcat connector port which received the + request. The default value is false.

    +
    invalidAuthenticationWhenDeny +

    When a request should be denied, do not deny but instead + set an invalid authentication header. This only works + if the context has the attribute preemptiveAuthentication="true" + set. An already existing authentication header will not be + overwritten. In effect this will trigger authentication instead of deny + even if the application does not have a security constraint configured.

    +

    This can be combined with addConnectorPort to trigger authentication + depending on the client and the connector that is used to access an application.

    +
    + +
    + +
    + +

    Remote CIDR Valve

    + +

    Introduction

    + +

    The Remote CIDR Valve allows you to compare the + IP address of the client that submitted this request against one or more + netmasks following the CIDR notation, and either allow the request to + continue or refuse to process the request from this client. IPv4 and + IPv6 are both fully supported. A Remote CIDR Valve can be associated + with any Catalina container (Engine, + Host, or Context), and + must accept any request presented to this container for processing before + it will be passed on. +

    + +

    This valve mimicks Apache's Order, + Allow from and Deny from directives, + with the following limitations: +

    + +
      +
    • Order will always be allow, deny;
    • +
    • dotted quad notations for netmasks are not supported (that is, you + cannot write 192.168.1.0/255.255.255.0, you must write + 192.168.1.0/24; +
    • +
    • shortcuts, like 10.10., which is equivalent to + 10.10.0.0/16, are not supported; +
    • +
    • as the valve name says, this is a CIDR only valve, + therefore subdomain notations like .mydomain.com are not + supported either. +
    • +
    + +

    Some more features of this valve are: +

    + +
      +
    • if you omit the CIDR prefix, this valve becomes a single IP + valve;
    • +
    • unlike the Remote Host Valve, + it can handle IPv6 addresses in condensed form (::1, + fe80::/71, etc).
    • +
    + +
    + +

    Attributes

    + +

    The Remote CIDR Valve supports the following + configuration attributes:

    + +
    + Attribute + + Description +
    className +

    Java class name of the implementation to use. This MUST be set to + org.apache.catalina.valves.RemoteCIDRValve.

    +
    allow +

    A comma-separated list of IPv4 or IPv6 netmasks or addresses + that the remote client's IP address is matched against. + If this attribute is specified, the remote address MUST match + for this request to be accepted. If this attribute is not specified, + all requests will be accepted UNLESS the remote IP is matched by a + netmask in the deny attribute. +

    +
    deny +

    A comma-separated list of IPv4 or IPv6 netmasks or addresses + that the remote client's IP address is matched against. + If this attribute is specified, the remote address MUST NOT match + for this request to be accepted. If this attribute is not specified, + request acceptance is governed solely by the accept + attribute. +

    +
    + +
    + +

    Example

    +

    To allow access only for the clients connecting from localhost:

    +
    +      <Valve className="org.apache.catalina.valves.RemoteCIDRValve"
    +      allow="127.0.0.1, ::1"/>
    +    
    +
    + +
    + + +

    Proxies Support

    +

    Load Balancer Draining Valve

    +

    Introduction

    +

    + When using mod_jk or mod_proxy_ajp, the client's session id is used to + determine which back-end server will be used to serve the request. If the + target node is being "drained" (in mod_jk, this is the DISABLED + state; in mod_proxy_ajp, this is the Drain (N) state), requests + for expired sessions can actually cause the draining node to fail to + drain. +

    +

    + Unfortunately, AJP-based load-balancers cannot prove whether the + client-provided session id is valid or not and therefore will send any + requests for a session that appears to be targeted to that node to the + disabled (or "draining") node, causing the "draining" process to take + longer than necessary. +

    +

    + This Valve detects requests for invalid sessions, strips the session + information from the request, and redirects back to the same URL, where + the load-balancer should choose a different (active) node to handle the + request. This will accelerate the "draining" process for the disabled + node(s). +

    + +

    + The activation state of the node is sent by the load-balancer in the + request, so no state change on the node being disabled is necessary. Simply + configure this Valve in your valve pipeline and it will take action when + the activation state is set to "disabled". +

    + +

    + You should take care to register this Valve earlier in the Valve pipeline + than any authentication Valves, because this Valve should be able to + redirect a request before any authentication Valve saves a request to a + protected resource. If this happens, a new session will be created and + the draining process will stall because a new, valid session will be + established. +

    +
    + +

    Attributes

    +

    The Load Balancer Draining Valve supports the + following configuration attributes:

    + +
    + Attribute + + Description +
    className +

    Java class name of the implementation to use. This MUST be set to + org.apache.catalina.valves.LoadBalancerDrainingValve. +

    +
    redirectStatusCode +

    Allows setting a custom redirect code to be used when the client + is redirected to be re-balanced by the load-balancer. The default is + 307 TEMPORARY_REDIRECT.

    +
    ignoreCookieName +

    When used with ignoreCookieValue, a client can present + this cookie (and accompanying value) that will cause this Valve to + do nothing. This will allow you to probe your disabled node + before re-enabling it to make sure that it is working as expected.

    +
    ignoreCookieValue +

    When used with ignoreCookieName, a client can present + a cookie (and accompanying value) that will cause this Valve to + do nothing. This will allow you to probe your disabled node + before re-enabling it to make sure that it is working as expected.

    +
    +
    +
    + +

    Remote IP Valve

    + +

    Introduction

    + +

    Tomcat port of + mod_remoteip, + this valve replaces the apparent client remote IP address and hostname for + the request with the IP address list presented by a proxy or a load balancer + via a request headers (e.g. "X-Forwarded-For").

    + +

    Another feature of this valve is to replace the apparent scheme + (http/https), server port and request.secure with the scheme presented + by a proxy or a load balancer via a request header + (e.g. "X-Forwarded-Proto").

    + +

    This Valve may be used at the Engine, Host or + Context level as required. Normally, this Valve would be used + at the Engine level.

    + +

    If used in conjunction with Remote Address/Host valves then this valve + should be defined first to ensure that the correct client IP address is + presented to the Remote Address/Host valves.

    + +

    Note: By default this valve has no effect on the + values that are written into access log. The original values are restored + when request processing leaves the valve and that always happens earlier + than access logging. To pass the remote address, remote host, server port + and protocol values set by this valve to the access log, + they are put into request attributes. Publishing these values here + is enabled by default, but AccessLogValve should be explicitly + configured to use them. See documentation for + requestAttributesEnabled attribute of + AccessLogValve.

    + +

    The names of request attributes that are set by this valve + and can be used by access logging are the following:

    + +
      +
    • org.apache.catalina.AccessLog.RemoteAddr
    • +
    • org.apache.catalina.AccessLog.RemoteHost
    • +
    • org.apache.catalina.AccessLog.Protocol
    • +
    • org.apache.catalina.AccessLog.ServerPort
    • +
    • org.apache.tomcat.remoteAddr
    • +
    + +
    + +

    Attributes

    + +

    The Remote IP Valve supports the + following configuration attributes:

    + +
    + Attribute + + Description +
    className +

    Java class name of the implementation to use. This MUST be set to + org.apache.catalina.valves.RemoteIpValve.

    +
    remoteIpHeader +

    Name of the HTTP Header read by this valve that holds the list of + traversed IP addresses starting from the requesting client. If not + specified, the default of x-forwarded-for is used.

    +
    internalProxies +

    Regular expression (using java.util.regex) that a + proxy's IP address must match to be considered an internal proxy. + Internal proxies that appear in the remoteIpHeader will + be trusted and will not appear in the proxiesHeader + value. If not specified the default value of + 10\.\d{1,3}\.\d{1,3}\.\d{1,3}|192\.168\.\d{1,3}\.\d{1,3}|169\.254\.\d{1,3}\.\d{1,3}|127\.\d{1,3}\.\d{1,3}\.\d{1,3}|172\.1[6-9]{1}\.\d{1,3}\.\d{1,3}|172\.2[0-9]{1}\.\d{1,3}\.\d{1,3}|172\.3[0-1]{1}\.\d{1,3}\.\d{1,3}|0:0:0:0:0:0:0:1 + will be used.

    +
    proxiesHeader +

    Name of the HTTP header created by this valve to hold the list of + proxies that have been processed in the incoming + remoteIpHeader. If not specified, the default of + x-forwarded-by is used.

    +
    requestAttributesEnabled +

    Set to true to set the request attributes used by + AccessLog implementations to override the values returned by the + request for remote address, remote host, server port and protocol. + Request attributes are also used to enable the forwarded remote address + to be displayed on the status page of the Manager web application. + If not set, the default value of true will be used.

    +
    trustedProxies +

    Regular expression (using java.util.regex) that a + proxy's IP address must match to be considered an trusted proxy. + Trusted proxies that appear in the remoteIpHeader will + be trusted and will appear in the proxiesHeader value. + If not specified, no proxies will be trusted.

    +
    protocolHeader +

    Name of the HTTP Header read by this valve that holds the protocol + used by the client to connect to the proxy. If not specified, the + default of X-Forwarded-Proto is used.

    +
    portHeader +

    Name of the HTTP Header read by this valve that holds the port + used by the client to connect to the proxy. If not specified, the + default of null is used.

    +
    protocolHeaderHttpsValue +

    Value of the protocolHeader to indicate that it is + an HTTPS request. If not specified, the default of https is + used.

    +
    httpServerPort +

    Value returned by ServletRequest.getServerPort() + when the protocolHeader indicates http + protocol and no portHeader is present. If not + specified, the default of 80 is used.

    +
    httpsServerPort +

    Value returned by ServletRequest.getServerPort() + when the protocolHeader indicates https + protocol and no portHeader is present. If not + specified, the default of 443 is used.

    +
    changeLocalPort +

    If true, the value returned by + ServletRequest.getLocalPort() and + ServletRequest.getServerPort() is modified by the this + valve. If not specified, the default of false is used.

    +
    + +
    + +
    + + +

    SSL Valve

    + +

    Introduction

    + +

    When using mod_proxy_http, the client SSL information is not included in + the protocol (unlike mod_jk and mod_proxy_ajp). To make the client SSL + information available to Tomcat, some additional configuration is required. + In httpd, mod_headers is used to add the SSL information as HTTP headers. In + Tomcat, this valve is used to read the information from the HTTP headers and + insert it into the request.

    + +

    Note: Ensure that the headers are always set by httpd for all requests to + prevent a client spoofing SSL information by sending fake headers.

    + +

    To configure httpd to set the necessary headers, add the following:

    +
    <IfModule ssl_module>
    +  RequestHeader set SSL_CLIENT_CERT "%{SSL_CLIENT_CERT}s"
    +  RequestHeader set SSL_CIPHER "%{SSL_CIPHER}s"
    +  RequestHeader set SSL_SESSION_ID "%{SSL_SESSION_ID}s"
    +  RequestHeader set SSL_CIPHER_USEKEYSIZE "%{SSL_CIPHER_USEKEYSIZE}s"
    +</IfModule>
    + +
    + +

    Attributes

    + +

    The SSL Valve supports the following configuration + attribute:

    + +
    + Attribute + + Description +
    className +

    Java class name of the implementation to use. This MUST be set to + org.apache.catalina.valves.SSLValve. +

    +
    sslClientCertHeader +

    Allows setting a custom name for the ssl_client_cert header. + If not specified, the default of ssl_client_cert is + used.

    +
    sslCipherHeader +

    Allows setting a custom name for the ssl_cipher header. + If not specified, the default of ssl_cipher is + used.

    +
    sslSessionIdHeader +

    Allows setting a custom name for the ssl_session_id header. + If not specified, the default of ssl_session_id is + used.

    +
    sslCipherUserKeySizeHeader +

    Allows setting a custom name for the ssl_cipher_usekeysize header. + If not specified, the default of ssl_cipher_usekeysize is + used.

    +
    + +
    + +
    + + +

    Single Sign On Valve

    + +

    Introduction

    + +

    The Single Sign On Valve is utilized when you wish to give users + the ability to sign on to any one of the web applications associated with + your virtual host, and then have their identity recognized by all other + web applications on the same virtual host.

    + +

    See the Single Sign On special + feature on the Host element for more information.

    + +
    + + +

    Attributes

    + +

    The Single Sign On Valve supports the following + configuration attributes:

    + +
    + Attribute + + Description +
    className +

    Java class name of the implementation to use. This MUST be set to + org.apache.catalina.authenticator.SingleSignOn.

    +
    requireReauthentication +

    Default false. Flag to determine whether each request needs to be + reauthenticated to the security Realm. If "true", this + Valve uses cached security credentials (username and password) to + reauthenticate to the Realm each request associated + with an SSO session. If "false", the Valve can itself authenticate + requests based on the presence of a valid SSO cookie, without + rechecking with the Realm.

    +
    cookieDomain +

    Sets the host domain to be used for sso cookies.

    +
    + +
    + + +

    Authentication

    + +

    The valves in this section implement +org.apache.catalina.Authenticator interface.

    + +

    Basic Authenticator Valve

    + +

    Introduction

    + +

    The Basic Authenticator Valve is automatically added to + any Context that is configured to use BASIC + authentication.

    + +

    If any non-default settings are required, the valve may be configured + within Context element with the required + values.

    + +
    + +

    Attributes

    + +

    The Basic Authenticator Valve supports the following + configuration attributes:

    + +
    + Attribute + + Description +
    alwaysUseSession +

    Should a session always be used once a user is authenticated? This + may offer some performance benefits since the session can then be used + to cache the authenticated Principal, hence removing the need to + authenticate the user via the Realm on every request. This may be of + help for combinations such as BASIC authentication used with the + JNDIRealm or DataSourceRealms. However there will also be the + performance cost of creating and GC'ing the session. If not set, the + default value of false will be used.

    +
    cache +

    Should we cache authenticated Principals if the request is part of an + HTTP session? If not specified, the default value of true + will be used.

    +
    changeSessionIdOnAuthentication +

    Controls if the session ID is changed if a session exists at the + point where users are authenticated. This is to prevent session fixation + attacks. If not set, the default value of true will be + used.

    +
    charset +

    Controls if the WWW-Authenticate HTTP header includes a + charset authentication parameter as per RFC 7617. The only + permitted options are null, the empty string and + UTF-8. If UTF-8 is specified then the + charset authentication parameter will be sent with that + value and the provided user name and optional password will be converted + from bytes to characters using UTF-8. Otherwise, no charset + authentication parameter will be sent and the provided user name and + optional password will be converted from bytes to characters using + ISO-8859-1. The default value is null

    +
    className +

    Java class name of the implementation to use. This MUST be set to + org.apache.catalina.authenticator.BasicAuthenticator.

    +
    disableProxyCaching +

    Controls the caching of pages that are protected by security + constraints. Setting this to false may help work around + caching issues in some browsers but will also cause secured pages to be + cached by proxies which will almost certainly be a security issue. + securePagesWithPragma offers an alternative, secure, + workaround for browser caching issues. If not set, the default value of + true will be used.

    +
    securePagesWithPragma +

    Controls the caching of pages that are protected by security + constraints. Setting this to false may help work around + caching issues in some browsers by using + Cache-Control: private rather than the default of + Pragma: No-cache and Cache-control: No-cache. + If not set, the default value of false will be used.

    +
    secureRandomAlgorithm +

    Name of the algorithm to use to create the + java.security.SecureRandom instances that generate session + IDs. If an invalid algorithm and/or provider is specified, the platform + default provider and the default algorithm will be used. If not + specified, the default algorithm of SHA1PRNG will be used. If the + default algorithm is not supported, the platform default will be used. + To specify that the platform default should be used, do not set the + secureRandomProvider attribute and set this attribute to the empty + string.

    +
    secureRandomClass +

    Name of the Java class that extends + java.security.SecureRandom to use to generate SSO session + IDs. If not specified, the default value is + java.security.SecureRandom.

    +
    secureRandomProvider +

    Name of the provider to use to create the + java.security.SecureRandom instances that generate SSO + session IDs. If an invalid algorithm and/or provider is specified, the + platform default provider and the default algorithm will be used. If not + specified, the platform default provider will be used.

    +
    trimCredentials +

    Controls whether leading and/or trailing whitespace is removed from + the parsed credentials. If not specified, the default value is + true.

    +
    jaspicCallbackHandlerClass +

    Name of the Java class of the + javax.security.auth.callback.CallbackHandler implementation + which should be used by JASPIC. If none is specified the default + org.apache.catalina.authenticator.jaspic.CallbackHandlerImpl + will be used.

    +
    + +
    + +
    + + +

    Digest Authenticator Valve

    + +

    Introduction

    + +

    The Digest Authenticator Valve is automatically added to + any Context that is configured to use DIGEST + authentication.

    + +

    If any non-default settings are required, the valve may be configured + within Context element with the required + values.

    + +
    + +

    Attributes

    + +

    The Digest Authenticator Valve supports the following + configuration attributes:

    + +
    + Attribute + + Description +
    alwaysUseSession +

    Should a session always be used once a user is authenticated? This + may offer some performance benefits since the session can then be used + to cache the authenticated Principal, hence removing the need to + authenticate the user via the Realm on every request. This may be of + help for combinations such as BASIC authentication used with the + JNDIRealm or DataSourceRealms. However there will also be the + performance cost of creating and GC'ing the session. If not set, the + default value of false will be used.

    +
    cache +

    Should we cache authenticated Principals if the request is part of an + HTTP session? If not specified, the default value of false + will be used.

    +
    changeSessionIdOnAuthentication +

    Controls if the session ID is changed if a session exists at the + point where users are authenticated. This is to prevent session fixation + attacks. If not set, the default value of true will be + used.

    +
    className +

    Java class name of the implementation to use. This MUST be set to + org.apache.catalina.authenticator.DigestAuthenticator.

    +
    disableProxyCaching +

    Controls the caching of pages that are protected by security + constraints. Setting this to false may help work around + caching issues in some browsers but will also cause secured pages to be + cached by proxies which will almost certainly be a security issue. + securePagesWithPragma offers an alternative, secure, + workaround for browser caching issues. If not set, the default value of + true will be used.

    +
    key +

    The secret key used by digest authentication. If not set, a secure + random value is generated. This should normally only be set when it is + necessary to keep key values constant either across server restarts + and/or across a cluster.

    +
    nonceCacheSize +

    To protect against replay attacks, the DIGEST authenticator tracks + server nonce and nonce count values. This attribute controls the size + of that cache. If not specified, the default value of 1000 is used.

    +
    nonceCountWindowSize +

    Client requests may be processed out of order which in turn means + that the nonce count values may be processed out of order. To prevent + authentication failures when nonce counts are presented out of order + the authenticator tracks a window of nonce count values. This attribute + controls how big that window is. If not specified, the default value of + 100 is used.

    +
    nonceValidity +

    The time, in milliseconds, that a server generated nonce will be + considered valid for use in authentication. If not specified, the + default value of 300000 (5 minutes) will be used.

    +
    opaque +

    The opaque server string used by digest authentication. If not set, a + random value is generated. This should normally only be set when it is + necessary to keep opaque values constant either across server restarts + and/or across a cluster.

    +
    securePagesWithPragma +

    Controls the caching of pages that are protected by security + constraints. Setting this to false may help work around + caching issues in some browsers by using + Cache-Control: private rather than the default of + Pragma: No-cache and Cache-control: No-cache. + If not set, the default value of false will be used.

    +
    secureRandomAlgorithm +

    Name of the algorithm to use to create the + java.security.SecureRandom instances that generate session + IDs. If an invalid algorithm and/or provider is specified, the platform + default provider and the default algorithm will be used. If not + specified, the default algorithm of SHA1PRNG will be used. If the + default algorithm is not supported, the platform default will be used. + To specify that the platform default should be used, do not set the + secureRandomProvider attribute and set this attribute to the empty + string.

    +
    secureRandomClass +

    Name of the Java class that extends + java.security.SecureRandom to use to generate SSO session + IDs. If not specified, the default value is + java.security.SecureRandom.

    +
    secureRandomProvider +

    Name of the provider to use to create the + java.security.SecureRandom instances that generate SSO + session IDs. If an invalid algorithm and/or provider is specified, the + platform default provider and the default algorithm will be used. If not + specified, the platform default provider will be used.

    +
    validateUri +

    Should the URI be validated as required by RFC2617? If not specified, + the default value of true will be used. This should + normally only be set when Tomcat is located behind a reverse proxy and + the proxy is modifying the URI passed to Tomcat such that DIGEST + authentication always fails.

    +
    jaspicCallbackHandlerClass +

    Name of the Java class of the + javax.security.auth.callback.CallbackHandler implementation + which should be used by JASPIC. If none is specified the default + org.apache.catalina.authenticator.jaspic.CallbackHandlerImpl + will be used.

    +
    + +
    + +
    + + +

    Form Authenticator Valve

    + +

    Introduction

    + +

    The Form Authenticator Valve is automatically added to + any Context that is configured to use FORM + authentication.

    + +

    If any non-default settings are required, the valve may be configured + within Context element with the required + values.

    + +
    + +

    Attributes

    + +

    The Form Authenticator Valve supports the following + configuration attributes:

    + +
    + Attribute + + Description +
    changeSessionIdOnAuthentication +

    Controls if the session ID is changed if a session exists at the + point where users are authenticated. This is to prevent session fixation + attacks. If not set, the default value of true will be + used.

    +
    characterEncoding +

    Character encoding to use to read the username and password parameters + from the request. If not set, the encoding of the request body will be + used.

    +
    className +

    Java class name of the implementation to use. This MUST be set to + org.apache.catalina.authenticator.FormAuthenticator.

    +
    disableProxyCaching +

    Controls the caching of pages that are protected by security + constraints. Setting this to false may help work around + caching issues in some browsers but will also cause secured pages to be + cached by proxies which will almost certainly be a security issue. + securePagesWithPragma offers an alternative, secure, + workaround for browser caching issues. If not set, the default value of + true will be used.

    +
    landingPage +

    Controls the behavior of the FORM authentication process if the + process is misused, for example by directly requesting the login page + or delaying logging in for so long that the session expires. If this + attribute is set, rather than returning an error response code, Tomcat + will redirect the user to the specified landing page if the login form + is submitted with valid credentials. For the login to be processed, the + landing page must be a protected resource (i.e. one that requires + authentication). If the landing page does not require authentication + then the user will not be logged in and will be prompted for their + credentials again when they access a protected page.

    +
    securePagesWithPragma +

    Controls the caching of pages that are protected by security + constraints. Setting this to false may help work around + caching issues in some browsers by using + Cache-Control: private rather than the default of + Pragma: No-cache and Cache-control: No-cache. + If not set, the default value of false will be used.

    +
    secureRandomAlgorithm +

    Name of the algorithm to use to create the + java.security.SecureRandom instances that generate session + IDs. If an invalid algorithm and/or provider is specified, the platform + default provider and the default algorithm will be used. If not + specified, the default algorithm of SHA1PRNG will be used. If the + default algorithm is not supported, the platform default will be used. + To specify that the platform default should be used, do not set the + secureRandomProvider attribute and set this attribute to the empty + string.

    +
    secureRandomClass +

    Name of the Java class that extends + java.security.SecureRandom to use to generate SSO session + IDs. If not specified, the default value is + java.security.SecureRandom.

    +
    secureRandomProvider +

    Name of the provider to use to create the + java.security.SecureRandom instances that generate SSO + session IDs. If an invalid algorithm and/or provider is specified, the + platform default provider and the default algorithm will be used. If not + specified, the platform default provider will be used.

    +
    jaspicCallbackHandlerClass +

    Name of the Java class of the + javax.security.auth.callback.CallbackHandler implementation + which should be used by JASPIC. If none is specified the default + org.apache.catalina.authenticator.jaspic.CallbackHandlerImpl + will be used.

    +
    + +
    + +
    + + +

    SSL Authenticator Valve

    + +

    Introduction

    + +

    The SSL Authenticator Valve is automatically added to + any Context that is configured to use SSL + authentication.

    + +

    If any non-default settings are required, the valve may be configured + within Context element with the required + values.

    + +
    + +

    Attributes

    + +

    The SSL Authenticator Valve supports the following + configuration attributes:

    + +
    + Attribute + + Description +
    cache +

    Should we cache authenticated Principals if the request is part of an + HTTP session? If not specified, the default value of true + will be used.

    +
    className +

    Java class name of the implementation to use. This MUST be set to + org.apache.catalina.authenticator.SSLAuthenticator.

    +
    changeSessionIdOnAuthentication +

    Controls if the session ID is changed if a session exists at the + point where users are authenticated. This is to prevent session fixation + attacks. If not set, the default value of true will be + used.

    +
    disableProxyCaching +

    Controls the caching of pages that are protected by security + constraints. Setting this to false may help work around + caching issues in some browsers but will also cause secured pages to be + cached by proxies which will almost certainly be a security issue. + securePagesWithPragma offers an alternative, secure, + workaround for browser caching issues. If not set, the default value of + true will be used.

    +
    securePagesWithPragma +

    Controls the caching of pages that are protected by security + constraints. Setting this to false may help work around + caching issues in some browsers by using + Cache-Control: private rather than the default of + Pragma: No-cache and Cache-control: No-cache. + If not set, the default value of false will be used.

    +
    secureRandomAlgorithm +

    Name of the algorithm to use to create the + java.security.SecureRandom instances that generate session + IDs. If an invalid algorithm and/or provider is specified, the platform + default provider and the default algorithm will be used. If not + specified, the default algorithm of SHA1PRNG will be used. If the + default algorithm is not supported, the platform default will be used. + To specify that the platform default should be used, do not set the + secureRandomProvider attribute and set this attribute to the empty + string.

    +
    secureRandomClass +

    Name of the Java class that extends + java.security.SecureRandom to use to generate SSO session + IDs. If not specified, the default value is + java.security.SecureRandom.

    +
    secureRandomProvider +

    Name of the provider to use to create the + java.security.SecureRandom instances that generate SSO + session IDs. If an invalid algorithm and/or provider is specified, the + platform default provider and the default algorithm will be used. If not + specified, the platform default provider will be used.

    +
    jaspicCallbackHandlerClass +

    Name of the Java class of the + javax.security.auth.callback.CallbackHandler implementation + which should be used by JASPIC. If none is specified the default + org.apache.catalina.authenticator.jaspic.CallbackHandlerImpl + will be used.

    +
    + +
    + +
    + + +

    SPNEGO Valve

    + +

    Introduction

    + +

    The SPNEGO Authenticator Valve is automatically added to + any Context that is configured to use SPNEGO + authentication.

    + +

    If any non-default settings are required, the valve may be configured + within Context element with the required + values.

    + +
    + +

    Attributes

    + +

    The SPNEGO Authenticator Valve supports the following + configuration attributes:

    + +
    + Attribute + + Description +
    applyJava8u40Fix +

    A fix introduced in Java 8 update 40 ( + JDK-8048194) + onwards broke SPNEGO authentication for IE with Tomcat running on + Windows 2008 R2 servers. This option enables a work-around that allows + SPNEGO authentication to continue working. The work-around should not + impact other configurations so it is enabled by default. If necessary, + the workaround can be disabled by setting this attribute to + false.

    +
    alwaysUseSession +

    Should a session always be used once a user is authenticated? This + may offer some performance benefits since the session can then be used + to cache the authenticated Principal, hence removing the need to + authenticate the user on every request. This will also help with clients + that assume that the server will cache the authenticated user. However + there will also be the performance cost of creating and GC'ing the + session. For an alternative solution see + noKeepAliveUserAgents. If not set, the default value of + false will be used.

    +
    cache +

    Should we cache authenticated Principals if the request is part of an + HTTP session? If not specified, the default value of true + will be used.

    +
    className +

    Java class name of the implementation to use. This MUST be set to + org.apache.catalina.authenticator.SpnegoAuthenticator. +

    +
    changeSessionIdOnAuthentication +

    Controls if the session ID is changed if a session exists at the + point where users are authenticated. This is to prevent session fixation + attacks. If not set, the default value of true will be + used.

    +
    disableProxyCaching +

    Controls the caching of pages that are protected by security + constraints. Setting this to false may help work around + caching issues in some browsers but will also cause secured pages to be + cached by proxies which will almost certainly be a security issue. + securePagesWithPragma offers an alternative, secure, + workaround for browser caching issues. If not set, the default value of + true will be used.

    +
    loginConfigName +

    The name of the JAAS login configuration to be used to login as the + service. If not specified, the default of + com.sun.security.jgss.krb5.accept is used.

    +
    noKeepAliveUserAgents +

    Some clients (not most browsers) expect the server to cache the + authenticated user information for a connection and do not resend the + credentials with every request. Tomcat will not do this unless an HTTP + session is available. A session will be available if either the + application creates one or if alwaysUseSession is enabled + for this Authenticator.

    +

    As an alternative to creating a session, this attribute may be used + to define the user agents for which HTTP keep-alive is disabled. This + means that a connection will only used for a single request and hence + there is no ability to cache authenticated user information per + connection. There will be a performance cost in disabling HTTP + keep-alive.

    +

    The attribute should be a regular expression that matches the entire + user-agent string, e.g. .*Chrome.*. If not specified, no + regular expression will be defined and no user agents will have HTTP + keep-alive disabled.

    +
    securePagesWithPragma +

    Controls the caching of pages that are protected by security + constraints. Setting this to false may help work around + caching issues in some browsers by using + Cache-Control: private rather than the default of + Pragma: No-cache and Cache-control: No-cache. + If not set, the default value of false will be used.

    +
    secureRandomAlgorithm +

    Name of the algorithm to use to create the + java.security.SecureRandom instances that generate session + IDs. If an invalid algorithm and/or provider is specified, the platform + default provider and the default algorithm will be used. If not + specified, the default algorithm of SHA1PRNG will be used. If the + default algorithm is not supported, the platform default will be used. + To specify that the platform default should be used, do not set the + secureRandomProvider attribute and set this attribute to the empty + string.

    +
    secureRandomClass +

    Name of the Java class that extends + java.security.SecureRandom to use to generate SSO session + IDs. If not specified, the default value is + java.security.SecureRandom.

    +
    secureRandomProvider +

    Name of the provider to use to create the + java.security.SecureRandom instances that generate SSO + session IDs. If an invalid algorithm and/or provider is specified, the + platform default provider and the default algorithm will be used. If not + specified, the platform default provider will be used.

    +
    storeDelegatedCredential +

    Controls if the user' delegated credential will be stored in + the user Principal. If available, the delegated credential will be + available to applications (e.g. for onward authentication to external + services) via the org.apache.catalina.realm.GSS_CREDENTIAL + request attribute. If not set, the default value of true + will be used.

    +
    jaspicCallbackHandlerClass +

    Name of the Java class of the + javax.security.auth.callback.CallbackHandler implementation + which should be used by JASPIC. If none is specified the default + org.apache.catalina.authenticator.jaspic.CallbackHandlerImpl + will be used.

    +
    + +
    + +
    + + +

    Error Report Valve

    + +

    Introduction

    + +

    The Error Report Valve is a simple error handler + for HTTP status codes that will generate and return HTML error pages.

    + +

    NOTE: Disabling both showServerInfo and showReport will + only return the HTTP status code and remove all CSS.

    + +
    + +

    Attributes

    + +

    The Error Report Valve supports the following + configuration attributes:

    + +
    + Attribute + + Description +
    className +

    Java class name of the implementation to use. This MUST be set to + org.apache.catalina.valves.ErrorReportValve to use the + default error report valve.

    +
    showReport +

    Flag to determine if the error report (custom error message and/or + stack trace) is presented when an error occurs. If set to + false, then the error report is not returned in the HTML + response. + Default value: true +

    +
    showServerInfo +

    Flag to determine if server information is presented when an error + occurs. If set to false, then the server version is not + returned in the HTML response. + Default value: true +

    +
    + +
    + +

    Crawler Session Manager Valve

    + +

    Introduction

    + +

    Web crawlers can trigger the creation of many thousands of sessions as + they crawl a site which may result in significant memory consumption. This + Valve ensures that crawlers are associated with a single session - just like + normal users - regardless of whether or not they provide a session token + with their requests.

    + +

    This Valve may be used at the Engine, Host or + Context level as required. Normally, this Valve would be used + at the Engine level.

    + +

    If used in conjunction with Remote IP valve then the Remote IP valve + should be defined before this valve to ensure that the correct client IP + address is presented to this valve.

    + +
    + +

    Attributes

    + +

    The Crawler Session Manager Valve supports the + following configuration attributes:

    + +
    + Attribute + + Description +
    className +

    Java class name of the implementation to use. This MUST be set to + org.apache.catalina.valves.CrawlerSessionManagerValve. +

    +
    contextAware +

    Flag to use the context name together with the client IP to + identify the session to re-use. Can be combined with hostAware. + Default value: true +

    +
    crawlerIps +

    Regular expression (using java.util.regex) that client + IP is matched against to determine if a request is from a web crawler. + By default such regular expression is not set.

    +
    crawlerUserAgents +

    Regular expression (using java.util.regex) that the user + agent HTTP request header is matched against to determine if a request + is from a web crawler. If not set, the default of + .*[bB]ot.*|.*Yahoo! Slurp.*|.*Feedfetcher-Google.* is used.

    +
    hostAware +

    Flag to use the configured host together with the client IP to + identify the session to re-use. Can be combined with contextAware. + Default value: true +

    +
    sessionInactiveInterval +

    The minimum time in seconds that the Crawler Session Manager Valve + should keep the mapping of client IP to session ID in memory without any + activity from the client. The client IP / session cache will be + periodically purged of mappings that have been inactive for longer than + this interval. If not specified the default value of 60 + will be used.

    +
    + +
    + +

    Stuck Thread Detection Valve

    + +

    Introduction

    + +

    This valve allows to detect requests that take a long time to process, + which might indicate that the thread that is processing it is stuck. + Additionally it can optionally interrupt such threads to try and unblock + them.

    +

    When such a request is detected, the current stack trace of its thread is + written to Tomcat log with a WARN level.

    +

    The IDs and names of the stuck threads are available through JMX in the + stuckThreadIds and stuckThreadNames attributes. + The IDs can be used with the standard Threading JVM MBean + (java.lang:type=Threading) to retrieve other information + about each stuck thread.

    + +
    + +

    Attributes

    + +

    The Stuck Thread Detection Valve supports the + following configuration attributes:

    + +
    + Attribute + + Description +
    className +

    Java class name of the implementation to use. This MUST be set to + org.apache.catalina.valves.StuckThreadDetectionValve. +

    +
    threshold +

    Minimum duration in seconds after which a thread is considered stuck. + Default is 600 seconds. If set to 0, the detection is disabled.

    +

    Note: since the detection (and optional interruption) is done in the + background thread of the Container (Engine, Host or Context) declaring + this Valve, the threshold should be higher than the + backgroundProcessorDelay of this Container.

    +
    interruptThreadThreshold +

    Minimum duration in seconds after which a stuck thread should be + interrupted to attempt to "free" it.

    +

    Note that there's no guarantee that the thread will get unstuck. + This usually works well for threads stuck on I/O or locks, but is + probably useless in case of infinite loops.

    +

    Default is -1 which disables the feature. To enable it, the value + must be greater or equal to threshold.

    +
    + +
    + +

    Semaphore Valve

    + +

    Introduction

    + +

    The Semaphore Valve is able to limit the number of + concurrent request processing threads.

    +

    org.apache.catalina.valves.SemaphoreValve provides + methods which may be overridden by a subclass to customize behavior:

    +
      +
    • controlConcurrency may be overridden to add + conditions;
    • +
    • permitDenied may be overridden to add error handling + when a permit isn't granted.
    • +
    + +
    + +

    Attributes

    + +

    The Semaphore Valve supports the following + configuration attributes:

    + +
    + Attribute + + Description +
    block +

    Flag to determine if a thread is blocked until a permit is available. + The default value is true.

    +
    className +

    Java class name of the implementation to use. This MUST be set to + org.apache.catalina.valves.SemaphoreValve.

    +
    concurrency +

    Concurrency level of the semaphore. The default value is + 10.

    +
    fairness +

    Fairness of the semaphore. The default value is + false.

    +
    interruptible +

    Flag to determine if a thread may be interrupted until a permit is + available. The default value is false.

    +
    + +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/connectors.html b/tomcat/docs/connectors.html new file mode 100644 index 0000000..fa2d09c --- /dev/null +++ b/tomcat/docs/connectors.html @@ -0,0 +1,86 @@ + +Apache Tomcat 8 (8.5.43) - Connectors How To

    Connectors How To

    Table of Contents

    Introduction

    + +

    Choosing a connector to use with Tomcat can be difficult. This page will +list the connectors which are supported with this Tomcat release, and will +hopefully help you make the right choice according to your needs.

    + +

    HTTP

    + +

    The HTTP connector is setup by default with Tomcat, and is ready to use. This +connector features the lowest latency and best overall performance.

    + +

    For clustering, a HTTP load balancer with support for web sessions stickiness +must be installed to direct the traffic to the Tomcat servers. Tomcat supports mod_proxy +(on Apache HTTP Server 2.x, and included by default in Apache HTTP Server 2.2) as the load balancer. +It should be noted that the performance of HTTP proxying is usually lower than the +performance of AJP, so AJP clustering is often preferable.

    + +

    AJP

    + +

    When using a single server, the performance when using a native webserver in +front of the Tomcat instance is most of the time significantly worse than a +standalone Tomcat with its default HTTP connector, even if a large part of the web +application is made of static files. If integration with the native webserver is +needed for any reason, an AJP connector will provide faster performance than +proxied HTTP. AJP clustering is the most efficient from the Tomcat perspective. +It is otherwise functionally equivalent to HTTP clustering.

    + +

    The native connectors supported with this Tomcat release are:

    +
      +
    • JK 1.2.x with any of the supported servers
    • +
    • mod_proxy on Apache HTTP Server 2.x (included by default in Apache HTTP Server 2.2), +with AJP enabled
    • +
    + +

    Other native connectors supporting AJP may work, but are no longer supported.

    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/default-servlet.html b/tomcat/docs/default-servlet.html new file mode 100644 index 0000000..b35e48e --- /dev/null +++ b/tomcat/docs/default-servlet.html @@ -0,0 +1,306 @@ + +Apache Tomcat 8 (8.5.43) - Default Servlet Reference

    Default Servlet Reference

    Table of Contents

    What is the DefaultServlet

    +

    +The default servlet is the servlet which serves static resources as well +as serves the directory listings (if directory listings are enabled). +

    +

    Where is it declared?

    +

    +It is declared globally in $CATALINA_BASE/conf/web.xml. +By default here is it's declaration: +

    +
        <servlet>
    +        <servlet-name>default</servlet-name>
    +        <servlet-class>
    +          org.apache.catalina.servlets.DefaultServlet
    +        </servlet-class>
    +        <init-param>
    +            <param-name>debug</param-name>
    +            <param-value>0</param-value>
    +        </init-param>
    +        <init-param>
    +            <param-name>listings</param-name>
    +            <param-value>false</param-value>
    +        </init-param>
    +        <load-on-startup>1</load-on-startup>
    +    </servlet>
    +
    +...
    +
    +    <servlet-mapping>
    +        <servlet-name>default</servlet-name>
    +        <url-pattern>/</url-pattern>
    +    </servlet-mapping>
    + +So by default, the default servlet is loaded at webapp startup and +directory listings are disabled and debugging is turned off. +

    What can I change?

    +

    + The DefaultServlet allows the following initParamters: +

    + +
    + Property + + Description +
    debug + Debugging level. It is not very useful unless you are a tomcat + developer. As + of this writing, useful values are 0, 1, 11, 1000. [0] +
    listings + If no welcome file is present, can a directory listing be + shown? + value may be true or false [false] +
    + Welcome files are part of the servlet api. +
    + WARNING: Listings of directories containing many entries are + expensive. Multiple requests for large directory listings can consume + significant proportions of server resources. +
    precompressed + If a precompressed version of a file exists (a file with .br + or .gz appended to the file name located alongside the + original file), Tomcat will serve the precompressed file if the user + agent supports the matching content encoding (br or gzip) and this + option is enabled. [false] +
    + The precompressed file with the with .br or .gz + extension will be accessible if requested directly so if the original + resource is protected with a security constraint, the precompressed + versions must be similarly protected. +
    + It is also possible to configure the list of precompressed formats. + The syntax is comma separated list of + [content-encoding]=[file-extension] pairs. For example: + br=.br,gzip=.gz,bzip2=.bz2. If multiple formats are + specified, the client supports more than one and the client does not + express a preference, the order of the list of formats will be treated + as the server preference order and used to select the format returned. +
    readmeFile + If a directory listing is presented, a readme file may also + be presented with the listing. This file is inserted as is + so it may contain HTML. +
    globalXsltFile + If you wish to customize your directory listing, you + can use an XSL transformation. This value is a relative file name (to + either $CATALINA_BASE/conf/ or $CATALINA_HOME/conf/) which will be used + for all directory listings. This can be overridden per context and/or + per directory. See contextXsltFile and + localXsltFile below. The format of the xml is shown + below. +
    contextXsltFile + You may also customize your directory listing by context by + configuring contextXsltFile. This must be a context + relative path (e.g.: /path/to/context.xslt) to a file with + a .xsl or .xslt extension. This overrides + globalXsltFile. If this value is present but a file does + not exist, then globalXsltFile will be used. If + globalXsltFile does not exist, then the default + directory listing will be shown. +
    localXsltFile + You may also customize your directory listing by directory by + configuring localXsltFile. This must be a file in the + directory where the listing will take place to with a + .xsl or .xslt extension. This overrides + globalXsltFile and contextXsltFile. If this + value is present but a file does not exist, then + contextXsltFile will be used. If + contextXsltFile does not exist, then + globalXsltFile will be used. If + globalXsltFile does not exist, then the default + directory listing will be shown. +
    input + Input buffer size (in bytes) when reading + resources to be served. [2048] +
    output + Output buffer size (in bytes) when writing + resources to be served. [2048] +
    readonly + Is this context "read only", so HTTP commands like PUT and + DELETE are rejected? [true] +
    fileEncoding + File encoding to be used when reading static resources. + [platform default] +
    sendfileSize + If the connector used supports sendfile, this represents the minimal + file size in KB for which sendfile will be used. Use a negative value + to always disable sendfile. [48] +
    useAcceptRanges + If true, the Accept-Ranges header will be set when appropriate for the + response. [true] +
    showServerInfo + Should server information be presented in the response sent to clients + when directory listing is enabled. [true] +
    sortListings + Should the server sort the listings in a directory. [false] +
    sortDirectoriesFirst + Should the server list all directories before all files. [false] +
    +

    How do I customize directory listings?

    +

    You can override DefaultServlet with you own implementation and use that +in your web.xml declaration. If you +can understand what was just said, we will assume you can read the code +to DefaultServlet servlet and make the appropriate adjustments. (If not, +then that method isn't for you) +

    +

    +You can use either localXsltFile or +globalXsltFile and DefaultServlet will create +an xml document and run it through an xsl transformation based +on the values provided in localXsltFile and +globalXsltFile. localXsltFile is first +checked, followed by globalXsltFile, then default +behaviors takes place. +

    + +

    +Format: +

    +
        <listing>
    +     <entries>
    +      <entry type='file|dir' urlPath='aPath' size='###' date='gmt date'>
    +        fileName1
    +      </entry>
    +      <entry type='file|dir' urlPath='aPath' size='###' date='gmt date'>
    +        fileName2
    +      </entry>
    +      ...
    +     </entries>
    +     <readme></readme>
    +    </listing>
    +
      +
    • size will be missing if type='dir'
    • +
    • Readme is a CDATA entry
    • +
    + +

    + The following is a sample xsl file which mimics the default tomcat behavior: +

    +
    <?xml version="1.0" encoding="UTF-8"?>
    +
    +<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    +  version="3.0">
    +
    +  <xsl:output method="html" html-version="5.0"
    +    encoding="UTF-8" indent="no"
    +    doctype-system="about:legacy-compat"/>
    +
    +  <xsl:template match="listing">
    +   <html>
    +    <head>
    +      <title>
    +        Sample Directory Listing For
    +        <xsl:value-of select="@directory"/>
    +      </title>
    +      <style>
    +        h1 {color : white;background-color : #0086b2;}
    +        h3 {color : white;background-color : #0086b2;}
    +        body {font-family : sans-serif,Arial,Tahoma;
    +             color : black;background-color : white;}
    +        b {color : white;background-color : #0086b2;}
    +        a {color : black;} HR{color : #0086b2;}
    +        table td { padding: 5px; }
    +      </style>
    +    </head>
    +    <body>
    +      <h1>Sample Directory Listing For
    +            <xsl:value-of select="@directory"/>
    +      </h1>
    +      <hr style="height: 1px;" />
    +      <table style="width: 100%;">
    +        <tr>
    +          <th style="text-align: left;">Filename</th>
    +          <th style="text-align: center;">Size</th>
    +          <th style="text-align: right;">Last Modified</th>
    +        </tr>
    +        <xsl:apply-templates select="entries"/>
    +        </table>
    +      <xsl:apply-templates select="readme"/>
    +      <hr style="height: 1px;" />
    +      <h3>Apache Tomcat/<version-major-minor/></h3>
    +    </body>
    +   </html>
    +  </xsl:template>
    +
    +
    +  <xsl:template match="entries">
    +    <xsl:apply-templates select="entry"/>
    +  </xsl:template>
    +
    +  <xsl:template match="readme">
    +    <hr style="height: 1px;" />
    +    <pre><xsl:apply-templates/></pre>
    +  </xsl:template>
    +
    +  <xsl:template match="entry">
    +    <tr>
    +      <td style="text-align: left;">
    +        <xsl:variable name="urlPath" select="@urlPath"/>
    +        <a href="{$urlPath}">
    +          <pre><xsl:apply-templates/></pre>
    +        </a>
    +      </td>
    +      <td style="text-align: right;">
    +        <pre><xsl:value-of select="@size"/></pre>
    +      </td>
    +      <td style="text-align: right;">
    +        <pre><xsl:value-of select="@date"/></pre>
    +      </td>
    +    </tr>
    +  </xsl:template>
    +
    +</xsl:stylesheet>
    + +

    How do I secure directory listings?

    +Use web.xml in each individual webapp. See the security section of the +Servlet specification. + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/deployer-howto.html b/tomcat/docs/deployer-howto.html new file mode 100644 index 0000000..781160e --- /dev/null +++ b/tomcat/docs/deployer-howto.html @@ -0,0 +1,351 @@ + +Apache Tomcat 8 (8.5.43) - Tomcat Web Application Deployment

    Tomcat Web Application Deployment

    Table of Contents

    Introduction

    +

    + Deployment is the term used for the process of installing a web + application (either a 3rd party WAR or your own custom web application) + into the Tomcat server. +

    +

    + Web application deployment may be accomplished in a number of ways + within the Tomcat server. +

    +
      +
    • Statically; the web application is setup before Tomcat is started
    • +
    • + Dynamically; by directly manipulating already deployed web + applications (relying on auto-deployment + feature) or remotely by using the Tomcat Manager web + application +
    • +
    +

    + The Tomcat Manager is a web + application that can be used interactively (via HTML GUI) or + programmatically (via URL-based API) to deploy and manage web + applications. +

    +

    + There are a number of ways to perform deployment that rely on + the Manager web application. Apache Tomcat provides tasks + for Apache Ant build tool. + Apache Tomcat Maven Plugin + project provides integration with Apache Maven. + There is also a tool called the Client Deployer, which can be + used from a command line and provides additional functionality + such as compiling and validating web applications as well as + packaging web application into web application resource (WAR) + files. +

    +

    Installation

    +

    + There is no installation required for static deployment of web + applications as this is provided out of the box by Tomcat. Nor is any + installation required for deployment functions with the Tomcat Manager, + although some configuration is required as detailed in the + Tomcat Manager manual. + An installation is however required if you wish + to use the Tomcat Client Deployer (TCD). +

    +

    + The TCD is not packaged with the Tomcat core + distribution, and must therefore be downloaded separately from + the Downloads area. The download is usually labelled + apache-tomcat-8.5.x-deployer. +

    +

    + TCD has prerequisites of Apache Ant 1.6.2+ and a Java installation. + Your environment should define an ANT_HOME environment value pointing to + the root of your Ant installation, and a JAVA_HOME value pointing to + your Java installation. Additionally, you should ensure Ant's ant + command, and the Java javac compiler command run from the command shell + that your operating system provides. +

    +
      +
    1. Download the TCD distribution
    2. +
    3. + The TCD package need not be extracted into any existing Tomcat + installation, it can be extracted to any location. +
    4. +
    5. Read Using the + Tomcat Client Deployer
    6. +
    +

    A word on Contexts

    +

    + In talking about deployment of web applications, the concept of a + Context is required to be understood. A Context is what Tomcat + calls a web application. +

    +

    + In order to configure a Context within Tomcat a Context Descriptor + is required. A Context Descriptor is simply an XML file that contains + Tomcat related configuration for a Context, e.g naming resources or + session manager configuration. In earlier versions of + Tomcat the content of a Context Descriptor configuration was often stored within + Tomcat's primary configuration file server.xml but this is now + discouraged (although it currently still works). +

    +

    + Context Descriptors not only help Tomcat to know how to configure + Contexts but other tools such as the Tomcat Manager and TCD often use + these Context Descriptors to perform their roles properly. +

    +

    + The locations for Context Descriptors are: +

    +
      +
    1. $CATALINA_BASE/conf/[enginename]/[hostname]/[webappname].xml
    2. +
    3. $CATALINA_BASE/webapps/[webappname]/META-INF/context.xml
    4. +
    +

    + Files in (1) are named [webappname].xml but files in (2) are named + context.xml. If a Context Descriptor is not provided for a Context, + Tomcat configures the Context using default values. +

    +

    Deployment on Tomcat startup

    +

    + If you are not interested in using the Tomcat Manager, or TCD, + then you'll need to deploy your web applications + statically to Tomcat, followed by a Tomcat startup. The location you + deploy web applications to for this type of deployment is called the + appBase which is specified per Host. You either copy a + so-called exploded web application, i.e non-compressed, to this + location, or a compressed web application resource .WAR file. +

    +

    + The web applications present in the location specified by the Host's + (default Host is "localhost") appBase attribute (default + appBase is "$CATALINA_BASE/webapps") will be deployed on Tomcat startup + only if the Host's deployOnStartup attribute is "true". +

    +

    + The following deployment sequence will occur on Tomcat startup in that + case: +

    +
      +
    1. Any Context Descriptors will be deployed first.
    2. +
    3. + Exploded web applications not referenced by any Context + Descriptor will then be deployed. If they have an associated + .WAR file in the appBase and it is newer than the exploded web application, + the exploded directory will be removed and the webapp will be + redeployed from the .WAR +
    4. +
    5. .WAR files will be deployed
    6. +
    +

    Deploying on a running Tomcat server

    +

    + It is possible to deploy web applications to a running Tomcat server. +

    +

    + If the Host autoDeploy attribute is "true", the Host will + attempt to deploy and update web applications dynamically, as needed, + for example if a new .WAR is dropped into the appBase. + For this to work, the Host needs to have background processing + enabled which is the default configuration. +

    + +

    + autoDeploy set to "true" and a running Tomcat allows for: +

    +
      +
    • Deployment of .WAR files copied into the Host appBase.
    • +
    • + Deployment of exploded web applications which are + copied into the Host appBase. +
    • +
    • + Re-deployment of a web application which has already been deployed from + a .WAR when the new .WAR is provided. In this case the exploded + web application is removed, and the .WAR is expanded again. + Note that the explosion will not occur if the Host is configured + so that .WARs are not exploded with a unpackWARs + attribute set to "false", in which case the web application + will be simply redeployed as a compressed archive. +
    • +
    • + Re-loading of a web application if the /WEB-INF/web.xml file (or + any other resource defined as a WatchedResource) is updated. +
    • +
    • + Re-deployment of a web application if the Context Descriptor + file from which the web application has been deployed is + updated. +
    • +
    • + Re-deployment of dependent web applications if the global or + per-host Context Descriptor file used by the web application is + updated. +
    • +
    • + Re-deployment of a web application if a Context Descriptor file (with a + filename corresponding to the Context path of the previously deployed + web application) is added to the + $CATALINA_BASE/conf/[enginename]/[hostname]/ + directory. +
    • +
    • + Undeployment of a web application if its document base (docBase) + is deleted. Note that on Windows, this assumes that anti-locking + features (see Context configuration) are enabled, otherwise it is not + possible to delete the resources of a running web application. +
    • +
    +

    + Note that web application reloading can also be configured in the loader, in which + case loaded classes will be tracked for changes. +

    +

    Deploying using the Tomcat Manager

    +

    + The Tomcat Manager is covered in its own manual page. +

    +

    Deploying using the Client Deployer Package

    +

    + Finally, deployment of web application may be achieved using the + Tomcat Client Deployer. This is a package which can be used to + validate, compile, compress to .WAR, and deploy web applications to + production or development Tomcat servers. It should be noted that this feature + uses the Tomcat Manager and as such the target Tomcat server should be + running. +

    + +

    + It is assumed the user will be familiar with Apache Ant for using the TCD. + Apache Ant is a scripted build tool. The TCD comes pre-packaged with a + build script to use. Only a modest understanding of Apache Ant is + required (installation as listed earlier in this page, and familiarity + with using the operating system command shell and configuring + environment variables). +

    + +

    + The TCD includes Ant tasks, the Jasper page compiler for JSP compilation + before deployment, as well as a task which + validates the web application Context Descriptor. The validator task (class + org.apache.catalina.ant.ValidatorTask) allows only one parameter: + the base path of an exploded web application. +

    + +

    + The TCD uses an exploded web application as input (see the list of the + properties used below). A web application that is programmatically + deployed with the deployer may include a Context Descriptor in + /META-INF/context.xml. +

    + +

    + The TCD includes a ready-to-use Ant script, with the following targets: +

    +
      +
    • + compile (default): Compile and validate the web + application. This can be used standalone, and does not need a running + Tomcat server. The compiled application will only run on the associated + Tomcat X.Y.Z server release, and is not guaranteed to work + on another Tomcat release, as the code generated by Jasper depends on its runtime + component. It should also be noted that this target will also compile + automatically any Java source file located in the + /WEB-INF/classes folder of the web application.
    • +
    • + deploy: Deploy a web application (compiled or not) to + a Tomcat server. +
    • +
    • undeploy: Undeploy a web application
    • +
    • start: Start web application
    • +
    • reload: Reload web application
    • +
    • stop: Stop web application
    • +
    + +

    + In order for the deployment to be configured, create a file + called deployer.properties in the TCD installation + directory root. In this file, add the following name=value pairs per + line: +

    + +

    + Additionally, you will need to ensure that a user has been + setup for the target Tomcat Manager (which TCD uses) otherwise the TCD + will not authenticate with the Tomcat Manager and the deployment will + fail. To do this, see the Tomcat Manager page. +

    + +
      +
    • + build: The build folder used will be, by default, + ${build}/webapp/${path} (${build}, by + default, points to ${basedir}/build). After the end + of the execution of the compile target, the web + application .WAR will be located at + ${build}/webapp/${path}.war. +
    • +
    • + webapp: The directory containing the exploded web application + which will be compiled and validated. By default, the folder is + myapp. +
    • +
    • + path: Deployed context path of the web application, + by default /myapp. +
    • +
    • + url: Absolute URL to the Tomcat Manager web application of a + running Tomcat server, which will be used to deploy and undeploy the + web application. By default, the deployer will attempt to access + a Tomcat instance running on localhost, at + http://localhost:8080/manager/text. +
    • +
    • + username: Tomcat Manager username (user should have a role of + manager-script) +
    • +
    • password: Tomcat Manager password.
    • +
    +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/developers.html b/tomcat/docs/developers.html new file mode 100644 index 0000000..974cc03 --- /dev/null +++ b/tomcat/docs/developers.html @@ -0,0 +1,89 @@ + +Apache Tomcat 8 (8.5.43) - Tomcat Developers

    Tomcat Developers

    Active Developers

    + +

    + The list indicates the developers' main areas of interest. Feel free to + add to the list :) The developers email addresses are + [login]@apache.org. Please do not contact + developers directly for any support issues (please post to the + tomcat-users mailing list instead, or one of the other support + resources; some organizations and individual consultants also offer + for pay Tomcat support, as listed on the + support and + training page on the Tomcat Wiki). +

    + +
      +
    • Bill Barker (billbarker): Connectors
    • +
    • Costin Manolache (costin): Catalina, Connectors
    • +
    • Filip Hanik (fhanik): Clustering, Release Manager
    • +
    • Jean-Frederic Clere (jfclere): Connectors
    • +
    • Jim Jagielski (jim): Connectors
    • +
    • Konstantin Kolinko (kkolinko): Catalina
    • +
    • Mark Thomas (markt): CGI, SSI, WebDAV, bug fixing
    • +
    • Mladen Turk (mturk): Connectors
    • +
    • Peter Rossbach (pero): Catalina, Clustering, JMX
    • +
    • Rainer Jung (rjung): Catalina, Clustering, Connectors
    • +
    • Remy Maucherat (remm): Catalina, Connectors, Docs
    • +
    • Tim Funk (funkman): Catalina, Docs
    • +
    • Tim Whittington (timw): Connectors
    • +
    + +

    Retired Developers

    + +
      +
    • Amy Roh (amyroh): Catalina
    • +
    • Glenn Nielsen (glenn): Catalina, Connectors
    • +
    • Henri Gomez (hgomez): Connectors
    • +
    • Jan Luehe (luehe): Jasper
    • +
    • Jean-Francois Arcand (jfarcand): Catalina
    • +
    • Kin-Man Chung (kinman): Jasper
    • +
    • Yoav Shapira (yoavs): Docs, JMX, Catalina, balancer
    • +
    +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/elapi/index.html b/tomcat/docs/elapi/index.html new file mode 100644 index 0000000..695de9d --- /dev/null +++ b/tomcat/docs/elapi/index.html @@ -0,0 +1,34 @@ + + + + + + API docs + + + + +The EL Javadoc is not installed by default. Download and install +the "fulldocs" package to get it. + +You can also access the javadoc online in the Tomcat + +documentation bundle. + + + diff --git a/tomcat/docs/extras.html b/tomcat/docs/extras.html new file mode 100644 index 0000000..38e9065 --- /dev/null +++ b/tomcat/docs/extras.html @@ -0,0 +1,128 @@ + +Apache Tomcat 8 (8.5.43) - Additional Components

    Additional Components

    Table of Contents

    Introduction

    +

    + A number of additional components may be used with Apache Tomcat. These + components may be built by users should they need them or they can be + downloaded from one of the mirrors. +

    + +

    Downloading

    +

    + To download the extras components open the + Tomcat download page + and select "Browse" from the Quick Navigation Links. The extras components + can be found in bin/extras. +

    +

    Building

    + +

    + The additional components are built using the extras target + of the standard Tomcat Ant script which is present in the source bundle of + Tomcat. +

    + +

    The build process is the following:

    + +
      +
    • Follow the build instructions to build a + Tomcat binary from the source bundle (note: it will be used by the build + process of the additional components, but does not need to be actually + used later on)
    • +
    • Execute the command ant extras to run the build + script
    • +
    • The additional components JARs will be placed in the + output/extras folder
    • +
    • Refer to the documentation below about the usage of these JARs
    • +
    + +

    Components list

    + +

    Full commons-logging implementation

    + +

    + Tomcat uses a package renamed commons-logging API implementation which is + hardcoded to use the java.util.logging API. The commons-logging additional + component builds a full fledged package renamed commons-logging + implementation which can be used to replace the implementation provided with + Tomcat. See the logging page for usage + instructions. +

    + +
    + +

    Web Services support (JSR 109)

    + +

    + Tomcat provides factories for JSR 109 which may be used to resolve web + services references. Place the generated catalina-ws.jar as well as + jaxrpc.jar and wsdl4j.jar (or another implementation of JSR 109) in the + Tomcat lib folder. +

    + +

    + Users should be aware that wsdl4j.jar is licensed under CPL 1.0 and not the + Apache License version 2.0. +

    + +
    + +

    JMX Remote Lifecycle Listener

    + +

    + The JMX protocol requires the JMX server (Tomcat in this instance) to listen + on two network ports. One of these ports can be fixed via configuration but + the second is selected randomly. This makes it difficult to use JMX through + a firewall. The JMX Remote Lifecycle Listener allows both ports to be fixed, + simplifying the process of connecting to JMX through a firewall. See the listeners page for usage instructions. +

    + +
    +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/funcspecs/fs-admin-apps.html b/tomcat/docs/funcspecs/fs-admin-apps.html new file mode 100644 index 0000000..16e86c5 --- /dev/null +++ b/tomcat/docs/funcspecs/fs-admin-apps.html @@ -0,0 +1,299 @@ + +Catalina Functional Specifications (8.5.43) - Administrative Apps - Overall Requirements

    Administrative Apps - Overall Requirements

    Table of Contents

    Overview

    + + +

    Introduction

    + +

    The purpose of this specification is to define high level requirements + for administrative applications that can be used to manage the operation + of a running Tomcat container. A variety of Access Methods + to the supported administrative functionality shall be supported, to + meet varying requirements:

    +
      +
    • As A Scriptable Web Application - The existing + Manager web application provides a simple HTTP-based + interface for managing Tomcat through commands that are expressed + entirely through a request URI. This is useful in environments + where you wish to script administrative commands with tools that + can generate HTTP transactions.
    • +
    • As An HTML-Based Web Application - Use an HTML presentation + to provide a GUI-like user interface for humans to interact with the + administrative capabilities.
    • +
    • As SOAP-Based Web Services - The operational commands to + administer Tomcat are made available as web services that utilize + SOAP message formats.
    • +
    • As Java Management Extensions (JMX) Commands - The operational + commands to administer Tomcat are made available through JMX APIs, + for integration into management consoles that utilize them.
    • +
    • Other Remote Access APIs - Other remote access APIs, such + as JINI, RMI, and CORBA can also be utilized to access administrative + capabilities.
    • +
    + +

    Underlying all of the access methods described above, it is assumed + that the actual operations are performed either directly on the + corresponding Catalina components (such as calling the + Deployer.deploy() method to deploy a new web application), + or through a "business logic" layer that can be shared across all of the + access methods. This approach minimizes the cost of adding new + administrative capabilities later -- it is only necessary to add the + corresponding business logic function, and then write adapters to it for + all desired access methods.

    + +

    The current status of this functional specification is + PROPOSED. It has not yet been discussed and + agreed to on the TOMCAT-DEV mailing list.

    + +
    + + +

    External Specifications

    + +

    The implementation of this functionality depends on the following + external specifications:

    + + +
    + + +

    Implementation Requirements

    + +

    The implementation of this functionality shall conform to the + following requirements:

    +
      +
    • To the maximum extent feasible, all administrative functions, + and the access methods that support them, shall run portably + on all platforms where Tomcat itself runs.
    • +
    • In a default Tomcat distribution, all administrative capabilities + shall be disabled. It shall be necessary for a system + administrator to specifically enable the desired access methods + (such as by adding a username/password with a specific role to + the Tomcat user's database.
    • +
    • Administrative functions shall be realized as direct calls to + corresponding Catalina APIs, or through a business logic layer + that is independent of the access method used to initiate it.
    • +
    • The common business logic components shall be implemented in + package org.apache.catalina.admin.
    • +
    • The common business logic components shall be built as part of the + standard Catalina build process, and made visible in the + Catalina class loader.
    • +
    • The Java components required for each access method shall be + implemented in subpackages of org.apache.catalina.admin. +
    • +
    • The build scripts should treat each access method as optional, + so that it will be built only if the corresponding required + APIs are present at build time.
    • +
    • It shall be possible to save the configured state of the running + Tomcat container such that this state can be reproduced when the + container is shut down and restarted.
    • +
    • Administrative commands to start up and shut down the overall + Tomcat container are out of scope for the + purposes of these applications. It is assumed that other + (usually platform-specific) mechanisms will be used for container + startup and shutdown.
    • +
    + +
    + + +

    Dependencies

    + + +

    Environmental Dependencies

    + +

    The following environmental dependencies must be met in order for + administrative applications to operate correctly:

    +
      +
    • For access methods that require creation of server sockets, the + appropriate ports must be configured and available.
    • +
    + +
    + + +

    Container Dependencies

    + +

    Correct operation of administrative applications depends on the + following specific features of the surrounding container:

    +
      +
    • To the maximum extent feasible, Catalina components that offer + direct administrative APIs and property setters shall support + "live" changes to their operation, without requiring a container + restart.
    • +
    + +
    + + +

    External Technologies

    + +

    The availability of the following technologies can be assumed + for the implementation and operation of the various access methods + and the corresponding administrative business logic:
    + FIXME - This list below is totally outdated, but nobody + cares about the administrative app anymore. It is removed and unsupported + since Tomcat 6.0.

    + + +
    + + +

    Functionality

    + + +

    Properties of Administered Objects

    + +

    Functional requirements for administrative applications are specified + in terms of Administered Objects, whose definitions and detailed + properties are listed here. In general, + Administered Objects correspond to components in the Catalina architecture, + but these objects are defined separately here for the following reasons:

    +
      +
    • It is possible that the administrative applications do not expose + every possible configurable facet of the underlying components.
    • +
    • In some cases, an Administered Object (from the perspective of an + administrative operation) is realized by more than one Catalina + component, at a finer-grained level of detail.
    • +
    • It is necessary to represent the configuration information for a + component separately from the component itself (for instance, in + order to store that configuration information for later use).
    • +
    • It is necessary to represent configuration information (such as + a Default Context) when there is no corresponding component instance. +
    • +
    • Administered Objects, when realized as Java classes, will include + methods for administrative operations that have no correspondence + to operations performed by the corresponding actual components.
    • +
    + +

    It is assumed that the reader is familiar with the overall component + architecture of Catalina. For further information, see the corresponding + Developer Documentation. To distinguish names that are used as both + Administered Objects and Components, different + font presentations are utilized. Default values for many properties + are listed in [square brackets].

    + +
    + + +

    Supported Administrative Operations

    + +

    The administrative operations that are available are described in terms + of the corresponding Administered Objects (as defined above), in a manner + that is independent of the access method by which these operations are + requested. In general, such operations are relevant only in the context + of a particular Administered Object (and will most likely be realized as + method calls on the corresponding Administered Object classes), so they + are organized based on the currently "focused" administered object. + The available Supported Operations are documented + here.

    + +
    + + +

    Access Method Specific Requirements

    + +
    Scriptable Web Application
    + +

    An appropriate subset of the administrative operations described above + shall be implemented as commands that can be performed by the "Manager" + web application. FIXME - Enumerate them.

    + +

    In addition, this web application shall conform to the following + requirements:

    +
      +
    • All request URIs shall be protected by security constraints that + require a security role to be assigned for processing.
    • +
    • The default user database shall not contain any + user that has been assigned a security role.
    • +
    + +
    HTML-Based Web Application
    + +

    The entire suite of administrative operations described above shall be + made available through a web application designed for human interaction. + In addition, this web application shall conform to the following + requirements:

    +
      +
    • Must be implemented using servlet, JSP, and MVC framework technologies + described under "External Technologies", above.
    • +
    • Prompts and error messages must be internationalizable to multiple + languages.
    • +
    • Rendered HTML must be compatible with Netscape Navigator (version 4.7 + or later) and Internet Explorer (version 5.0 or later).
    • +
    + +
    + + +

    Testable Assertions

    + +

    FIXME - Complete this section.

    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/funcspecs/fs-admin-objects.html b/tomcat/docs/funcspecs/fs-admin-objects.html new file mode 100644 index 0000000..fde724a --- /dev/null +++ b/tomcat/docs/funcspecs/fs-admin-objects.html @@ -0,0 +1,450 @@ + +Catalina Functional Specifications (8.5.43) - Administrative Apps - Administered Objects

    Administrative Apps - Administered Objects

    Table of Contents

    Administered Objects Overview

    + +

    This document defines the Administered Objects that represent +the internal architectural components of the Catalina servlet container. +Associated with each is a set of Supported +Operations that can be performed when the administrative application is +"focused" on a particular configurable object.

    + +

    The following Administered Objects are defined:

    + + +

    Access Logger

    + +

    An Access Logger is an optional Valve that can + create request access logs in the same formats as those provided by + web servers. Such access logs are useful input to hit count and user + access tracking analysis programs. An Access Logger can be attached to + an Engine, a Host, a Context, or a Default + Context.

    + +

    The standard component implementing an Access Logger is + org.apache.catalina.valves.AccessLogValve. It supports the + following configurable properties:

    +
      +
    • debug - Debugging detail level. [0]
    • +
    • directory - Absolute or relative (to $CATALINA_BASE) path + of the directory into which access log files are created. + [logs].
    • +
    • pattern - Pattern string defining the fields to be + included in the access log output, or "common" for the standard + access log pattern. See + org.apache.catalina.valves.AccessLogValve for more + information. [common]
    • +
    • prefix - Prefix added to the beginning of each log file + name created by this access logger.
    • +
    • resolveHosts - Should IP addresses be resolved to host + names in the log? [false]
    • +
    • suffix - Suffix added to the end of each log file name + created by this access logger.
    • +
    + +

    Connector

    + +

    A Connector is the representation of a communications endpoint + by which requests are received from (and responses returned to) a Tomcat + client. The administrative applications shall support those connectors + that are commonly utilized in Tomcat installations, as described in detail + below.

    + +

    For standalone use, the standard connector supporting the HTTP/1.1 + protocol is org.apache.catalina.connectors.http.HttpConnector. + It supports the following configurable properties:

    +
      +
    • acceptCount - The maximum queue length of incoming + connections that have not yet been accepted. [10]
    • +
    • address - For servers with more than one IP address, the + address upon which this connector should listen. [All Addresses]
    • +
    • bufferSize - Default input buffer size (in bytes) for + requests created by this Connector. [2048]
    • +
    • debug - Debugging detail level. [0]
    • +
    • enableLookups - Should we perform DNS lookups on remote + IP addresses when request.getRemoteHost() is called? + [false]
    • +
    • maxProcessors - The maximum number of processor threads + supported by this connector. [20]
    • +
    • minProcessors - The minimum number of processor threads + to be created at container startup. [5]
    • +
    • port - TCP/IP port number on which this Connector should + listen for incoming requests. [8080]
    • +
    • proxyName - Host name to be returned when an application + calls request.getServerName(). [Value of Host: header]
    • +
    • proxyPort - Port number to be returned when an application + calls request.getServerPort(). [Same as port] +
    • +
    + +

    Context

    + +

    A Context is the representation of an individual web application, + which is associated with a corresponding Host. Note that the + administrable properties of a Context do not + include any settings from inside the web application deployment descriptor + for that application.

    + +

    The standard component implementing a Context is + org.apache.catalina.core.StandardContext. It supports the + following configurable properties:

    +
      +
    • cookies - Should be use cookies for session identifier + communication? [true]
    • +
    • crossContext - Should calls to + ServletContext.getServletContext() return the actual + context responsible for the specified path? [false]
    • +
    • debug - Debugging detail level. [0]
    • +
    • docBase - The absolute or relative (to the + appBase of our owning Host) pathname of a + directory containing an unpacked web application, or of a web + application archive (WAR) file.
    • +
    • override - Should settings in this Context + override corresponding settings in the Default Context? + [false]
    • +
    • path - Context path for this web application, or an empty + string for the root application of a Host. [Inferred from + directory or WAR file name]
    • +
    • reloadable - Should Tomcat monitor classes in the + /WEB-INF/classes directory for changes, and reload the + application if they occur? [false]
    • +
    • useNaming - Should Tomcat provide a JNDI naming context, + containing preconfigured entries and resources, corresponding to the + requirements of the Java2 Enterprise Edition specification? [true]
    • +
    • workDir - Absolute pathname of a scratch directory that is + provided to this web application. [Automatically assigned relative to + $CATALINA_BASE/work]
    • +
    + +

    Each Context is owned by a parent Host, and is + associated with:

    +
      +
    • An optional Access Logger that logs all requests processed + by this web application.
    • +
    • Zero or more Environment Entries representing environment + entries for the JNDI naming context associated with a web + application.
    • +
    • Zero or more JDBC Resources representing database connection + pools associated with a web application.
    • +
    • A Loader representing the web application class loader used + by this web application.
    • +
    • A Manager representing the session manager used by this + web application.
    • +
    • An optional Realm used to provide authentication and access + control information for this web application.
    • +
    • Zero or more Request Filters used to limit access to this + web application based on remote host name or IP address.
    • +
    + +

    Default Context

    + +

    A Default Context represents a subset of the configurable + properties of a Context, and is used to set defaults for those + properties when web applications are automatically deployed. A Default + Context object can be associated with an Engine or a + Host. The following configurable properties are supported:

    +
      +
    • cookies - Should be use cookies for session identifier + communication? [true]
    • +
    • crossContext - Should calls to + ServletContext.getServletContext() return the actual + context responsible for the specified path? [false]
    • +
    • reloadable - Should Tomcat monitor classes in the + /WEB-INF/classes directory for changes, and reload the + application if they occur? [false]
    • +
    • useNaming - Should Tomcat provide a JNDI naming context, + containing preconfigured entries and resources, corresponding to the + requirements of the Java2 Enterprise Edition specification? [true]
    • +
    + +

    Each Default Context is owned by a parent Engine or + Host, and is associated with:

    +
      +
    • Zero or more Environment Entries representing environment + entries for the JNDI naming context associated with a web + application.
    • +
    • Zero or more JDBC Resources representing database connection + pools associated with a web application.
    • +
    • An optional Loader representing default configuration + properties for the Loader component of deployed web applications.
    • +
    • An optional Manager representing default configuration + properties for the Manager component of deployed web applications.
    • +
    + +

    Default Deployment Descriptor

    + +

    Default web application characteristics are configured in a special + deployment descriptor named $CATALINA_BASE/conf/web.xml. This + section describes the configurable components that may be stored there.

    + +

    FIXME - Complete the description of default servlets, + default mappings, default MIME types, and so on.

    + +

    Engine

    + +

    An Engine is the representation of the entire Catalina + servlet container, and processes all requests for all of the associated + virtual hosts and web applications.

    + +

    The standard component implementing an Engine is + org.apache.catalina.core.StandardEngine. It supports the + following configurable properties:

    +
      +
    • debug - Debugging detail level. [0]
    • +
    • defaultHost - Name of the Host to which requests + will be directed if the requested host is unknown. [localhost]
    • +
    • name - Logical name of this engine. [Tomcat Stand-Alone] +
    • +
    + +

    Each Engine is owned by a parent Service, and is + associated with:

    +
      +
    • An optional Access Logger that logs all requests processed + by the entire container.
    • +
    • A Default Context, representing default properties of a + Context for automatically deployed applications for all + associated Hosts (unless overridden by a subordinate + component).
    • +
    • One or more Hosts representing individual virtual hosts + supported by this container.
    • +
    • A Realm used to provide authentication and access control + information for all virtual hosts and web applications (unless + overridden by a subordinate component).
    • +
    • Zero or more Request Filters used to limit access to the + entire container based on remote host name or IP address.
    • +
    + +

    Environment Entry

    + +

    An Environment Entry is the representation of a + <env-entry> element from a web application deployment + descriptor. It will cause the creation of a corresponding entry in the + JNDI naming context provided to the corresponding Context. The + following configurable properties are supported:

    +
      +
    • description - Description of this environment entry.
    • +
    • name - Environment entry name (relative to the + java:comp/env context)
    • +
    • type - Environment entry type (must be one of the fully + qualified Java classes listed in the servlet spec).
    • +
    • value - Environment entry value (must be convertible from + String to the specified type.
    • +
    + +

    Host

    + +

    A Host is the representation of an individual virtual host, + which has a unique set of associated web applications.

    + +

    The standard component implementing a Host is + org.apache.catalina.core.StandardHost. It supports the + following configurable properties:

    +
      +
    • aliases - Zero or more DNS names that are also associated + with this host (for example, a particular host might be named + www.mycompany.com with an alias company.com). +
    • +
    • appBase - Absolute or relative (to $CATALINA_BASE) path + to a directory from which web applications will be automatically + deployed.
    • +
    • debug - Debugging detail level. [0]
    • +
    • name - DNS Name of the virtual host represented by this + object.
    • +
    • unpackWARs - Should web application archive files + deployed by this virtual host be unpacked first? [true]
    • +
    + +

    Each Host is owned by a parent Engine, and is + associated with:

    +
      +
    • An optional Access Logger that logs all requests processed + by this virtual host.
    • +
    • One or more Contexts representing the web applications + operating on this Host.
    • +
    • A Default Context representing default Context + properties for web applications that are automatically deployed + by this Host.
    • +
    • A optional Realm used to provide authentication and access + control information for all web applications associated with this + virtual host (unless overridden by a subordinate component).
    • +
    + +

    FIXME - Should we support configuration of the + User Web Applications functionality?

    + +

    JDBC Resource

    + +

    A JDBC Resources represents a database connection pool (i.e. + an implementation of javax.sql.DataSource that will be + configured and made available in the JNDI naming context associated with + a web application.

    + +

    FIXME - properties of this administered object

    + +

    Loader

    + +

    A Loader represents a web application class loader that will + be utilized to provide class loading services for a particular + Context.

    + +

    The standard component implementing a Loader is + org.apache.catalina.loader.WebappLoader. It supports + the following configurable properties:

    +
      +
    • reloadable - Should this class loader check for modified + classes and initiate automatic reloads? [Set automatically from the + reloadable property of the corresponding Context] +
    • +
    + +

    Each Loader is owned by a parent Context.

    + +

    Manager

    + +

    A Manager represents a session manager that will be associated + with a particular web application. FIXME - Add support + for advanced session managers and their associated Stores.

    + +

    The standard component implementing a Manager is + org.apache.catalina.session.StandardManager. It supports + the following configurable properties:

    +
      +
    • maxActiveSessions - The maximum number of active sessions + that are allowed, or -1 for no limit. [-1]
    • +
    + +

    Each Manager is owned by a parent Context.

    + +

    Realm

    + +

    A Realm represents a "database" of information about authorized + users, their passwords, and the security roles assigned to them. This will + be used by the container in the implementation of container-managed security + in accordance with the Servlet Specification. Several alternative + implementations are supported.

    + +

    org.apache.catalina.realm.MemoryRealm initializes its user + information from a simple XML file at startup time. If changes are made + to the information in this file, the corresponding web applications using + it must be restarted for the changes to take effect. It supports the + following configurable properties:

    +
      +
    • debug - Debugging detail level. [0]
    • +
    • pathname - Absolute or relative (to $CATALINA_BASE) path to + the XML file containing our user information. [conf/tomcat-users.xml] +
    • +
    + +

    org.apache.catalina.realm.JDBCRealm uses a relational + database (accessed via JDBC APIs) to contain the user information. Changes + in the contents of this database take effect immediately; however, the roles + assigned to a particular user are calculated only when the user initially + logs on (and not per request). The following configurable properties + are supported:

    +
      +
    • connectionName - Database username to use when establishing + a JDBC connection.
    • +
    • connectionPassword - Database password to use when + establishing a JDBC connection.
    • +
    • connectionURL - Connection URL to use when establishing + a JDBC connection.
    • +
    • driverName - Fully qualified Java class name of the JDBC + driver to be utilized.
    • +
    • roleNameCol - Name of the column, in the User Roles table, + which contains the role name.
    • +
    • userCredCol - Name of the column, in the Users table, + which contains the password (encrypted or unencrypted).
    • +
    • userNameCol - Name of the column, in both the Users and + User Roles tables, that contains the username.
    • +
    • userRoleTable - Name of the User Roles table, which contains + one row per security role assigned to a particular user. This table must + contain the columns specified by the userNameCol and + roleNameCol properties.
    • +
    • userTable - Name of the Users table, which contains one row + per authorized user. This table must contain the columns specified by + the userNameCol and userCredCol properties. +
    • +
    + +

    FIXME - Should we provide mechanisms to edit the contents + of a "tomcat-users.xml" file through the admin applications?

    + +

    Each Realm is owned by a parent Engine, Host, + or Context.

    + +

    Request Filter

    + +

    FIXME - complete this entry

    + +

    Server

    + +

    FIXME - complete this entry

    + +

    Service

    + +

    FIXME - complete this entry

    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/funcspecs/fs-admin-opers.html b/tomcat/docs/funcspecs/fs-admin-opers.html new file mode 100644 index 0000000..90c212a --- /dev/null +++ b/tomcat/docs/funcspecs/fs-admin-opers.html @@ -0,0 +1,309 @@ + +Catalina Functional Specifications (8.5.43) - Administrative Apps - Supported Operations

    Administrative Apps - Supported Operations

    Table of Contents

    Supported Operations Overview

    + +

    This document defines the Supported Operations that may +be performed against the Administered +Objects that are supported by Tomcat administrative applications. +Not all operations are required to be available through every administrative +application that is implemented. However, if a given operation is available, +it should operate consistently with the descriptions found here.

    + +

    Supported Operations are described for the following Administered +Objects:

    + + +

    Access Logger

    + +

    From the perspective of a particular Access Logger, it shall + be possible to perform the following administrative operations:

    +
      +
    • Navigate to the owning Engine, Host, or + Context.
    • +
    • Edit the configurable properties of this object.
    • +
    + +

    Connector

    + +

    From the perspective of a particular Connector, it shall be + possible to perform the following administrative operations:

    +
      +
    • Navigate to the owning Service.
    • +
    • Edit the configurable properties of this object.
    • +
    + +

    Context

    + +

    From the perspective of a particular Context, it shall be + possible to perform the following administrative operations:

    +
      +
    • Navigate to the owning Host.
    • +
    • Edit the configurable properties of this object.
    • +
    • Create and configure a new Access Logger associated + with this object.
    • +
    • Edit the configurable properties of the associated Access + Logger.
    • +
    • Remove the associated Access Logger.
    • +
    • Create and configure a new Environment Entry associated + with this object.
    • +
    • Select and edit the configurable properties of an associated + Environment Entry.
    • +
    • Remove an associated Environment Entry.
    • +
    • Create and configure a new JDBC Resource associated + with this object.
    • +
    • Select and edit the configurable properties of an associated + JDBC Resource.
    • +
    • Remove an associated JDBC Resource.
    • +
    • Create and configure a new Loader associated with + this object.
    • +
    • Edit the configurable properties of the associated Loader.
    • +
    • Remove the associated Loader.
    • +
    • Create and configure a new Manager associated with + this object.
    • +
    • Edit the configurable properties of the associated Manager.
    • +
    • Remove the associated Manager.
    • +
    • Create and configure a new Realm associated with + this object.
    • +
    • Edit the configurable properties of the associated Realm.
    • +
    • Remove the associated Realm.
    • +
    • Create and configure a new Request Filter associated with + this object.
    • +
    • Select and edit the configurable properties of an + associated Request Filter
    • +
    • Remove an associated Request Filter.
    • +
    + +

    Default Context

    + +

    From the perspective of a particular Default Context, it shall + be possible to perform the following administrative operations:

    +
      +
    • Navigate to the owning Engine or Host.
    • +
    • Edit the configurable properties of this object.
    • +
    • Create and configure a new Environment Entry associated + with this object.
    • +
    • Select and edit the configurable properties of an associated + Environment Entry.
    • +
    • Remove an associated Environment Entry.
    • +
    • Create and configure a new JDBC Resource associated + with this object.
    • +
    • Select and edit the configurable properties of an associated + JDBC Resource.
    • +
    • Remove an associated JDBC Resource.
    • +
    + +

    Engine

    + +

    From the perspective of a particular Engine, it shall be + possible to perform the following administrative operations:

    +
      +
    • Navigate to the owning Service.
    • +
    • Edit the configurable properties of this object.
    • +
    • Create and configure a new Access Logger associated + with this object.
    • +
    • Edit the configurable properties of the associated Access + Logger.
    • +
    • Remove the associated Access Logger.
    • +
    • Create and configure a new Default Context associated + with this object.
    • +
    • Edit the configurable properties of the associated Default + Context.
    • +
    • Remove the associated Default Context.
    • +
    • Create and configure a new Host associated with + this object.
    • +
    • Select and edit the configurable properties of an + associated Host.
    • +
    • Remove an associated Host.
    • +
    • Create and configure a new Realm associated with + this object.
    • +
    • Edit the configurable properties of the associated Realm.
    • +
    • Remove the associated Realm.
    • +
    • Create and configure a new Request Filter associated with + this object.
    • +
    • Select and edit the configurable properties of an + associated Request Filter
    • +
    • Remove an associated Request Filter.
    • +
    + +

    Environment Entry

    + +

    From the perspective of a particular Environment Entry, it shall + be possible to perform the following administrative operations:

    +
      +
    • Navigate to the owning Context or Default Context.
    • +
    • Edit the configurable properties of this object.
    • +
    + +

    Host

    + +

    From the perspective of a particular Host, it shall be + possible to perform the following administrative operations:

    +
      +
    • Navigate to the owning Engine.
    • +
    • Edit the configurable properties of this object.
    • +
    • Create and configure a new Access Logger associated + with this object.
    • +
    • Edit the configurable properties of the associated Access + Logger.
    • +
    • Remove the associated Access Logger.
    • +
    • Create and configure a new Context associated with + this object.
    • +
    • Select and edit the configurable properties of an associated + Context.
    • +
    • Remove an associated Context.
    • +
    • Create and configure a new Default Context associated + with this object.
    • +
    • Edit the configurable properties of the associated Default + Context.
    • +
    • Remove the associated Default Context.
    • +
    • Create and configure a new Realm associated with + this object.
    • +
    • Edit the configurable properties of the associated Realm.
    • +
    • Remove the associated Realm.
    • +
    • Create and configure a new Request Filter associated with + this object.
    • +
    • Select and edit the configurable properties of an + associated Request Filter
    • +
    • Remove an associated Request Filter.
    • +
    + +

    JDBC Resource

    + +

    From the perspective of a particular JDBC Resource, it shall + be possible to perform the following administrative operations:

    +
      +
    • Navigate to the owning Context or Default Context.
    • +
    • Edit the configurable properties of this object.
    • +
    + +

    Loader

    + +

    From the perspective of a particular Loader, it shall + be possible to perform the following administrative operations:

    +
      +
    • Navigate to the owning Context.
    • +
    • Edit the configurable properties of this object.
    • +
    + +

    Manager

    + +

    From the perspective of a particular Manager, it shall + be possible to perform the following administrative operations:

    +
      +
    • Navigate to the owning Context.
    • +
    • Edit the configurable properties of this object.
    • +
    + +

    Realm

    + +

    From the perspective of a particular Realm, it shall + be possible to perform the following administrative operations:

    +
      +
    • Navigate to the owning Engine, Host, or + Context.
    • +
    • Edit the configurable properties of this object.
    • +
    + +

    Request Filter

    + +

    From the perspective of a particular Request Filter, it shall + be possible to perform the following administrative operations:

    +
      +
    • Navigate to the owning Engine, Host, or + Context.
    • +
    • Edit the configurable properties of this object.
    • +
    + +

    Server

    + +

    From the perspective of the overall Server, it shall be + possible to perform the following administrative operations:

    +
      +
    • Edit the configurable properties of this object.
    • +
    • Create and configure a new Service associated with + this object.
    • +
    • Select and edit the configurable properties of an associated + Service.
    • +
    + +

    Service

    + +

    From the perspective of a particular Service, it shall be + possible to perform the following administrative operations:

    +
      +
    • Navigate to the owning Server.
    • +
    • Edit the configurable properties of this object.
    • +
    • Create and configure a new Connector associated with + this object.
    • +
    • Select and edit the configurable properties of an associated + Connector.
    • +
    • Remove an associated Connector.
    • +
    • Create and configure a new Engine associated with + this object.
    • +
    • Edit the configurable properties of the associated Engine.
    • +
    • Remove the associated Engine.
    • +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/funcspecs/fs-default.html b/tomcat/docs/funcspecs/fs-default.html new file mode 100644 index 0000000..8d7eb6d --- /dev/null +++ b/tomcat/docs/funcspecs/fs-default.html @@ -0,0 +1,270 @@ + +Catalina Functional Specifications (8.5.43) - Default Servlet

    Default Servlet

    Table of Contents

    Overview

    + + +

    Introduction

    + +

    The purpose of the Default Servlet is to serve + static resources of a web application in response to client requests. + As the name implies, it is generally configured as the "default" + servlet for a web application, by being mapped to a URL pattern "/".

    + +
    + + +

    External Specifications

    + +

    The following external specifications have provisions which + partially define the correct behavior of the default servlet:

    + + +
    + + +

    Implementation Requirements

    + +

    The implementation of this functionality shall conform to the + following requirements:

    +
      +
    • Must be implemented as a servlet.
    • +
    • Must support configurable parameters for debugging detail level, + input buffer size, output buffer size, whether or not to produce + directory listings when no welcome file is present, and whether or not + modifications are supported via DELETE and PUT.
    • +
    • Log debugging and operational messages (suitably internationalized) + via the getServletContext().log() method.
    • +
    + +
    + + +

    Dependencies

    + + +

    Environmental Dependencies

    + +

    The following environmental dependencies must be met in order for + the default servlet to operate correctly:

    +
      +
    • The default servlet must be registered in the application deployment + descriptor (or the default deployment descriptor in file + $CATALINA_BASE/conf/web.xml) using a "default servlet" + servlet mapping, signified by URL pattern "/".
    • +
    + +
    + + +

    Container Dependencies

    + +

    Correct operation of the default servlet depends on the following + specific features of the surrounding container:

    +
      +
    • The container shall provide a servlet context attribute that + lists the welcome file names that have been defined for this + web application.
    • +
    • The container shall provide a servlet context attribute that + contains a javax.naming.directory.DirContext + implementation representing the static resources of this + web application.
    • +
    + +
    + + +

    Functionality

    + + +

    Initialization Functionality

    + +

    The following processing must be performed when the init() + method of the default servlet is called:

    +
      +
    • Process and sanity check configuration parameters.
    • +
    + +
    + + +

    Per-Request Functionality

    + + +

    For all HTTP request methods, the resource path is determined from + the path information provided to this request, either as request attribute + javax.servlet.include.path_info (for a request dispatcher + access to a static resource) or by calling + request.getPathInfo() directly.

    + +

    On each HTTP DELETE request processed by this servlet, the following + processing shall be performed:

    +
      +
    • If modifications to the static resources are not allowed (set by a + configuration parameter), return HTTP status 403 (forbidden).
    • +
    • If an attempt is made to delete a resource from /META-INF + or /WEB-INF, return HTTP status 403 (forbidden).
    • +
    • If the requested resource does not exist, return HTTP status 404 + (not found)
    • +
    • Unbind the resource from the directory context containing the + static resources for this web application. If successful, return + HTTP status 204 (no content). Otherwise, return HTTP status 405 + (method not allowed).
    • +
    + + +

    On each HTTP GET request processed by this servlet, the following + processing shall be performed:

    +
      +
    • If the request is for a resource under /META-INF or + /WEB-INF, return HTTP status 404 (not found).
    • +
    • If the requested resource does not exist, return HTTP status 404 + (not found).
    • +
    • If the requested resource is not a directory, but the resource + path ends in "/" or "\", return HTTP status 404 (not found).
    • +
    • If the requested resource is a directory: +
        +
      • If the request path does not end with "/", redirect to a + corresponding path with "/" appended so that relative references + in welcome files are resolved correctly.
      • +
      • If one of the specified welcome files exists, redirect to the + path for that welcome file so that it will be served explicitly. +
      • +
    • +
    • If the request being processed contains an If-Range + header, perform the processing described in the HTTP/1.1 specification + to determine whether the client's information is up to date.
    • +
    • Determine the content type of the response, by looking up the + corresponding MIME type in our servlet context.
    • +
    • If the requested resource is a directory: +
        +
      • If directory listings are suppressed, return HTTP status 404 + (not found).
      • +
      • Set the content type to text/html.
      • +
    • +
    • Determine the range(s) to be returned, based on the existence of + any If-Range and Range headers.
    • +
    • If the requested resource is a directory, include an ETag + header in the response, with the value calculated based on the content + of the directory.
    • +
    • Include a Last-Modified header in the response documenting + the date/time that the resource was last modified.
    • +
    • Unless we are processing a HEAD request, include the appropriate + content (or content ranges) in the response.
    • +
    + +

    On each HTTP HEAD request processed by this servlet, the following + processing shall be performed:

    +
      +
    • Processed identically to an HTTP GET request, except that the data + content is not transmitted after the headers.
    • +
    + +

    On each HTTP POST request processed by this servlet, the following + processing shall be performed:

    +
      +
    • Processed identically to an HTTP GET request.
    • +
    + + +

    On each HTTP PUT request processed by this servlet, the following + processing shall be performed:

    +
      +
    • If modifications to the static resources are not allowed (set by a + configuration parameter), return HTTP status 403 (forbidden).
    • +
    • If an attempt is made to delete a resource from /META-INF + or /WEB-INF, return HTTP status 403 (forbidden).
    • +
    • Create a new resource from the body of this request.
    • +
    • Bind or rebind the specified path to the new resource (depending on + whether it currently exists or not). Return HTTP status as follows: +
        +
      • If binding was unsuccessful, return HTTP status 409 (conflict). +
      • +
      • If binding was successful and the resource did not previously + exist, return HTTP status 201 (created).
      • +
      • If binding was successful and the resource previously existed, + return HTTP status 204 (no content).
      • +
    • +
    + +
    + + +

    Finalization Functionality

    + +

    No specific processing is required when the destroy() + method is called:

    + +
    + + +

    Testable Assertions

    + +

    In addition to the assertions implied by the functionality requirements + listed above, the following additional assertions shall be tested to + validate the behavior of the default servlet:

    +
      +
    • Requests for resources that do not exist in the web application must + return HTTP status 404 (not found).
    • +
    • The default servlet must operate identically for web applications that + are run out of a WAR file directly, or from an unpacked directory + structure.
    • +
    • If the web application is running out of an unpacked directory + structure, the default servlet must recognize cases where the resource + has been updated through external means.
    • +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/funcspecs/fs-jdbc-realm.html b/tomcat/docs/funcspecs/fs-jdbc-realm.html new file mode 100644 index 0000000..b567979 --- /dev/null +++ b/tomcat/docs/funcspecs/fs-jdbc-realm.html @@ -0,0 +1,266 @@ + +Catalina Functional Specifications (8.5.43) - JDBCRealm

    JDBCRealm

    Table of Contents

    Overview

    + + +

    Introduction

    + +

    The purpose of the JDBCRealm implementation is to + provide a mechanism by which Tomcat can acquire information needed + to authenticate web application users, and define their security roles, + from a relational database accessed via JDBC APIs. For integration + with Catalina, the resulting class(es) must implement the + org.apache.catalina.Realm interface.

    + +

    This specification reflects a combination of functionality that is + already present in the org.apache.catalina.realm.JDBCRealm + class, as well as requirements for enhancements that have been + discussed. Where appropriate, requirements statements are marked + [Current] and [Requested] to distinguish them.

    + +

    The current status of this functional specification is + PROPOSED. It has not yet been discussed and + agreed to on the TOMCAT-DEV mailing list.

    + +
    + + +

    External Specifications

    + +

    The implementation of this functionality depends on the following + external specifications:

    + + +
    + + +

    Implementation Requirements

    + +

    The implementation of this functionality shall conform to the + following requirements:

    +
      +
    • Be realized in one or more implementation classes.
    • +
    • Implement the org.apache.catalina.Realm interface. + [Current]
    • +
    • Implement the org.apache.catalina.Lifecycle + interface. [Current]
    • +
    • Subclass the org.apache.catalina.realm.RealmBase + base class.
    • +
    • Live in the org.apache.catalina.realm package. + [Current]
    • +
    • Support a configurable debugging detail level. [Current]
    • +
    • Log debugging and operational messages (suitably internationalized) + via the getContainer().log() method. [Current]
    • +
    + +
    + + +

    Dependencies

    + + +

    Environmental Dependencies

    + +

    The following environmental dependencies must be met in order for + JDBCRealm to operate correctly:

    +
      +
    • The desire to utilize JDBCRealm must be registered in + $CATALINA_BASE/conf/server.xml, in a + <Realm> element that is nested inside a + corresponding <Engine>, <Host>, + or <Context> element.
    • +
    + +
    + + +

    Container Dependencies

    + +

    Correct operation of JDBCRealm depends on the following + specific features of the surrounding container:

    +
      +
    • Interactions with JDBCRealm will be initiated by + the appropriate Authenticator implementation, based + on the login method that is selected.
    • +
    • JDBCRealm must have the JDBC standard API classes + available to it. For a JDK 1.2 or later container, these APIs + are included in the standard platform.
    • +
    • When connection pooling is implemented, JDBCRealm + must have the JDBC Optional Package (version 2.0 or later) APIs + available to it. This library is available as a separate + download (and will be included in Tomcat binary distributions).
    • +
    + +
    + + +

    Functionality

    + + +

    Overview of Operation

    + +

    The main purpose of JDBCRealm is to allow Catalina to + authenticate users, and look up the corresponding security roles, from + the information found in a relational database accessed via JDBC APIs. + For maximum flexibility, the details of how this is done (for example, + the names of the required tables and columns) should be configurable.

    + +

    Each time that Catalina needs to authenticate a user, it will call + the authenticate() method of this Realm implementation, + passing the username and password that were specified by the user. If + we find the user in the database (and match on the password), we accumulate + all of the security roles that are defined for this user, and create a + new GenericPrincipal object to be returned. If the user + is not authenticated, we return null instead. The + GenericUser object caches the set of security roles that + were owned by this user at the time of authentication, so that calls to + isUserInRole() can be answered without going back to the + database every time.

    + +
    + + +

    Detailed Functional Requirements

    + + +

    Configurable Properties

    + +

    The implementation shall support the following properties + that can be configured with JavaBeans property setters:

    +
      +
    • Configuration parameters defining the JDBC driver to use, the + database connection URL to be accessed, and the username/password + to use for logging in. [Current]
    • +
    • Configuration parameters describing the connection pool to be + created to support simultaneous authentications. [Requested]
    • +
    • Name of the tables to be searched for users and roles. [Current]
    • +
    • Name of the columns to be used for usernames, passwords, and + role names. [Current]
    • +
    + +

    Lifecycle Functionality

    + +

    The following processing must be performed when the start() + method is called:

    +
      +
    • Establish a connection to the configured database, using the + configured username and password. [Current]
    • +
    • Configure and establish a connection pool of connections to the + database. [Requested]
    • +
    + +

    The following processing must be performed when the stop() + method is called:

    +
      +
    • Close any opened connections to the database.
    • +
    + + +

    Method authenticate() Functionality

    + +

    When authenticate() is called, the following processing + is required:

    +
      +
    • Acquire the one and only connection [Current] or acquire a connection + from the connection pool [Requested].
    • +
    • Select the one and only row from the user's table for this user, + and retrieve the corresponding password column. If zero rows (or + more than one row) are found, return null.
    • +
    • Authenticate the user by comparing the (possibly encrypted) password + value that was received against the password presented by the user. + If there is no match, return null.
    • +
    • Acquire a List of the security roles assigned to the + authenticated user by selecting from the roles table.
    • +
    • Construct a new instance of class + org.apache.catalina.realm.GenericPrincipal, passing as + constructor arguments: this realm instance, the authenticated + username, and a List of the security roles associated + with this user.
    • +
    • WARNING - Do not attempt to cache and reuse previous + GenericPrincipal objects for a particular user, because + the information in the directory server might have changed since the + last time this user was authenticated.
    • +
    • Return the newly constructed GenericPrincipal.
    • +
    + + +

    Method hasRole() Functionality

    + +

    When hasRole() is called, the following processing + is required:

    +
      +
    • The principal that is passed as an argument SHOULD + be one that we returned (instanceof class + org.apache.catalina.realm.GenericPrincipal, with a + realm property that is equal to our instance.
    • +
    • If the passed principal meets these criteria, check + the specified role against the list returned by + getRoles(), and return true if the + specified role is included; otherwise, return false.
    • +
    • If the passed principal does not meet these criteria, + return false.
    • +
    + +
    + +

    Testable Assertions

    + +

    In addition to the assertions implied by the functionality requirements + listed above, the following additional assertions shall be tested to + validate the behavior of JDBCRealm:

    +
      +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/funcspecs/fs-jndi-realm.html b/tomcat/docs/funcspecs/fs-jndi-realm.html new file mode 100644 index 0000000..04dbb33 --- /dev/null +++ b/tomcat/docs/funcspecs/fs-jndi-realm.html @@ -0,0 +1,417 @@ + +Catalina Functional Specifications (8.5.43) - JNDIRealm

    JNDIRealm

    Table of Contents

    Overview

    + + +

    Introduction

    + +

    The purpose of the JNDIRealm implementation is to + provide a mechanism by which Tomcat can acquire information needed + to authenticate web application users, and define their security roles, + from a directory server or other service accessed via JNDI APIs. For + integration with Catalina, this class must implement the + org.apache.catalina.Realm interface.

    + +

    This specification reflects a combination of functionality that is + already present in the org.apache.catalina.realm.JNDIRealm + class, as well as requirements for enhancements that have been + discussed. Where appropriate, requirements statements are marked + [Current] and [Requested] to distinguish them.

    + +

    The current status of this functional specification is + PROPOSED. It has not yet been discussed and + agreed to on the TOMCAT-DEV mailing list.

    + +

    The code in the current version of JNDIRealm, and the + ideas expressed in this functional specification, are the results of + contributions from many individuals, including (alphabetically):

    +
      +
    • Holman, John <j.g.holman@qmw.ac.uk>
    • +
    • Lockhart, Ellen <elockhart@home.com>
    • +
    • McClanahan, Craig <craigmcc@apache.org>
    • +
    + +
    + + +

    External Specifications

    + +

    The implementation of this functionality depends on the following + external specifications:

    + + +
    + + +

    Implementation Requirements

    + +

    The implementation of this functionality shall conform to the + following requirements:

    +
      +
    • Be realized in one or more implementation classes.
    • +
    • Implement the org.apache.catalina.Realm interface. + [Current]
    • +
    • Implement the org.apache.catalina.Lifecycle + interface. [Current]
    • +
    • Subclass the org.apache.catalina.realm.RealmBase + base class.
    • +
    • Live in the org.apache.catalina.realm package. + [Current]
    • +
    • Support a configurable debugging detail level. [Current]
    • +
    • Log debugging and operational messages (suitably internationalized) + via the getContainer().log() method. [Current]
    • +
    + +
    + + +

    Dependencies

    + + +

    Environmental Dependencies

    + +

    The following environmental dependencies must be met in order for + JNDIRealm to operate correctly:

    +
      +
    • The desire to utilize JNDIRealm must be registered in + $CATALINA_BASE/conf/server.xml, in a + <Realm> element that is nested inside a + corresponding <Engine>, <Host>, + or <Context> element.
    • +
    • If the Administrator Login operational mode is selected, + the configured administrator username and password must be configured + in the corresponding directory server.
    • +
    • If the Username Login operational mode is selected, + the corresponding directory server must be configured to accept + logins with the username and password that will be passed to + JNDIRealm by the appropriate Authenticator. +
    • +
    + +
    + + +

    Container Dependencies

    + +

    Correct operation of JNDIRealm depends on the following + specific features of the surrounding container:

    +
      +
    • Interactions with JNDIRealm will be initiated by + the appropriate Authenticator implementation, based + on the login method that is selected.
    • +
    + +
    + + +

    Functionality

    + + +

    Operational Modes

    + +

    The completed JNDIRealm must support two major operational + modes in order to support all of the required use cases. For the purposes + of this document, the modes are called administrator login and + Username Login. They are described further in the following + paragraphs.

    + +

    For Administrator Login mode, JNDIRealm will be + configured to establish one or more connections (using a connection pool) + to an appropriate directory server, using JNDI APIs, under a "system + administrator" username and password. This is similar to the approach + normally used to configure JDBCRealm to access authentication + and access control information in a database. It is assumed that the + system administrator username and password that are configured provide + sufficient privileges within the directory server to read (but not modify) + the username, password, and assigned roles for each valid user of the + web application associated with this Realm. The password + can be stored in cleartext, or in one of the digested modes supported by + the org.apache.catalina.realm.RealmBase base class.

    + +

    For Username Login mode, JNDIRealm does not + normally remain connected to the directory server. Instead, whenever a + user is to be authenticated, a connection to the directory server + (using the username and password received from the authenticator) is + attempted. If this connection is successful, the user is assumed to be + successfully authenticated. This connection is then utilized to read + the corresponding security roles associated with this user, and the + connection is then broken.

    + +

    NOTE - Username Login mode cannot be used + if you have selected login method DIGEST in your web + application deployment descriptor (web.xml) file. This + restriction exists because the cleartext password is never available + to the container, so it is not possible to bind to the directory server + using the user's username and password.

    + +

    Because these operational modes work so differently, the functionality + for each mode will be described separately. Whether or not both modes + are actually supported by a single class (versus a class per mode) is + an implementation detail left to the designer.

    + +

    NOTE - The current implementation only implements + part of the Administrator Lookup mode requirements. It does + not support the Username Lookup mode at all, at this point.

    + +
    + + +

    Administrator Login Mode Functionality

    + + +

    Configurable Properties

    + +

    The implementation shall support the following properties + that can be configured with JavaBeans property setters:

    +
      +
    • connectionURL - URL of the directory server we will + be contacting.
    • +
    • contextFactory - Fully qualified class name of the JNDI + context factory used to retrieve our InitialContext. + [com.sun.jndi.ldap.LdapCtxFactory]
    • +
    • Additional configuration properties required to establish the + appropriate connection. [Requested]
    • +
    • Connection pool configuration properties. [Requested]
    • +
    • Configuration properties defining how a particular user is + authenticated. The following capabilities should be supported: +
        +
      • Substitute the specified username into a string. [Requested]
      • +
      • Retrieve the distinguished name (DN) of an authorized user via an + LDAP search string with a replacement placeholder for the + username, and comparison of the password to a configurable + attribute retrieved from the search result. [Current]
      • +
    • +
    • Configuration properties defining how the roles associated with a + particular authenticated user can be retrieved. The following + approaches should be supported: +
        +
      • Retrieve a specified attribute (possibly multi-valued) + from an LDAP search expression, + with a replacement placeholder for the DN of the user. + [Current]
      • +
      • Retrieve a set of role names that are defined implicitly (by + selecting principals that match a search pattern) rather than + explicitly (by finding a particular attribute value). + [Requested]
      • +
    • +
    + +

    Lifecycle Functionality

    + +

    The following processing must be performed when the start() + method is called:

    +
      +
    • Establish a connection to the configured directory server, using the + configured system administrator username and password. [Current]
    • +
    • Configure and establish a connection pool of connections to the + directory server. [Requested]
    • +
    + +

    The following processing must be performed when the stop() + method is called:

    +
      +
    • Close any opened connections to the directory server.
    • +
    + + +

    Method authenticate() Functionality

    + +

    When authenticate() is called, the following processing + is required:

    +
      +
    • Acquire the one and only connection [Current] or acquire a connection + from the connection pool [Requested].
    • +
    • Authenticate the user by retrieving the user's Distinguished Name, + based on the specified username and password.
    • +
    • If the user was not authenticated, release the allocated connection + and return null.
    • +
    • Acquire a List of the security roles assigned to the + authenticated user.
    • +
    • Construct a new instance of class + org.apache.catalina.realm.GenericPrincipal, passing as + constructor arguments: this realm instance, the authenticated + username, and a List of the security roles associated + with this user.
    • +
    • WARNING - Do not attempt to cache and reuse previous + GenericPrincipal objects for a particular user, because + the information in the directory server might have changed since the + last time this user was authenticated.
    • +
    • Return the newly constructed GenericPrincipal.
    • +
    + + +

    Method hasRole() Functionality

    + +

    When hasRole() is called, the following processing + is required:

    +
      +
    • The principal that is passed as an argument SHOULD + be one that we returned (instanceof class + org.apache.catalina.realm.GenericPrincipal, with a + realm property that is equal to our instance.
    • +
    • If the passed principal meets these criteria, check + the specified role against the list returned by + getRoles(), and return true if the + specified role is included; otherwise, return false.
    • +
    • If the passed principal does not meet these criteria, + return false.
    • +
    + +
    + + +

    Username Login Mode Functionality

    + +

    Configurable Properties

    + +

    The implementation shall support the following properties + that can be configured with JavaBeans property setters:

    +
      +
    • connectionURL - URL of the directory server we will + be contacting.
    • +
    • contextFactory - Fully qualified class name of the JNDI + context factory used to retrieve our InitialContext. + [com.sun.jndi.ldap.LdapCtxFactory]
    • +
    • Additional configuration properties required to establish the + appropriate connection. [Requested]
    • +
    • Connection pool configuration properties. [Requested]
    • +
    • Configuration properties defining if and how a user might be looked + up before binding to the directory server. The following approaches + should be supported: +
        +
      • No previous lookup is required - username specified by the user + is the same as that used to authenticate to the directory + server.
      • +
      • Substitute the specified username into a string.
      • +
      • Search the directory server based on configured criteria to + retrieve the distinguished name of the user, then attempt to + bind with that distinguished name.
      • +
    • +
    • Configuration properties defining how the roles associated with a + particular authenticated user can be retrieved. The following + approaches should be supported: +
        +
      • Retrieve a specified attribute (possibly multi-valued) + from an LDAP search expression, + with a replacement placeholder for the DN of the user. + [Current]
      • +
    • +
    + +

    Lifecycle Functionality

    + +

    The following processing must be performed when the start() + method is called:

    +
      +
    • None required.
    • +
    + +

    The following processing must be performed when the stop() + method is called:

    +
      +
    • None required.
    • +
    + + +

    Method authenticate() Functionality

    + +

    When authenticate() is called, the following processing + is required:

    +
      +
    • Attempt to bind to the directory server, using the username and + password provided by the user.
    • +
    • If the user was not authenticated, release the allocated connection + and return null.
    • +
    • Acquire a List of the security roles assigned to the + authenticated user.
    • +
    • Construct a new instance of class + org.apache.catalina.realm.GenericPrincipal, passing as + constructor arguments: this realm instance, the authenticated + username, and a List of the security roles associated + with this user.
    • +
    • WARNING - Do not attempt to cache and reuse previous + GenericPrincipal objects for a particular user, because + the information in the directory server might have changed since the + last time this user was authenticated.
    • +
    • Return the newly constructed GenericPrincipal.
    • +
    + + +

    Method hasRole() Functionality

    + +

    When hasRole() is called, the following processing + is required:

    +
      +
    • The principal that is passed as an argument SHOULD + be one that we returned (instanceof class + org.apache.catalina.realm.GenericPrincipal, with a + realm property that is equal to our instance.
    • +
    • If the passed principal meets these criteria, check + the specified role against the list returned by + getRoles(), and return true if the + specified role is included; otherwise, return false.
    • +
    • If the passed principal does not meet these criteria, + return false.
    • +
    + +
    + +

    Testable Assertions

    + +

    In addition to the assertions implied by the functionality requirements + listed above, the following additional assertions shall be tested to + validate the behavior of JNDIRealm:

    +
      +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/funcspecs/fs-memory-realm.html b/tomcat/docs/funcspecs/fs-memory-realm.html new file mode 100644 index 0000000..0eb2344 --- /dev/null +++ b/tomcat/docs/funcspecs/fs-memory-realm.html @@ -0,0 +1,253 @@ + +Catalina Functional Specifications (8.5.43) - MemoryRealm

    MemoryRealm

    Table of Contents

    Overview

    + + +

    Introduction

    + +

    The purpose of the MemoryRealm implementation is to + provide a mechanism by which Tomcat can acquire information needed + to authenticate web application users, and define their security roles, + from a simple text-based configuration file in XML format. This is + intended to simplify the initial installation and operation of Tomcat, + without the complexity of configuring a database or directory server + based Realm. It is not intended for production use.

    + +

    This specification reflects a combination of functionality that is + already present in the org.apache.catalina.realm.MemoryRealm + class, as well as requirements for enhancements that have been + discussed. Where appropriate, requirements statements are marked + [Current] and [Requested] to distinguish them.

    + +

    The current status of this functional specification is + PROPOSED. It has not yet been discussed and + agreed to on the TOMCAT-DEV mailing list.

    + +
    + + +

    External Specifications

    + +

    The implementation of this functionality depends on the following + external specifications:

    +
      +
    • None
    • +
    + +
    + + +

    Implementation Requirements

    + +

    The implementation of this functionality shall conform to the + following requirements:

    +
      +
    • Be realized in one or more implementation classes.
    • +
    • Implement the org.apache.catalina.Realm interface. + [Current]
    • +
    • Implement the org.apache.catalina.Lifecycle + interface. [Current]
    • +
    • Subclass the org.apache.catalina.realm.RealmBase + base class.
    • +
    • Live in the org.apache.catalina.realm package. + [Current]
    • +
    • Support a configurable debugging detail level. [Current]
    • +
    • Log debugging and operational messages (suitably internationalized) + via the getContainer().log() method. [Current]
    • +
    + +
    + + +

    Dependencies

    + + +

    Environmental Dependencies

    + +

    The following environmental dependencies must be met in order for + MemoryRealm to operate correctly:

    +
      +
    • The desire to utilize MemoryRealm must be registered in + $CATALINA_BASE/conf/server.xml, in a + <Realm> element that is nested inside a + corresponding <Engine>, <Host>, + or <Context> element. (This is already + included in the default server.xml file.)
    • +
    + +
    + + +

    Container Dependencies

    + +

    Correct operation of MemoryRealm depends on the following + specific features of the surrounding container:

    +
      +
    • Interactions with MemoryRealm will be initiated by + the appropriate Authenticator implementation, based + on the login method that is selected.
    • +
    • MemoryRealm must have an XML parser compatible with + the JAXP/1.1 APIs available to it. This is normally accomplished + by placing the corresponding JAR files in directory + $CATALINA_HOME/lib.
    • +
    + +
    + + +

    Functionality

    + + +

    Overview of Operation

    + +

    The main purpose of MemoryRealm is to allow Catalina to + authenticate users, and look up the corresponding security roles, from + the information found in an XML-format configuration file. The format + of this file is described below. When a MemoryRealm + instance is started, it will read the contents of this XML file and create + an "in memory database" of all the valid users and their associated + security roles.

    + +

    Each time that Catalina needs to authenticate a user, it will call + the authenticate() method of this Realm implementation, + passing the username and password that were specified by the user. If + we find the user in the database (and match on the password), we accumulate + all of the security roles that are defined for this user, and create a + new GenericPrincipal object to be returned. If the user + is not authenticated, we return null instead. The + GenericUser object caches the set of security roles that + were owned by this user at the time of authentication, so that calls to + isUserInRole() can be answered without going back to the + database every time.

    + +
    + + +

    Detailed Functional Requirements

    + + +

    Configurable Properties

    + +

    The implementation shall support the following properties + that can be configured with JavaBeans property setters:

    +
      +
    • Configurable debugging detail level.
    • +
    • Configurable file pathname (absolute or relative to + $CATALINA_BASE of the XML file containing our + defined users. [conf/tomcat-users.xml].
    • +
    + +

    Lifecycle Functionality

    + +

    The following processing must be performed when the start() + method is called:

    +
      +
    • Open and parse the specified XML file.
    • +
    • Create an in-memory database representation of the XML file + contents.
    • +
    • NOTE - There is no requirement to recognize + subsequent changes to the contents of the XML file.
    • +
    + +

    The following processing must be performed when the stop() + method is called:

    +
      +
    • Release object references to the in-memory database representation.
    • +
    + + +

    Method authenticate() Functionality

    + +

    When authenticate() is called, the following processing + is required:

    +
      +
    • Select the one and only "user" instance from the in-memory database, + based on matching the specified username. If there is no such + instance, return null.
    • +
    • Authenticate the user by comparing the (possibly encrypted) password + value that was received against the password presented by the user. + If there is no match, return null.
    • +
    • Construct a new instance of class + org.apache.catalina.realm.GenericPrincipal (if not + already using this as the internal database representation) that + contains the authenticated username and a List of the + security roles associated with this user.
    • +
    • Return the newly constructed GenericPrincipal.
    • +
    + + +

    Method hasRole() Functionality

    + +

    When hasRole() is called, the following processing + is required:

    +
      +
    • The principal that is passed as an argument SHOULD + be one that we returned (instanceof class + org.apache.catalina.realm.GenericPrincipal, with a + realm property that is equal to our instance.
    • +
    • If the passed principal meets these criteria, check + the specified role against the list returned by + getRoles(), and return true if the + specified role is included; otherwise, return false.
    • +
    • If the passed principal does not meet these criteria, + return false.
    • +
    + +
    + +

    Testable Assertions

    + +

    In addition to the assertions implied by the functionality requirements + listed above, the following additional assertions shall be tested to + validate the behavior of MemoryRealm:

    +
      +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/funcspecs/index.html b/tomcat/docs/funcspecs/index.html new file mode 100644 index 0000000..dc6008a --- /dev/null +++ b/tomcat/docs/funcspecs/index.html @@ -0,0 +1,80 @@ + +Catalina Functional Specifications (8.5.43) - Table of Contents

    Table of Contents

    Catalina Functional Specifications

    + +

    This documentation area includes functional specifications for +many features supported by the Catalina servlet container +portion of Tomcat. In most cases, these features are not documented in the +underlying Servlet or JSP specifications, so a definition of the expected +correct behavior is important both to implementors of those features, and to +test writers trying to decide what to test.

    + +

    The functional specifications are divided into the following categories +in the menu (to the left):

    +
      +
    • Administrative Apps - Overall requirements for supporting an + ability to configure and operate a Tomcat installation through tools, + as well as detailed requirements for the tools themselves.
    • +
    • Internal Servlets - Requirements for Catalina features that are + implemented as internal, container-managed, servlets.
    • +
    • Realm Implementations - Requirements for the implementations of + the org.apache.catalina.Realm interface (providing access to + collections of users, passwords and roles) that are included in the + standard Tomcat distribution.
    • +
    + +

    NOTE - In some cases, the contents of these functional specs has +been "reverse engineered" from existing implementations. This exercise is +still useful, because it provides an introduction to what +Catalina does, without being as concerned with how this is +accomplished.

    + +

    TODO - Obviously, this area has a long ways to go before +it is complete. Contributions are welcome!

    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/funcspecs/mbean-names.html b/tomcat/docs/funcspecs/mbean-names.html new file mode 100644 index 0000000..fed59fc --- /dev/null +++ b/tomcat/docs/funcspecs/mbean-names.html @@ -0,0 +1,701 @@ + +Catalina Functional Specifications (8.5.43) - Tomcat MBean Names

    Tomcat MBean Names

    Table of Contents

    Background

    + +

    We will be using JMX MBeans as the technology for + implementing manageability of Tomcat.

    + +

    One of the key concepts of JMX is that each management bean has a unique + name in the MBeanServer's registry, and that management applications can + utilize these names to retrieve the MBean of interest to them for a + particular management operation. This document proposes a naming convention + for MBeans that allows easy calculation of the name for a particular MBean. + For background information on JMX MBean names, see the Java Management + Extensions Instrumentation and Agent Specification, version 1.0, + section 6. In particular, we will be discussing the String Representation of + ObjectName instances.

    + +

    Catalina Object Hierarchy

    + +

    Tomcat's servlet container implementation, called Catalina, can be +represented as a hierarchy of objects that contain references to each other. +The object hierarchy can be represented as a tree, or (isomorphically) based +on the nesting of configuration elements in the conf/server.xml +file that is traditionally used to configure Tomcat stand-alone.

    + +

    The valid component nestings for Catalina are depicted in the following +table, with columns that contain the following values:

    +
      +
    • Pattern - Nesting pattern of XML elements (in the + conf/server.xml file) used to configure this component.
    • +
    • Cardinality - Minimum and maximum number of occurrences of + this element at this nesting position, which also corresponds to the + minimum and maximum number of Catalina components.
    • +
    • Identifier - Name of the JavaBeans property of this component + that represents the unique identifier (within the nested hierarchy), + if any.
    • +
    • MBean ObjectName - The portion of the MBean object name that + appears after the domain name. For now, it should be + assumed that all of these MBeans appear in the default JMX domain.
    • +
    + +

    In the MBean ObjectName descriptions, several types of symbolic +expressions are utilized to define variable text that is replaced by +corresponding values:

    +
      +
    • ${GROUP} - One of the standard MBean names of the specified + "group" category. For example, the expression ${REALM} + represents the values like JDBCRealm and JAASRealm + that identify the various MBeans for possible Realm components.
    • +
    • ${name} - Replaced by the value of property name + from the current component.
    • +
    • ${parent.name} - Replaced by the value of property + name from a parent of the current component, with the + parent's type identified by parent.
    • +
    • ${###} - An arbitrary numeric identifier that preserves + order but has no other particular meaning. In general, the server will + assign numeric values to existing instances with large gaps into which + new items can be configured if desired.
    • +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    PatternCardinalityIdentifierMBean ObjectName
    Server1..1(none)type=${SERVER}
    Server / Listener0..n(none)type=${LISTENER}, sequence=${###}
    Server / Service1..nnametype=${SERVICE}, name=${name}
    Server / Service / Connector1..naddress, porttype=${CONNECTOR}, service=${service}, port=${port}, + address=${address}
    Server / Service / Connector / Factory0..1(none)(Only defined explicitly for an SSL connector, but can be treated + as part of the connector component)
    Server / Service / Connector / Listener0..n(none)type=${LISTENER}, sequence=${###}, service=${service}, + port=${connector.port}, address=${connector.address}
    Server / Service / Engine1..1(none)type=${ENGINE}, service=${service.name}
    Server / Service / Engine / Host1..nnametype=${HOST}, host=${name}, + service=${service.name}
    Server / Service / Engine / Host / Context1..npathtype=${CONTEXT}, context=${name}, host=${host.name}, + service=${service.name}
    Server / Service / Engine / Host / Context / Listener0..n(none)type=${LISTENER}, sequence=${###}, context=${context.name}, + host=${host.name}, service=${service.name}
    Server / Service / Engine / Host / Context / Loader0..1(none)type=${LOADER}, context=${context.name}, host=${host.name}, + service=${service.name}
    Server / Service / Engine / Host / Context / Manager0..1(none)type=${MANAGER}, context=${context.name}, host=${host.name}, + service=${service.name}
    Server / Service / Engine / Host / Context / Realm0..1(none)type=${REALM}, context=${context.name}, host=${host.name}, + service=${service.name}
    Server / Service / Engine / Host / Context / Resources0..1(none)type=${RESOURCES}, context=${context.name}, host=${host.name}, + service=${service.name}
    Server / Service / Engine / Host / Context / Valve0..n(none)type=${VALVE}, sequence=${###}, context=${context.name}, + host=${host.name}, service=${service.name}
    Server / Service / Engine / Host / Context / Wrapper0..n(none)j2eeType=Servlet,name=${name}, + WebModule=//${host.name}/${context.name}, + J2EEApplication=${context.J2EEApplication}, + J2EEServer=${context.J2EEServer}
    Server / Service / Engine / Host / Context / WrapperLifecycle0..n(none)type=${WRAPPER-LIFECYCLE}, sequence=${###}, + context=${context.name}, host=${host.name}, + service=${service.name}
    Server / Service / Engine / Host / Context / WrapperListener0..n(none)type=${WRAPPER-LISTENER}, sequence=${###}, + context=${context.name}, host=${host.name}, + service=${service.name}
    Server / Service / Engine / Host / Listener0..n(none)type=${LISTENER}, sequence=${###}, host=${host.name}, + service=${service.name}
    Server / Service / Engine / Host / Realm0..1(none)type=${REALM}, host=${host.name}, + service=${service.name}
    Server / Service / Engine / Host / Valve0..n(none)type=${VALVE}, sequence=${###}, + host=${host.name}, service=${service.name}
    Server / Service / Engine / Listener0..n(none)type=${LISTENER}, sequence=${###} + (FIXME - disambiguate from Server / Service / + Listener)
    Server / Service / Engine / Realm0..1(none)type=${REALM}, service=${service.name}
    Server / Service / Engine / Valve0..n(none)type=${VALVE}, sequence=${###}, + service=${service.name}
    Server / Service / Listener0..n(none)type=${LISTENER}, sequence=${###} + (FIXME - disambiguate from Server / Service / + Engine / Listener)
    + +

    MBean Groups and Names

    + +

    The following MBean names shall be defined in the resource file +/org/apache/catalina/mbeans/mbeans-descriptors.xml (and +therefore available for use within the Administration/Configuration +web application for Tomcat):

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    MBean NameGroup NameCatalina InterfaceImplementation Class
    AccessLogValveVALVEorg.apache.catalina.Valveorg.apache.catalina.valves.AccessLogValve
    BasicAuthenticatorVALVEorg.apache.catalina.Valveorg.apache.catalina.authenticator.BasicAuthenticator
    CertificatesValveVALVEorg.apache.catalina.Valveorg.apache.catalina.valves.CertificatesValve
    ContextConfigLISTENERorg.apache.catalina.LifecycleListenerorg.apache.catalina.startup.ContextConfig
    ContextEnvironmentRESOURCESorg.apache.catalina.deploy.ContextEnvironmentorg.apache.catalina.deploy.ContextEnvironment
    ContextResourceRESOURCESorg.apache.catalina.deploy.ContextResourceorg.apache.catalina.deploy.ContextResource
    ContextResourceLinkRESOURCESorg.apache.catalina.deploy.ContextResourceLinkorg.apache.catalina.deploy.ContextResourceLink
    CoyoteConnectorCONNECTORorg.apache.catalina.Connectororg.apache.coyote.tomcat4.CoyoteConnector
    DigestAuthenticatorVALVEorg.apache.catalina.Valveorg.apache.catalina.authenticator.DigestAuthenticator
    EngineConfigLISTENERorg.apache.catalina.LifecycleListenerorg.apache.catalina.startup.EngineConfig
    ErrorReportValveVALVEorg.apache.catalina.Valveorg.apache.catalina.valves.ErrorReportValve
    ErrorDispatcherValveVALVEorg.apache.catalina.Valveorg.apache.catalina.valves.ErrorDispatcherValve
    FormAuthenticatorVALVEorg.apache.catalina.Valveorg.apache.catalina.authenticator.FormAuthenticator
    GroupGROUPorg.apache.catalina.Grouporg.apache.catalina.Group
    HostConfigLISTENERorg.apache.catalina.LifecycleListenerorg.apache.catalina.startup.HostConfig
    HttpConnector10CONNECTORorg.apache.catalina.Connectororg.apache.catalina.connector.http10.HttpConnector
    HttpConnector11CONNECTORorg.apache.catalina.Connectororg.apache.catalina.connector.http.HttpConnector
    JAASRealmREALMorg.apache.catalina.Realmorg.apache.catalina.realm.JAASRealm
    JDBCRealmREALMorg.apache.catalina.Realmorg.apache.catalina.realm.JDBCRealm
    JDBCUserDatabaseUSERDATABASEorg.apache.catalina.users.JDBCUserDatabaseorg.apache.catalina.users.JDBCUserDatabase
    JNDIRealmREALMorg.apache.catalina.Realmorg.apache.catalina.realm.JNDIRealm
    MBeanFactoryorg.apache.catalina.mbeans.MBeanFactory
    MemoryRealmREALMorg.apache.catalina.Realmorg.apache.catalina.realm.MemoryRealm
    MemoryUserDatabaseUSERDATABASEorg.apache.catalina.users.MemoryUserDatabaseorg.apache.catalina.users.MemoryUserDatabase
    NamingContextListenerLISTENERorg.apache.catalina.LifecycleListenerorg.apache.catalina.core.NamingContextListener
    NamingResourcesRESOURCESorg.apache.catalina.deploy.NamingResourcesorg.apache.catalina.deploy.NamingResources
    NonLoginAuthenticatorVALVEorg.apache.catalina.Valveorg.apache.catalina.authenticator.NonLoginAuthenticator
    PersistentManagerMANAGERorg.apache.catalina.Managerorg.apache.catalina.session.PersistentManager
    RemoteAddrValveVALVEorg.apache.catalina.Valveorg.apache.catalina.valves.RemoteAddrValve
    RemoteHostValveVALVEorg.apache.catalina.Valveorg.apache.catalina.valves.RemoteHostValve
    RequestDumperValveVALVEorg.apache.catalina.Valveorg.apache.catalina.valves.RequestDumperValve
    RoleROLEorg.apache.catalina.Roleorg.apache.catalina.Role
    SingleSignOnVALVEorg.apache.catalina.Valveorg.apache.catalina.valves.SingleSignOn
    SSLAuthenticatorVALVEorg.apache.catalina.Valveorg.apache.catalina.authenticator.SSLAuthenticator
    StandardContextCONTEXTorg.apache.catalina.Contextorg.apache.catalina.core.StandardContext
    StandardContextValveVALVEorg.apache.catalina.Valveorg.apache.catalina.core.StandardContextValve
    StandardEngineENGINEorg.apache.catalina.Engineorg.apache.catalina.core.StandardEngine
    StandardEngineValveVALVEorg.apache.catalina.Valveorg.apache.catalina.core.StandardEngineValve
    StandardHostHOSTorg.apache.catalina.Hostorg.apache.catalina.core.StandardHost
    StandardHostValveVALVEorg.apache.catalina.Valveorg.apache.catalina.core.StandardHostValve
    StandardManagerMANAGERorg.apache.catalina.Managerorg.apache.catalina.session.StandardManager
    StandardServerSERVERorg.apache.catalina.Serverorg.apache.catalina.core.StandardServer
    StandardServiceSERVICEorg.apache.catalina.Serviceorg.apache.catalina.core.StandardService
    StandardWrapperWRAPPERorg.apache.catalina.Wrapperorg.apache.catalina.core.StandardWrapper
    StandardWrapperValveVALVEorg.apache.catalina.Valveorg.apache.catalina.core.StandardWrapperValve
    UserUSERorg.apache.catalina.Userorg.apache.catalina.User
    UserDatabaseRealmREALMorg.apache.catalina.Realmorg.apache.catalina.realm.UserDatabaseRealm
    WebappLoaderLOADERorg.apache.catalina.Loaderorg.apache.catalina.loader.WebappLoader
    + +

    JSR-88 Cross Reference

    + +

    The deployment objects in the JSR-88 API object hierarchy correspond +to the specified MBean names or groups as follows:

    + + + + + + + + + + + + + + + + + + + + + +
    JSR-88 API ObjectMBean Name or GroupComments
    DeployableObject${CONTEXT}Context deployment info plus the corresponding WAR file
    Target${HOST}
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/host-manager-howto.html b/tomcat/docs/host-manager-howto.html new file mode 100644 index 0000000..1f84e0e --- /dev/null +++ b/tomcat/docs/host-manager-howto.html @@ -0,0 +1,252 @@ + +Apache Tomcat 8 (8.5.43) - Host Manager App -- Text Interface

    Host Manager App -- Text Interface

    Table of Contents

    Introduction

    +

    + The Tomcat Host Manager application enables you to create, + delete, and otherwise manage virtual hosts within Tomcat. This how-to guide + is best accompanied by the following pieces of documentation: +

    +
      +
    • + Virtual Hosting How-To for more + information about virtual hosting. +
    • +
    • + The Host Container for more information + about the underlying xml configuration of virtual hosts and description + of attributes. +
    • +
    + +

    + The Tomcat Host Manager application is a part of + Tomcat installation, by default available using the following + context: /host-manager. You can use the host manager in the + following ways: +

    + +
      +
    • + Utilizing the graphical user interface, accessible at: + {server}:{port}/host-manager/html. +
    • +
    • + Utilizing a set of minimal HTTP requests suitable for scripting. + You can access this mode at: + {server}:{port}/host-manager/text. +
    • +
    +

    + Both ways enable you to add, remove, start, and stop virtual hosts. Changes + may be presisted by using the persist command. This document + focuses on the text interface. For further information about the graphical + interface, see + Host Manager App -- HTML Interface. +

    +

    Configuring Manager Application Access

    +

    The description below uses $CATALINA_HOME to refer the + base Tomcat directory. It is the directory in which you installed + Tomcat, for example C:\tomcat8, or + /usr/share/tomcat8.

    + +

    + The Host Manager application requires a user with one of the following + roles: +

    + +
      +
    • + admin-gui - use this role for the graphical web interface. +
    • +
    • + admin-script - use this role for the scripting web interface. +
    • +
    + +

    + To enable access to the text interface of the Host Manager application, + either grant your Tomcat user the appropriate role, or create a new one with + the correct role. For example, open + ${CATALINA_BASE}/conf/tomcat-users.xml and enter the following: +

    +
    <user username="test" password="chang3m3N#w" roles="admin-script"/>
    +

    + No further settings is needed. When you now access + {server}:{port}/host-manager/text/${COMMAND},you are able to + log in with the created credentials. For example: +

    $ curl -u ${USERNAME}:${PASSWORD} http://localhost:8080/host-manager/text/list
    +OK - Listed hosts
    +localhost:
    +

    +

    + Note that in case you retrieve your users using the + DataSourceRealm, JDBCRealm, or + JNDIRealm mechanism, add the appropriate role in the database + or the directory server respectively. +

    +

    List of Commands

    +

    The following commands are supported:

    +
      +
    • list
    • +
    • add
    • +
    • remove
    • +
    • start
    • +
    • stop
    • +
    • persist
    • +
    +

    + In the following subsections, the username and password is assumed to be + test:test. For your environment, use credentials created in the + previous sections. +

    +

    List command

    +

    + Use the list command to see the available virtual hosts on your + Tomcat instance. +

    +

    Example command:

    + curl -u test:test http://localhost:8080/host-manager/text/list +

    Example response:

    +
    OK - Listed hosts
    +localhost:
    +
    +

    Add command

    +

    + Use the add command to add a new virtual host. Parameters used + for the add command: +

    +
      +
    • String name: Name of the virtual host. REQUIRED
    • +
    • String aliases: Aliases for your virtual host.
    • +
    • String appBase: Base path for the application that will be + served by this virtual host. Provide relative or absolute path.
    • +
    • Boolean manager: If true, the Manager app is added to the + virtual host. You can access it with the /manager context.
    • +
    • Boolean autoDeploy: If true, Tomcat automatically redeploys + applications placed in the appBase directory.
    • +
    • Boolean deployOnStartup: If true, Tomcat automatically deploys + applications placed in the appBase directory on startup.
    • +
    • Boolean deployXML: If true, the /META-INF/context.xml + file is read and used by Tomcat.
    • +
    • Boolean copyXML: If true, Tomcat copies /META-INF/context.xml + file and uses the original copy regardless of updates to the application's + /META-INF/context.xml file.
    • +
    +

    Example command:

    +
    curl -u test:test http://localhost:8080/host-manager/text/add?name=www.awesomeserver.com&aliases=awesomeserver.com&appBase/mnt/appDir&deployOnStartup=true
    +

    Example response:

    +
    add: Adding host [www.awesomeserver.com]
    +
    +

    Remove command

    +

    + Use the remove command to remove a virtual host. Parameters used + for the remove command: +

    +
      +
    • String name: Name of the virtual host to be removed. + REQUIRED
    • +
    +

    Example command:

    +
    curl -u test:test http://localhost:8080/host-manager/text/remove?name=www.awesomeserver.com
    +

    Example response:

    +
    remove: Removing host [www.awesomeserver.com]
    +
    +

    Start command

    +

    + Use the start command to start a virtual host. Parameters used + for the start command: +

    +
      +
    • String name: Name of the virtual host to be started. + REQUIRED
    • +
    +

    Example command:

    +
    curl -u test:test http://localhost:8080/host-manager/text/start?name=www.awesomeserver.com
    +

    Example response:

    +
    OK - Host www.awesomeserver.com started
    +
    +

    Stop command

    +

    + Use the stop command to stop a virtual host. Parameters used + for the stop command: +

    +
      +
    • String name: Name of the virtual host to be stopped. + REQUIRED
    • +
    +

    Example command:

    +
    curl -u test:test http://localhost:8080/host-manager/text/stop?name=www.awesomeserver.com
    +

    Example response:

    +
    OK - Host www.awesomeserver.com stopped
    +
    +

    Persist command

    +

    + Use the persist command to persist a virtual host into + server.xml. Parameters used for the persist command: +

    +
      +
    • String name: Name of the virtual host to be persist. + REQUIRED
    • +
    +

    + This functionality is disabled by default. To enable this option, you must + configure the StoreConfigLifecycleListener listener first. + To do so, add the following listener to your server.xml: +

    +
    <Listener className="org.apache.catalina.storeconfig.StoreConfigLifecycleListener"/>
    +

    Example command:

    +
    curl -u test:test http://localhost:8080/host-manager/text/persist?name=www.awesomeserver.com
    +

    Example response:

    +
    OK - Configuration persisted
    +

    Example manual entry:

    +
    <Host appBase="www.awesomeserver.com" name="www.awesomeserver.com" deployXML="false" unpackWARs="false">
    +</Host>
    +
    +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/html-host-manager-howto.html b/tomcat/docs/html-host-manager-howto.html new file mode 100644 index 0000000..c00d060 --- /dev/null +++ b/tomcat/docs/html-host-manager-howto.html @@ -0,0 +1,212 @@ + +Apache Tomcat 8 (8.5.43) - Host Manager App -- HTML Interface

    Host Manager App -- HTML Interface

    Table of Contents

    Introduction

    +

    + The Tomcat Host Manager application enables you to create, + delete, and otherwise manage virtual hosts within Tomcat. This how-to guide + is best accompanied by the following pieces of documentation: +

    + + +

    + The Tomcat Host Manager application is a part of + Tomcat installation, by default available using the following + context: /host-manager. You can use the host manager in the + following ways: +

    + +
      +
    • + Utilizing the graphical user interface, accessible at: + {server}:{port}/host-manager/html. +
    • +
    • + Utilizing a set of minimal HTTP requests suitable for scripting. + You can access this mode at: + {server}:{port}/host-manager/text. +
    • +
    +

    + Both ways enable you to add, remove, start, and stop virtual hosts. + Changes may be presisted by using the persist command. This + document focuses on the HTML interface. For further information about the + graphical interface, see + Host Manager App -- Text Interface. +

    +

    Configuring Manager Application Access

    +

    The description below uses $CATALINA_HOME to refer the + base Tomcat directory. It is the directory in which you installed + Tomcat, for example C:\tomcat8, or + /usr/share/tomcat8.

    + +

    + The Host Manager application requires a user with one of the following + roles: +

    + +
      +
    • + admin-gui - use this role for the graphical web interface. +
    • +
    • + admin-script - use this role for the scripting web interface. +
    • +
    + +

    + To enable access to the HTML interface of the Host Manager application, + either grant your Tomcat user the appropriate role, or create a new one with + the correct role. For example, open + ${CATALINA_BASE}/conf/tomcat-users.xml and enter the following: +

    +
    <user username="test" password="chang3m3N#w" roles="admin-gui"/>
    +

    + No further settings is needed. When you now access + {server}:{port}/host-manager/html,you are able to + log in with the created credentials. +

    +

    + Note that in case you retrieve your users using the + DataSourceRealm, JDBCRealm, or + JNDIRealm mechanism, add the appropriate role in the database + or the directory server respectively. +

    +

    Interface Description

    +

    The interface is divided into six sections:

    +
      +
    • Message - Displays success and failure messages.
    • +
    • Host Manager - Provides basic Host Manager operations + , like list and help.
    • +
    • Host name - Provides a list of virtual Host Names and + enables you to operate them.
    • +
    • Add Virtual Host - Enables you to add a new Virtual + Host.
    • +
    • Persist configuration - Enables you to persist your + current Virtual Hosts.
    • +
    • Server Information - Information about the Tomcat + server.
    • +
    +

    Message

    + +

    + Displays information about the success or failure of the last Host Manager + command you performed: +

    +
      +
    • Success: OK is displayed + and may be followed by a success message.
    • +
    • Failure: FAIL + is displayed followed by an error message.
    • +
    +

    + Note that the console of your Tomcat server may reveal more information + about each command. +

    +

    Host Manager

    + +

    The Host Manager section enables you to:

    +
      +
    • List Virtual Hosts - Refresh a list of + currently-configured virtual hosts.
    • +
    • HTML Host Manager Help - A documentation link.
    • +
    • Host Manager Help - A documentation link.
    • +
    • Server Status - A link to the Manager + application. Note that you user must have sufficient permissions to access + the application.
    • +
    +

    Host Name

    + +

    The Host name section contains a list of currently-configured virtual host + names. It enables you to:

    +
      +
    • View the host names
    • +
    • View the host name aliases
    • +
    • Perform basic commands, that is start, + stop, and remove.
    • +
    +

    Add Virtual Host

    + +

    The Add Virtual Host section enables you to add a virtual host using a + graphical interface. For a description of each property, see the + Host Manager App -- Text Interface + documentation. Note that any configuration added via this interface is + non-persistent.

    +

    Persist Configuration

    + +

    The Persist Configuration section enables you to persist your current + configuration into the server.xml file.

    + +

    This functionality is disabled by default. To enable this option, you must + configure the StoreConfigLifecycleListener listener first. + To do so, add the following listener to your server.xml:

    +
    <Listener className="org.apache.catalina.storeconfig.StoreConfigLifecycleListener"/>
    + +

    After you configure the listener, click All to make your + configuration persistent.

    +

    Server Information

    +

    + Provides a basic information about the currently-running Tomcat instance, + the JVM, and the underlying operating system. +

    +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/html-manager-howto.html b/tomcat/docs/html-manager-howto.html new file mode 100644 index 0000000..2432ce5 --- /dev/null +++ b/tomcat/docs/html-manager-howto.html @@ -0,0 +1,537 @@ + +Apache Tomcat 8 (8.5.43) - Tomcat Web Application Manager How To

    Tomcat Web Application Manager How To

    Table of Contents

    Introduction

    + +

    In many production environments it is very useful to have the capability +to manage your web applications without having to shut down and restart +Tomcat. This document is for the HTML web interface to the web application +manager.

    + +

    The interface is divided into six sections:

    +
      +
    • Message - Displays success and failure messages.
    • +
    • Manager - General manager operations like list and + help.
    • +
    • Applications - List of web applications and + commands.
    • +
    • Deploy - Deploying web applications.
    • +
    • Diagnostics - Identifying potential problems.
    • +
    • Server Information - Information about the Tomcat + server.
    • +
    + +

    Message

    + +

    +Displays information about the success or failure of the last web application +manager command you performed. If it succeeded OK is displayed +and may be followed by a success message. If it failed FAIL +is displayed followed by an error message. Common failure messages are +documented below for each command. The complete list of failure messages for +each command can be found in the manager web +application documentation. +

    + +

    Manager

    + +

    The Manager section has three links:

    +
      +
    • List Applications - Redisplay a list of web + applications.
    • +
    • HTML Manager Help - A link to this document.
    • +
    • Manager Help - A link to the comprehensive Manager + App HOW TO.
    • +
    + +

    Applications

    + +

    The Applications section lists information about all the installed web +applications and provides links for managing them. For each web application +the following is displayed:

    +
      +
    • Path - The web application context path.
    • +
    • Display Name - The display name for the web application + if it has one configured in its "web.xml" file.
    • +
    • Running - Whether the web application is running and + available (true), or not running and unavailable (false).
    • +
    • Sessions - The number of active sessions for remote + users of this web application. The number of sessions is a link which + when submitted displays more details about session usage by the web + application in the Message box.
    • +
    • Commands - Lists all commands which can be performed on + the web application. Only those commands which can be performed will be + listed as a link which can be submitted. No commands can be performed on + the manager web application itself. The following commands can be + performed: +
        +
      • Start - Start a web application which had been + stopped.
      • +
      • Stop - Stop a web application which is currently + running and make it unavailable.
      • +
      • Reload - Reload the web application so that new + ".jar" files in /WEB-INF/lib/ or new classes in + /WEB-INF/classes/ can be used.
      • +
      • Undeploy - Stop and then remove this web + application from the server.
      • +
      +
    • +
    + +

    Start

    + +

    Signal a stopped application to restart, and make itself available again. +Stopping and starting is useful, for example, if the database required by +your application becomes temporarily unavailable. It is usually better to +stop the web application that relies on this database rather than letting +users continuously encounter database exceptions.

    + +

    If this command succeeds, you will see a Message like this:

    +
    OK - Started application at context path /examples
    + +

    Otherwise, the Message will start with FAIL and include an +error message. Possible causes for problems include:

    +
      +
    • Encountered exception +

      An exception was encountered trying to start the web application. + Check the Tomcat logs for the details.

      +
    • +
    • Invalid context path was specified +

      The context path must start with a slash character, unless you are + referencing the ROOT web application -- in which case the context path + must be a zero-length string.

      +
    • +
    • No context exists for path /foo +

      There is no deployed application on the context path + that you specified.

      +
    • +
    • No context path was specified +

      + The path parameter is required. +

      +
    • +
    + +
    + +

    Stop

    + +

    Signal an existing application to make itself unavailable, but leave it +deployed. Any request that comes in while an application is +stopped will see an HTTP error 404, and this application will show as +"stopped" on a list applications command.

    + +

    If this command succeeds, you will see a Message like this:

    +
    OK - Stopped application at context path /examples
    + +

    Otherwise, the Message will start with FAIL and include an +error message. Possible causes for problems include:

    +
      +
    • Encountered exception +

      An exception was encountered trying to stop the web application. + Check the Tomcat logs for the details.

      +
    • +
    • Invalid context path was specified +

      The context path must start with a slash character, unless you are + referencing the ROOT web application -- in which case the context path + must be a zero-length string.

      +
    • +
    • No context exists for path /foo +

      There is no deployed application on the context path + that you specified.

      +
    • +
    • No context path was specified +

      + The path parameter is required. +

      +
    • +
    + +
    + +

    Reload

    + +

    Signal an existing application to shut itself down and reload. This can +be useful when the web application context is not reloadable and you have +updated classes or property files in the /WEB-INF/classes +directory or when you have added or updated jar files in the +/WEB-INF/lib directory. +

    +

    NOTE: The /WEB-INF/web.xml +web application configuration file is not checked on a reload; +the previous web.xml configuration is used. +If you have made changes to your web.xml file you must stop +then start the web application. +

    + +

    If this command succeeds, you will see a Message like this:

    +
    
    +OK - Reloaded application at context path /examples
    +
    + +

    Otherwise, the Message will start with FAIL and include an +error message. Possible causes for problems include:

    +
      +
    • Encountered exception +

      An exception was encountered trying to restart the web application. + Check the Tomcat logs for the details.

      +
    • +
    • Invalid context path was specified +

      The context path must start with a slash character, unless you are + referencing the ROOT web application -- in which case the context path + must be a zero-length string.

      +
    • +
    • No context exists for path /foo +

      There is no deployed application on the context path + that you specified.

      +
    • +
    • No context path was specified +

      The path parameter is required.

      +
    • +
    • Reload not supported on WAR deployed at path /foo +

      Currently, application reloading (to pick up changes to the classes or + web.xml file) is not supported when a web application is + installed directly from a WAR file, which happens when the host is + configured to not unpack WAR files. As it only works when the web + application is installed from an unpacked directory, if you are using + a WAR file, you should undeploy and then deploy + the application again to pick up your changes.

      +
    • +
    + +
    + +

    Undeploy

    + +

    WARNING - This command will delete the +contents of the web application directory and/or ".war" file if it exists within +the appBase directory (typically "webapps") for this virtual host +. The web application temporary work directory is also deleted. If +you simply want to take an application out of service, you should use the +/stop command instead.

    + +

    Signal an existing application to gracefully shut itself down, and then +remove it from Tomcat (which also makes this context path available for +reuse later). This command is the logical opposite of the +/deploy Ant command, and the related deploy features available +in the HTML manager.

    + +

    If this command succeeds, you will see a Message like this:

    +
    OK - Undeployed application at context path /examples
    + +

    Otherwise, the Message will start with FAIL and include an +error message. Possible causes for problems include:

    +
      +
    • Encountered exception +

      An exception was encountered trying to undeploy the web application. + Check the Tomcat logs for the details.

      +
    • +
    • Invalid context path was specified +

      The context path must start with a slash character, unless you are + referencing the ROOT web application -- in which case the context path + must be a zero-length string.

      +
    • +
    • No context exists for path /foo +

      There is no deployed application on the context path + that you specified.

      +
    • +
    • No context path was specified + The path parameter is required. +
    • +
    + +
    + +

    Deploy

    + +

    Web applications can be deployed using files or directories located +on the Tomcat server or you can upload a web application archive (WAR) +file to the server.

    + +

    To install an application, fill in the appropriate fields for the type +of install you want to do and then submit it using the Install +button.

    + +

    Deploy directory or WAR file located on server

    + +

    Deploy and start a new web application, attached to the specified Context +Path: (which must not be in use by any other web application). +This command is the logical opposite of the Undeploy command.

    + +

    There are a number of different ways the deploy command can be used.

    + +

    Deploy a Directory or WAR by URL

    + +

    Install a web application directory or ".war" file located on the Tomcat +server. If no Context Path is specified, the directory name or the +war file name without the ".war" extension is used as the path. The +WAR or Directory URL specifies a URL (including the file: +scheme) for either a directory or a web application archive (WAR) file. The +supported syntax for a URL referring to a WAR file is described on the Javadocs +page for the java.net.JarURLConnection class. Use only URLs that +refer to the entire WAR file.

    + +

    In this example the web application located in the directory +C:\path\to\foo on the Tomcat server (running on Windows) +is deployed as the web application context named /footoo.

    +
    Context Path: /footoo
    +WAR or Directory URL: file:C:/path/to/foo
    +
    + + +

    In this example the ".war" file /path/to/bar.war on the +Tomcat server (running on Unix) is deployed as the web application +context named /bar. Notice that there is no path +parameter so the context path defaults to the name of the web application +archive file without the ".war" extension.

    +
    WAR or Directory URL: jar:file:/path/to/bar.war!/
    + +
    + +

    Deploy a Directory or War from the Host appBase

    + +

    Install a web application directory or ".war" file located in your Host +appBase directory. If no Context Path is specified the directory name +or the war file name without the ".war" extension is used as the path.

    + +

    In this example the web application located in a subdirectory named +foo in the Host appBase directory of the Tomcat server is +deployed as the web application context named /foo. Notice +that there is no path parameter so the context path defaults +to the name of the web application directory.

    +
    WAR or Directory URL: foo
    + + +

    In this example the ".war" file bar.war located in your +Host appBase directory on the Tomcat server is deployed as the web +application context named /bartoo.

    +
    Context Path: /bartoo
    +WAR or Directory URL: bar.war
    + +
    + +

    Deploy using a Context configuration ".xml" file

    + +

    If the Host deployXML flag is set to true, you can install a web +application using a Context configuration ".xml" file and an optional +".war" file or web application directory. The Context Path +is not used when installing a web application using a context ".xml" +configuration file.

    + +

    A Context configuration ".xml" file can contain valid XML for a +web application Context just as if it were configured in your +Tomcat server.xml configuration file. Here is an +example for Tomcat running on Windows:

    +
    <Context path="/foobar" docBase="C:\path\to\application\foobar">
    +</Context>
    + + +

    Use of the WAR or Directory URL is optional. When used +to select a web application ".war" file or directory it overrides any +docBase configured in the context configuration ".xml" file.

    + +

    Here is an example of installing an application using a Context +configuration ".xml" file for Tomcat running on Windows.

    +
    XML Configuration file URL: file:C:/path/to/context.xml
    + + +

    Here is an example of installing an application using a Context +configuration ".xml" file and a web application ".war" file located +on the server (Tomcat running on Unix).

    +
    XML Configuration file URL: file:/path/to/context.xml
    +WAR or Directory URL: jar:file:/path/to/bar.war!/
    + +
    +
    + +

    Upload a WAR file to install

    + +

    Upload a WAR file from your local system and install it into the +appBase for your Host. The name of the WAR file without the ".war" +extension is used as the context path name.

    + +

    Use the Browse button to select a WAR file to upload to the +server from your local desktop system.

    + +

    The .WAR file may include Tomcat specific deployment configuration, by +including a Context configuration XML file in +/META-INF/context.xml.

    + +

    Upload of a WAR file could fail for the following reasons:

    +
      +
    • File uploaded must be a .war +

      The upload install will only accept files which have the filename + extension of ".war".

      +
    • +
    • War file already exists on server +

      If a war file of the same name already exists in your Host's + appBase the upload will fail. Either undeploy the existing war file + from your Host's appBase or upload the new war file using a different + name.

      +
    • +
    • File upload failed, no file +

      The file upload failed, no file was received by the server.

      +
    • +
    • Install Upload Failed, Exception: +

      The war file upload or install failed with a Java Exception. + The exception message will be listed.

      +
    • +
    + +
    + +

    Deployment Notes

    + +

    If the Host is configured with unpackWARs=true and you install a war +file, the war will be unpacked into a directory in your Host appBase +directory.

    + +

    If the application war or directory is deployed in your Host appBase +directory and either the Host is configured with autoDeploy=true the Context +path must match the directory name or war file name without the ".war" +extension.

    + +

    For security when untrusted users can manage web applications, the +Host deployXML flag can be set to false. This prevents untrusted users +from installing web applications using a configuration XML file and +also prevents them from installing application directories or ".war" +files located outside of their Host appBase.

    + +
    + +

    Deploy Message

    + +

    If deployment and startup is successful, you will receive a Message +like this:

    +
    OK - Deployed application at context path /foo
    + +

    Otherwise, the Message will start with FAIL and include an +error message. Possible causes for problems include:

    +
      +
    • Application already exists at path /foo +

      The context paths for all currently running web applications must be + unique. Therefore, you must either undeploy the existing web + application using this context path, or choose a different context path + for the new one.

      +
    • +
    • Document base does not exist or is not a readable directory +

      The URL specified by the WAR or Directory URL: field must + identify a directory on this server that contains the "unpacked" version + of a web application, or the absolute URL of a web application archive + (WAR) file that contains this application. Correct the value entered for + the WAR or Directory URL: field.

      +
    • +
    • Encountered exception +

      An exception was encountered trying to start the new web application. + Check the Tomcat logs for the details, but likely explanations include + problems parsing your /WEB-INF/web.xml file, or missing + classes encountered when initializing application event listeners and + filters.

      +
    • +
    • Invalid application URL was specified +

      The URL for the WAR or Directory URL: field that you specified + was not valid. Such URLs must start with file:, and URLs + for a WAR file must end in ".war".

      +
    • +
    • Invalid context path was specified +

      The context path must start with a slash character, unless you are + referencing the ROOT web application -- in which case the context path + must be a "/" string.

      +
    • +
    • Context path must match the directory or WAR file name: +

      If the application war or directory is deployed in your Host appBase + directory and either the Host is configured with autoDeploy=true the Context + path must match the directory name or war file name without the ".war" + extension.

      +
    • +
    • Only web applications in the Host web application directory can + be deployed +

      + If the Host deployXML flag is set to false this error will happen + if an attempt is made to install a web application directory or + ".war" file outside of the Host appBase directory. +

    • +
    + +
    +

    Diagnostics

    + +

    Finding memory leaks

    + +

    The find leaks diagnostic triggers a full garbage collection. It +should be used with extreme caution on production systems.

    + +

    The find leaks diagnostic attempts to identify web applications that have +caused memory leaks when they were stopped, reloaded or undeployed. Results +should always be confirmed +with a profiler. The diagnostic uses additional functionality provided by the +StandardHost implementation. It will not work if a custom host is used that +does not extend StandardHost.

    + +

    This diagnostic will list context paths for the web applications that were +stopped, reloaded or undeployed, but which classes from the previous runs +are still present in memory, thus being a memory leak. If an application +has been reloaded several times, it may be listed several times.

    + +

    Explicitly triggering a full garbage collection from Java code is documented +to be unreliable. Furthermore, depending on the JVM used, there are options to +disable explicit GC triggering, like -XX:+DisableExplicitGC. +If you want to make sure, that the diagnostics were successfully running a full GC, +you will need to check using tools like GC logging, JConsole or similar.

    + +
    +

    Server Information

    + +

    This section displays information about Tomcat, the operating system of the +server Tomcat is hosted on, the Java Virtual Machine Tomcat is running in, the +primary host name of the server (may not be the host name used to access Tomcat) +and the primary IP address of the server (may not be the IP address used to +access Tomcat).

    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/images/add.gif b/tomcat/docs/images/add.gif new file mode 100644 index 0000000..0774d07 Binary files /dev/null and b/tomcat/docs/images/add.gif differ diff --git a/tomcat/docs/images/asf-logo.svg b/tomcat/docs/images/asf-logo.svg new file mode 100644 index 0000000..e24cbe5 --- /dev/null +++ b/tomcat/docs/images/asf-logo.svg @@ -0,0 +1,226 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tomcat/docs/images/code.gif b/tomcat/docs/images/code.gif new file mode 100644 index 0000000..d27307b Binary files /dev/null and b/tomcat/docs/images/code.gif differ diff --git a/tomcat/docs/images/cors-flowchart.png b/tomcat/docs/images/cors-flowchart.png new file mode 100644 index 0000000..9abb09d Binary files /dev/null and b/tomcat/docs/images/cors-flowchart.png differ diff --git a/tomcat/docs/images/design.gif b/tomcat/docs/images/design.gif new file mode 100644 index 0000000..f5db0a9 Binary files /dev/null and b/tomcat/docs/images/design.gif differ diff --git a/tomcat/docs/images/docs-stylesheet.css b/tomcat/docs/images/docs-stylesheet.css new file mode 100644 index 0000000..768e2ed --- /dev/null +++ b/tomcat/docs/images/docs-stylesheet.css @@ -0,0 +1,303 @@ +@charset "utf-8"; +/* + 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. +*/ + +/* Fonts */ +@import url("fonts/fonts.css"); + +/* General style */ + +h1, h2, h3, h4, h5, h6, th { + font-weight: 600; +} + +body { + margin: 0; +} + +body, input { + font-family: 'Open Sans', sans-serif; + font-size: 10.5pt; +} + +code, pre { + font-family: Consolas, monospace; +} + +img { + border: 0; +} + +table { + border-collapse: collapse; + text-align: left; +} +table *:not(table) { + /* Prevent border-collapsing for table child elements like
    */ + border-collapse: separate; +} + +th { + text-align: left; +} + +main { + /* Remove this once all IEs support
    element */ + display: block; +} + + +/* Layout */ + +#wrapper { + min-width: 400px; +} + +#header { + border-bottom: 1px solid #bbb; +} + +@media not print { + #header { + box-shadow: 0 0 7px #aaa; + } +} + +#header > div { + padding-left: 15px; + padding-right: 15px; + + /* Work-around for old browsers: */ + background-color: #F8F3E4; + background: linear-gradient(to bottom, #ffffff -10%, #F8F3E4 100%); + position: relative; +} + +#header .logo { + float: left; + padding-top: 10px; + min-width: 190px; +} + +#header .logo img{ + /* To avoid that the Font Descender being added to the parent div's height */ + vertical-align: middle; +} + +#header .asfLogo { + float: right; + position: relative; + top: 8px; +} + +#header h1 { + margin-top: 0.6em; + margin-bottom: 0; +} + +#header .versionInfo { + font-size: 13pt; + margin-bottom: 1em; +} + +#middle { + display: table; + table-layout: fixed; + margin: 0; + width: 100%; +} +#middle > div { display: table-row; } +#middle > div > div { display: table-cell; vertical-align: top; } + + + +#mainLeft { + width: 190px; +} + +#mainLeft > div { + margin-top: -1px; /* to overwrite border of element above */ + padding-left: 16px; + padding-right: 14px; + padding-top: 6px; + padding-bottom: 15px; + background-color: #F8F3E4; + border-right: 1px solid #bbb; + border-bottom: 1px solid #bbb; + font-size: 10pt; + border-bottom-right-radius: 20px; + box-shadow: 0 0 5px #aaa; +} + +#mainLeft h2 { + margin-bottom: 0.2em; + font-size: 1.2em; +} + +#mainLeft ul { + padding: 0; + margin: 0; + list-style-type: none; +} + +#mainLeft ul a { + text-indent: -0.6em; + padding-left: 1.4em; + display: block; + text-decoration: none; + color: #444; +} +#mainLeft ul a:hover { + color: #000; + background-color: #D1c9b9; +} + +#mainRight { + padding-left: 14px; + padding-right: 20px; + +} + +#footer { + margin-top: 30px; + padding-top: 20px; + padding-bottom: 20px; + padding-left: 20px; + padding-right: 20px; + border-top: 1px solid #ccc; + color: #444; + text-align: center; + /* font-style: italic; */ + font-size: 9pt; +} + + +/* Content */ + +#content div.text { + padding-left: 1em; + padding-left: 1em; +} + +#content h3, #content h4, #content h5, #content h6 { + padding-left: 5px; + padding-right: 5px; + background-color: #eaeaea; +} + +@media not print { + #content h3, #content h4, #content h5, #content h6 { + border: 1px solid #ccc; + border-radius: 4px; + } +} + +#content h4, #content h5, #content h6 { + background-color: #f6f6f6; +} + +code { + background-color: rgb(224,255,255); +} + +div.codeBox pre code, code.attributeName, code.propertyName, code.noHighlight, .noHighlight code { + background-color: transparent; +} +div.codeBox { + overflow: auto; + margin: 1em 0; +} +div.codeBox pre { + margin: 0; + padding: 4px; + border: 1px solid #999; + border-radius: 5px; + background-color: #eff8ff; + display: table; /* To prevent
    s from taking the complete available width. */
    +  /*
    +  When it is officially supported, use the following CSS instead of display: table
    +  to prevent big 
    s from exceeding the browser window:
    +  max-width: available;
    +  width: min-content;
    +  */
    +}
    +
    +div.codeBox pre.wrap {
    +  white-space: pre-wrap;
    +}
    +
    +
    +table.defaultTable tr, table.detail-table tr {
    +    border: 1px solid #CCC;
    +}
    +
    +table.defaultTable tr:nth-child(even), table.detail-table tr:nth-child(even) {
    +    background-color: #FAFBFF;
    +}
    +
    +table.defaultTable tr:nth-child(odd), table.detail-table tr:nth-child(odd) {
    +    background-color: #EEEFFF;
    +}
    +
    +table.defaultTable th, table.detail-table th {
    +  background-color: #88b;
    +  color: #fff;
    +}
    +
    +table.defaultTable th, table.defaultTable td, table.detail-table th, table.detail-table td {
    +  padding: 5px 8px;
    +}
    +
    +
    +p.notice {
    +  border: 1px solid rgb(255, 0, 0);
    +  background-color: rgb(238, 238, 238);
    +  color: rgb(0, 51, 102);
    +  padding: 0.5em;
    +  margin: 1em 2em 1em 1em;
    +}
    +
    +
    +/* Changelog-Styles */
    +
    +ul.changelog {
    +  padding-left: 1em;
    +  list-style-type: none;
    +}
    +
    +ul.changelog  li{
    +  padding-top: 5px;
    +  padding-bottom: 5px;
    +}
    +
    +ul.changelog img {
    +  vertical-align: middle
    +}
    +
    +
    +/* Printer-only Styles */
    +@media print {
    +    .noPrint { display: none; }
    +    #middle > div > div#mainLeft { display: none; }
    +    a { color: inherit; text-decoration: none; }
    +}
    +
    +/* Fix for Comments section which contains a 

    */ +#comments_thread h1, #comments_thread h2, #comments_thread h3, #comments_thread h4, #comments_thread h5, #comments_thread h6 { + border: none; + background-color: transparent; +} \ No newline at end of file diff --git a/tomcat/docs/images/docs.gif b/tomcat/docs/images/docs.gif new file mode 100644 index 0000000..d64a4a1 Binary files /dev/null and b/tomcat/docs/images/docs.gif differ diff --git a/tomcat/docs/images/fix.gif b/tomcat/docs/images/fix.gif new file mode 100644 index 0000000..d59ad64 Binary files /dev/null and b/tomcat/docs/images/fix.gif differ diff --git a/tomcat/docs/images/fonts/OpenSans400.woff b/tomcat/docs/images/fonts/OpenSans400.woff new file mode 100644 index 0000000..55b25f8 Binary files /dev/null and b/tomcat/docs/images/fonts/OpenSans400.woff differ diff --git a/tomcat/docs/images/fonts/OpenSans400italic.woff b/tomcat/docs/images/fonts/OpenSans400italic.woff new file mode 100644 index 0000000..cedefb8 Binary files /dev/null and b/tomcat/docs/images/fonts/OpenSans400italic.woff differ diff --git a/tomcat/docs/images/fonts/OpenSans600.woff b/tomcat/docs/images/fonts/OpenSans600.woff new file mode 100644 index 0000000..e83bb33 Binary files /dev/null and b/tomcat/docs/images/fonts/OpenSans600.woff differ diff --git a/tomcat/docs/images/fonts/OpenSans600italic.woff b/tomcat/docs/images/fonts/OpenSans600italic.woff new file mode 100644 index 0000000..983bb33 Binary files /dev/null and b/tomcat/docs/images/fonts/OpenSans600italic.woff differ diff --git a/tomcat/docs/images/fonts/OpenSans700.woff b/tomcat/docs/images/fonts/OpenSans700.woff new file mode 100644 index 0000000..27619e7 Binary files /dev/null and b/tomcat/docs/images/fonts/OpenSans700.woff differ diff --git a/tomcat/docs/images/fonts/OpenSans700italic.woff b/tomcat/docs/images/fonts/OpenSans700italic.woff new file mode 100644 index 0000000..e12c3a9 Binary files /dev/null and b/tomcat/docs/images/fonts/OpenSans700italic.woff differ diff --git a/tomcat/docs/images/fonts/fonts.css b/tomcat/docs/images/fonts/fonts.css new file mode 100644 index 0000000..fa306fc --- /dev/null +++ b/tomcat/docs/images/fonts/fonts.css @@ -0,0 +1,54 @@ +@charset "utf-8"; +/* + 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. +*/ + +@font-face { + font-family: 'Open Sans'; + font-style: normal; + font-weight: 400; + src: local('Open Sans'), local('OpenSans'), url('OpenSans400.woff') format('woff'); +} +@font-face { + font-family: 'Open Sans'; + font-style: italic; + font-weight: 400; + src: local('Open Sans Italic'), local('OpenSans-Italic'), url('OpenSans400italic.woff') format('woff'); +} +@font-face { + font-family: 'Open Sans'; + font-style: normal; + font-weight: 600; + src: local('Open Sans Semibold'), local('OpenSans-Semibold'), url('OpenSans600.woff') format('woff'); +} +@font-face { + font-family: 'Open Sans'; + font-style: italic; + font-weight: 600; + src: local('Open Sans Semibold Italic'), local('OpenSans-SemiboldItalic'), url('OpenSans600italic.woff') format('woff'); +} +@font-face { + font-family: 'Open Sans'; + font-style: normal; + font-weight: 700; + src: local('Open Sans Bold'), local('OpenSans-Bold'), url('OpenSans700.woff') format('woff'); +} +@font-face { + font-family: 'Open Sans'; + font-style: italic; + font-weight: 700; + src: local('Open Sans Bold Italic'), local('OpenSans-BoldItalic'), url('OpenSans700italic.woff') format('woff'); +} \ No newline at end of file diff --git a/tomcat/docs/images/tomcat.gif b/tomcat/docs/images/tomcat.gif new file mode 100644 index 0000000..f2aa6f8 Binary files /dev/null and b/tomcat/docs/images/tomcat.gif differ diff --git a/tomcat/docs/images/tomcat.png b/tomcat/docs/images/tomcat.png new file mode 100644 index 0000000..209b07f Binary files /dev/null and b/tomcat/docs/images/tomcat.png differ diff --git a/tomcat/docs/images/update.gif b/tomcat/docs/images/update.gif new file mode 100644 index 0000000..31e22ab Binary files /dev/null and b/tomcat/docs/images/update.gif differ diff --git a/tomcat/docs/images/void.gif b/tomcat/docs/images/void.gif new file mode 100644 index 0000000..e565824 Binary files /dev/null and b/tomcat/docs/images/void.gif differ diff --git a/tomcat/docs/index.html b/tomcat/docs/index.html new file mode 100644 index 0000000..8142cb9 --- /dev/null +++ b/tomcat/docs/index.html @@ -0,0 +1,235 @@ + +Apache Tomcat 8 (8.5.43) - Documentation Index

    Documentation Index

    Introduction

    + +

    This is the top-level entry point of the documentation bundle for the +Apache Tomcat Servlet/JSP container. Apache Tomcat version +8.5 implements the Servlet 3.1 and JavaServer Pages 2.3 +specifications from the +Java Community Process, and includes many +additional features that make it a useful platform for developing and deploying +web applications and web services.

    + +

    Select one of the links from the navigation menu (to the left) to drill +down to the more detailed documentation that is available. Each available +manual is described in more detail below.

    + +

    Apache Tomcat User Guide

    + +

    The following documents will assist you in downloading and installing +Apache Tomcat, and using many of the Apache Tomcat features.

    + +
      +
    1. Introduction - A + brief, high level, overview of Apache Tomcat.
    2. +
    3. Setup - How to install and run + Apache Tomcat on a variety of platforms.
    4. +
    5. First web application + - An introduction to the concepts of a web application as defined + in the Servlet Specification. Covers basic organization of your web application + source tree, the structure of a web application archive, and an + introduction to the web application deployment descriptor + (/WEB-INF/web.xml).
    6. +
    7. Deployer - + Operating the Apache Tomcat Deployer to deploy, precompile, and validate web + applications.
    8. +
    9. Manager - + Operating the Manager web app to deploy, undeploy, and + redeploy applications while Apache Tomcat is running.
    10. +
    11. Host Manager - + Operating the Host Manager web app to add and remove + virtual hosts while Apache Tomcat is running.
    12. +
    13. Realms and Access Control + - Description of how to configure Realms (databases of users, + passwords, and their associated roles) for use in web applications that + utilize Container Managed Security.
    14. +
    15. Security Manager + - Configuring and using a Java Security Manager to + support fine-grained control over the behavior of your web applications. +
    16. +
    17. JNDI Resources + - Configuring standard and custom resources in the JNDI naming context + that is provided to each web application.
    18. +
    19. + JDBC DataSource + - Configuring a JNDI DataSource with a DB connection pool. + Examples for many popular databases.
    20. +
    21. Classloading + - Information about class loading in Apache Tomcat, including where to place + your application classes so that they are visible.
    22. +
    23. JSPs + - Information about Jasper configuration, as well as the JSP compiler + usage.
    24. +
    25. SSL/TLS - + Installing and configuring SSL/TLS support so that your Apache Tomcat will + serve requests using the https protocol.
    26. +
    27. SSI - + Using Server Side Includes in Apache Tomcat.
    28. +
    29. CGI - + Using CGIs with Apache Tomcat.
    30. +
    31. Proxy Support - + Configuring Apache Tomcat to run behind a proxy server (or a web server + functioning as a proxy server).
    32. +
    33. MBeans Descriptors - + Configuring MBean descriptors files for custom components.
    34. +
    35. Default Servlet - + Configuring the default servlet and customizing directory listings.
    36. +
    37. Apache Tomcat Clustering - + Enable session replication in a Apache Tomcat environment.
    38. +
    39. Balancer - + Configuring, using, and extending the load balancer application.
    40. +
    41. Connectors - + Connectors available in Apache Tomcat, and native web server integration.
    42. +
    43. Monitoring and Management - + Enabling JMX Remote support, and using tools to monitor and manage Apache Tomcat.
    44. +
    45. Logging - + Configuring logging in Apache Tomcat.
    46. +
    47. Apache Portable Runtime - + Using APR to provide superior performance, scalability and better + integration with native server technologies.
    48. +
    49. Virtual Hosting - + Configuring virtual hosting in Apache Tomcat.
    50. +
    51. Advanced IO - + Extensions available over regular, blocking IO.
    52. +
    53. Additional Components - + Obtaining additional, optional components.
    54. +
    55. Using Tomcat libraries with Maven - + Obtaining Tomcat jars through Maven.
    56. +
    57. Security Considerations - + Options to consider when securing an Apache Tomcat installation.
    58. +
    59. Windows Service - + Running Tomcat as a service on Microsoft Windows.
    60. +
    61. Windows Authentication - + Configuring Tomcat to use integrated Windows authentication.
    62. +
    63. High Concurrency JDBC Pool - + Configuring Tomcat to use an alternative JDBC pool.
    64. +
    65. WebSocket support - + Developing WebSocket applications for Apache Tomcat.
    66. +
    67. URL rewrite - + Using the regexp based rewrite valve for conditional URL and host rewrite.
    68. + +
    + +

    Reference

    + +

    The following documents are aimed at System Administrators who +are responsible for installing, configuring, and operating an Apache Tomcat server. +

    + + +

    Apache Tomcat Developers

    + +

    The following documents are for Java developers who wish to contribute to +the development of the Apache Tomcat project.

    +
      +
    • Building from Source - + Details the steps necessary to download Apache Tomcat source code (and the + other packages that it depends on), and build a binary distribution from + those sources. +
    • +
    • Changelog - Details the + changes made to Apache Tomcat. +
    • +
    • Status - + Apache Tomcat development status. +
    • +
    • Developers - List of active + Apache Tomcat contributors. +
    • +
    • Functional Specifications + - Requirements specifications for features of the Catalina servlet + container portion of Apache Tomcat.
    • +
    • Javadocs + - Javadoc API documentation for Apache Tomcat's internals.
    • +
    • Apache Tomcat Architecture + - Documentation of the Apache Tomcat Server Architecture.
    • +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/introduction.html b/tomcat/docs/introduction.html new file mode 100644 index 0000000..db88bf6 --- /dev/null +++ b/tomcat/docs/introduction.html @@ -0,0 +1,300 @@ + +Apache Tomcat 8 (8.5.43) - Introduction

    Introduction

    Table of Contents

    Introduction

    + +

    For administrators and web developers alike, there are some important bits +of information you should familiarize yourself with before starting out. This +document serves as a brief introduction to some of the concepts and +terminology behind the Tomcat container. As well, where to go when you need +help.

    + +

    Terminology

    + +

    In the course of reading these documents, you will run across a number of +terms; some specific to Tomcat, and others defined by the +Servlet and +JSP specifications.

    + +
      +
    • Context - In a nutshell, a Context is a + web application.
    • +
    +

    That is it. If you find any more terms we need to add to this section, please +do let us know.

    + +

    Directories and Files

    + +

    These are some of the key tomcat directories:

    + +
      +
    • /bin - Startup, shutdown, and other scripts. The + *.sh files (for Unix systems) are functional duplicates of + the *.bat files (for Windows systems). Since the Win32 + command-line lacks certain functionality, there are some additional + files in here.
    • +
    • /conf - Configuration files and related DTDs. The most + important file in here is server.xml. It is the main configuration file + for the container.
    • +
    • /logs - Log files are here by default.
    • +
    • /webapps - This is where your webapps go.
    • +
    + +

    CATALINA_HOME and CATALINA_BASE

    +

    Throughout the documentation, there are references to the two following + properties: +

      +
    • + CATALINA_HOME: Represents the root of your Tomcat + installation, for example /home/tomcat/apache-tomcat-9.0.10 + or C:\Program Files\apache-tomcat-9.0.10. +
    • +
    • + CATALINA_BASE: Represents the root of a runtime + configuration of a specific Tomcat instance. If you want to have + multiple Tomcat instances on one machine, use the CATALINA_BASE + property. +
    • +
    +

    +

    + If you set the properties to different locations, the CATALINA_HOME location + contains static sources, such as .jar files, or binary files. + The CATALINA_BASE location contains configuration files, log files, deployed + applications, and other runtime requirements. +

    +

    Why Use CATALINA_BASE

    +

    + By default, CATALINA_HOME and CATALINA_BASE point to the same directory. + Set CATALINA_BASE manually when you require running multiple Tomcat + instances on one machine. Doing so provides the following benefits: +

    +
      +
    • + Easier management of upgrading to a newer version of Tomcat. Because all + instances with single CATALINA_HOME location share one set of + .jar files and binary files, you can easily upgrade the files + to newer version and have the change propagated to all Tomcat instances + using the same CATALIA_HOME directory. +
    • +
    • + Avoiding duplication of the same static .jar files. +
    • +
    • + The possibility to share certain settings, for example the setenv shell + or bat script file (depending on your operating system). +
    • +
    +
    +

    Contents of CATALINA_BASE

    +

    + Before you start using CATALINA_BASE, first consider and create the + directory tree used by CATALINA_BASE. Note that if you do not create + all the recommended directories, Tomcat creates the directories + automatically. If it fails to create the necessary directory, for example + due to permission issues, Tomcat will either fail to start, or may not + function correctly. +

    +

    + Consider the following list of directories: +

      +
    • +

      + The bin directory with the setenv.sh, + setenv.bat, and tomcat-juli.jar files. +

      +

      + Recommended: No. +

      +

      + Order of lookup: CATALINA_BASE is checked first; fallback is provided + to CATALINA_HOME. +

      +
    • +
    • +

      + The lib directory with further resources to be added on + classpath. +

      +

      + Recommended: Yes, if your application depends on external libraries. +

      +

      + Order of lookup: CATALINA_BASE is checked first; CATALINA_HOME is + loaded second. +

      +
    • +
    • +

      + The logs directory for instance-specific log files. +

      +

      + Recommended: Yes. +

      +
    • +
    • +

      + The webapps directory for automatically loaded web + applications. +

      +

      + Recommended: Yes, if you want to deploy applications. +

      +

      + Order of lookup: CATALINA_BASE only. +

      +
    • +
    • +

      + The work directory that contains temporary working + directories for the deployed web applications. +

      +

      + Recommended: Yes. +

      +
    • +
    • +

      + The temp directory used by the JVM for temporary files. +

      +

      + Recommended: Yes. +

      +
    • +
    +

    +

    + We recommend you not to change the tomcat-juli.jar file. + However, in case you require your own logging implementation, you can + replace the tomcat-juli.jar file in a CATALINA_BASE location + for the specific Tomcat instance. +

    +

    + We also recommend you copy all configuration files from the + CATALINA_HOME/conf directory into the + CATALINA_BASE/conf/ directory. In case a configuration file + is missing in CATALINA_BASE, there is no fallback to CATALINA_HOME. + Consequently, this may cause failure. +

    +

    + At minimum, CATALINA_BASE must contain: +

      +
    • conf/server.xml
    • +
    • conf/web.xml
    • +
    + That includes the conf directory. Otherwise, Tomcat fails + to start, or fails to function properly. +

    +

    + For advanced configuration information, see the + + RUNNING.txt + file. +

    +
    +

    How to Use CATALINA_BASE

    +

    + The CATALINA_BASE property is an environment variable. You can set it + before you execute the Tomcat start script, for example: +

      +
    • On Unix: CATALINA_BASE=/tmp/tomcat_base1 bin/catalina.sh start
    • +
    • On Windows: CATALINA_BASE=C:\tomcat_base1 bin/catalina.bat start
    • +
    +

    +
    +

    Configuring Tomcat

    + +

    This section will acquaint you with the basic information used during +the configuration of the container.

    + +

    All of the information in the configuration files is read at startup, +meaning that any change to the files necessitates a restart of the container. +

    + +

    Where to Go for Help

    + +

    While we've done our best to ensure that these documents are clearly +written and easy to understand, we may have missed something. Provided +below are various web sites and mailing lists in case you get stuck.

    + +

    Keep in mind that some of the issues and solutions vary between the +major versions of Tomcat. As you search around the web, there will be +some documentation that is not relevant to Tomcat 8, but +only to earlier versions.

    + +
      +
    • Current document - most documents will list potential hangups. Be sure + to fully read the relevant documentation as it will save you much time + and effort. There's nothing like scouring the web only to find out that + the answer was right in front of you all along!
    • +
    • Tomcat FAQ
    • +
    • Tomcat WIKI
    • +
    • Tomcat FAQ at jGuru
    • +
    • Tomcat mailing list archives - numerous sites archive the Tomcat mailing + lists. Since the links change over time, clicking here will search + Google. +
    • +
    • The TOMCAT-USER mailing list, which you can subscribe to + here. If you don't + get a reply, then there's a good chance that your question was probably + answered in the list archives or one of the FAQs. Although questions + about web application development in general are sometimes asked and + answered, please focus your questions on Tomcat-specific issues.
    • +
    • The TOMCAT-DEV mailing list, which you can subscribe to + here. This list is + reserved for discussions about the development of Tomcat + itself. Questions about Tomcat configuration, and the problems you run + into while developing and running applications, will normally be more + appropriate on the TOMCAT-USER list instead.
    • +
    + +

    And, if you think something should be in the docs, by all means let us know +on the TOMCAT-DEV list.

    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/jasper-howto.html b/tomcat/docs/jasper-howto.html new file mode 100644 index 0000000..87cc43d --- /dev/null +++ b/tomcat/docs/jasper-howto.html @@ -0,0 +1,407 @@ + +Apache Tomcat 8 (8.5.43) - Jasper 2 JSP Engine How To

    Jasper 2 JSP Engine How To

    Table of Contents

    Introduction

    + +

    Tomcat 8.5 uses the Jasper 2 JSP Engine to implement +the JavaServer Pages 2.3 +specification.

    + +

    Jasper 2 has been redesigned to significantly improve performance over +the original Jasper. In addition to general code improvements the following +changes were made:

    +
      +
    • JSP Custom Tag Pooling - The java objects instantiated +for JSP Custom Tags can now be pooled and reused. This significantly boosts +the performance of JSP pages which use custom tags.
    • +
    • Background JSP compilation - If you make a change to +a JSP page which had already been compiled Jasper 2 can recompile that +page in the background. The previously compiled JSP page will still be +available to serve requests. Once the new page has been compiled +successfully it will replace the old page. This helps improve availability +of your JSP pages on a production server.
    • +
    • Recompile JSP when included page changes - Jasper 2 +can now detect when a page included at compile time from a JSP has changed +and then recompile the parent JSP.
    • +
    • JDT used to compile JSP pages - The +Eclipse JDT Java compiler is now used to perform JSP java source code +compilation. This compiler loads source dependencies from the container +classloader. Ant and javac can still be used.
    • +
    + + +

    Jasper is implemented using the servlet class +org.apache.jasper.servlet.JspServlet.

    + +

    Configuration

    + +

    By default Jasper is configured for use when doing web application +development. See the section +Production Configuration for information on configuring Jasper +for use on a production Tomcat server.

    + +

    The servlet which implements Jasper is configured using init parameters +in your global $CATALINA_BASE/conf/web.xml. +

    +
      +
    • checkInterval - If development is false and checkInterval +is greater than zero, background compiles are enabled. checkInterval is the time +in seconds between checks to see if a JSP page (and its dependent files) needs +to be recompiled. Default 0 seconds.
    • + +
    • classdebuginfo - Should the class file be compiled with +debugging information? true or false, default +true. +
    • + +
    • classpath - Defines the class path to be used to compile +the generated servlets. This parameter only has an effect if the ServletContext +attribute org.apache.jasper.Constants.SERVLET_CLASSPATH is not set. This +attribute is always set when Jasper is used within Tomcat. By default the +classpath is created dynamically based on the current web application.
    • + +
    • compiler - Which compiler Ant should use to compile JSP +pages. The valid values for this are the same as for the compiler attribute of +Ant's +javac +task. If the value is not set, then the default Eclipse JDT Java compiler will +be used instead of using Ant. There is no default value. If this attribute is +set then setenv.[sh|bat] should be used to add +ant.jar, ant-launcher.jar and tools.jar +to the CLASSPATH environment variable.
    • + +
    • compilerSourceVM - What JDK version are the source files +compatible with? (Default value: 1.7)
    • + +
    • compilerTargetVM - What JDK version are the generated files +compatible with? (Default value: 1.7)
    • + +
    • development - Is Jasper used in development mode? If true, +the frequency at which JSPs are checked for modification may be specified via +the modificationTestInterval parameter.true or false, +default true.
    • + +
    • displaySourceFragment - Should a source fragment be +included in exception messages? true or false, +default true.
    • + +
    • dumpSmap - Should the SMAP info for JSR45 debugging be +dumped to a file? true or false, default +false. false if suppressSmap is true.
    • + +
    • enablePooling - Determines whether tag handler pooling is +enabled. This is a compilation option. It will not alter the behaviour of JSPs +that have already been compiled. true or false, +default true. +
    • + +
    • engineOptionsClass - Allows specifying the Options class +used to configure Jasper. If not present, the default EmbeddedServletOptions +will be used. This option is ignored if running under a SecurityManager. +
    • + +
    • errorOnUseBeanInvalidClassAttribute - Should Jasper issue +an error when the value of the class attribute in an useBean action is not a +valid bean class? true or false, default +true.
    • + +
    • fork - Have Ant fork JSP page compiles so they are +performed in a separate JVM from Tomcat? true or +false, default true.
    • + +
    • genStringAsCharArray - Should text strings be generated as char +arrays, to improve performance in some cases? Default false.
    • + +
    • ieClassId - The class-id value to be sent to Internet +Explorer when using <jsp:plugin> tags. Default +clsid:8AD9C840-044E-11D1-B3E9-00805F499D93.
    • + +
    • javaEncoding - Java file encoding to use for generating +java source files. Default UTF8.
    • + +
    • keepgenerated - Should we keep the generated Java source +code for each page instead of deleting it? true or +false, default true.
    • + +
    • mappedfile - Should we generate static content with one +print statement per input line, to ease debugging? +true or false, default true.
    • + +
    • maxLoadedJsps - The maximum number of JSPs that will be +loaded for a web application. If more than this number of JSPs are loaded, the +least recently used JSPs will be unloaded so that the number of JSPs loaded at +any one time does not exceed this limit. A value of zero or less indicates no +limit. Default -1
    • + +
    • jspIdleTimeout - The amount of time in seconds a JSP can be +idle before it is unloaded. A value of zero or less indicates never unload. +Default -1
    • + +
    • modificationTestInterval - Causes a JSP (and its dependent +files) to not be checked for modification during the specified time interval +(in seconds) from the last time the JSP was checked for modification. A value of +0 will cause the JSP to be checked on every access. Used in development mode +only. Default is 4 seconds.
    • + +
    • recompileOnFail - If a JSP compilation fails should the +modificationTestInterval be ignored and the next access trigger a re-compilation +attempt? Used in development mode only and is disabled by default as compilation +may be expensive and could lead to excessive resource usage.
    • + +
    • scratchdir - What scratch directory should we use when +compiling JSP pages? Default is the work directory for the current web +application. This option is ignored if running under a SecurityManager.
    • + +
    • suppressSmap - Should the generation of SMAP info for JSR45 +debugging be suppressed? true or false, default +false.
    • + +
    • trimSpaces - Should template text that consists entirely of +whitespace be removed? true or false, default +false.
    • + +
    • xpoweredBy - Determines whether X-Powered-By response +header is added by generated servlet. true or false, +default false.
    • + +
    • strictQuoteEscaping - When scriptlet expressions are used +for attribute values, should the rules in JSP.1.6 for the escaping of quote +characters be strictly applied? true or false, default +true.
    • + +
    • quoteAttributeEL - When EL is used in an attribute value +on a JSP page, should the rules for quoting of attributes described in JSP.1.6 +be applied to the expression? true or false, default +true.
    • +
    + +

    The Java compiler from Eclipse JDT in included as the default compiler. It is +an advanced Java compiler which will load all dependencies from the Tomcat class +loader, which will help tremendously when compiling on large installations with +tens of JARs. On fast servers, this will allow sub-second recompilation cycles +for even large JSP pages.

    + +

    Apache Ant, which was used in previous Tomcat releases, can be used instead +of the new compiler by configuring the compiler attribute as explained above. +

    + +

    Known issues

    + +

    As described in + +bug 39089, a known JVM issue, + +bug 6294277, may cause a +java.lang.InternalError: name is too long to represent exception +when compiling very large JSPs. If this is observed then it may be worked around +by using one of the following: +

    +
      +
    • reduce the size of the JSP
    • +
    • disable SMAP generation and JSR-045 support by setting +suppressSmap to true.
    • +
    + +

    Production Configuration

    + +

    The main JSP optimization which can be done is precompilation of JSPs. +However, this might not be possible (for example, when using the +jsp-property-group feature) or practical, in which case the configuration of the +Jasper servlet becomes critical.

    + +

    When using Jasper 2 in a production Tomcat server you should consider making +the following changes from the default configuration.

    +
      +
    • development - To disable on access checks for JSP +pages compilation set this to false.
    • +
    • genStringAsCharArray - To generate slightly more efficient +char arrays, set this to true.
    • +
    • modificationTestInterval - If development has to be set to +true for any reason (such as dynamic generation of JSPs), setting +this to a high value will improve performance a lot.
    • +
    • trimSpaces - To remove useless bytes from the response, +set this to true.
    • +
    + +

    Web Application Compilation

    + +

    Using Ant is the preferred way to compile web applications using JSPC. Note +that when pre-compiling JSPs, SMAP information will only be included in the +final classes if suppressSmap is false and compile is true. +Use the script given below (a similar script is included in the "deployer" +download) to precompile a webapp: +

    + +
    <project name="Webapp Precompilation" default="all" basedir=".">
    +
    +   <import file="${tomcat.home}/bin/catalina-tasks.xml"/>
    +
    +   <target name="jspc">
    +
    +    <jasper
    +             validateXml="false"
    +             uriroot="${webapp.path}"
    +             webXmlInclude="${webapp.path}/WEB-INF/generated_web.xml"
    +             outputDir="${webapp.path}/WEB-INF/src" />
    +
    +  </target>
    +
    +  <target name="compile">
    +
    +    <mkdir dir="${webapp.path}/WEB-INF/classes"/>
    +    <mkdir dir="${webapp.path}/WEB-INF/lib"/>
    +
    +    <javac destdir="${webapp.path}/WEB-INF/classes"
    +           debug="on" failonerror="false"
    +           srcdir="${webapp.path}/WEB-INF/src"
    +           excludes="**/*.smap">
    +      <classpath>
    +        <pathelement location="${webapp.path}/WEB-INF/classes"/>
    +        <fileset dir="${webapp.path}/WEB-INF/lib">
    +          <include name="*.jar"/>
    +        </fileset>
    +        <pathelement location="${tomcat.home}/lib"/>
    +        <fileset dir="${tomcat.home}/lib">
    +          <include name="*.jar"/>
    +        </fileset>
    +        <fileset dir="${tomcat.home}/bin">
    +          <include name="*.jar"/>
    +        </fileset>
    +      </classpath>
    +      <include name="**" />
    +      <exclude name="tags/**" />
    +    </javac>
    +
    +  </target>
    +
    +  <target name="all" depends="jspc,compile">
    +  </target>
    +
    +  <target name="cleanup">
    +    <delete>
    +        <fileset dir="${webapp.path}/WEB-INF/src"/>
    +        <fileset dir="${webapp.path}/WEB-INF/classes/org/apache/jsp"/>
    +    </delete>
    +  </target>
    +
    +</project>
    + +

    +The following command line can be used to run the script +(replacing the tokens with the Tomcat base path and the path to the webapp +which should be precompiled): +

    +
    $ANT_HOME/bin/ant -Dtomcat.home=<$TOMCAT_HOME> -Dwebapp.path=<$WEBAPP_PATH>
    + + +

    +Then, the declarations and mappings for the servlets which were generated +during the precompilation must be added to the web application deployment +descriptor. Insert the ${webapp.path}/WEB-INF/generated_web.xml +at the right place inside the ${webapp.path}/WEB-INF/web.xml file. +Restart the web application (using the manager) and test it to verify it is +running fine with precompiled servlets. An appropriate token placed in the +web application deployment descriptor may also be used to automatically +insert the generated servlet declarations and mappings using Ant filtering +capabilities. This is actually how all the webapps distributed with Tomcat +are automatically compiled as part of the build process. +

    + +

    +At the jasper task you can use the option addWebXmlMappings for +automatic merge the ${webapp.path}/WEB-INF/generated_web.xml +with the current web application deployment descriptor at +${webapp.path}/WEB-INF/web.xml. When you want to use Java 6 +features inside your JSP's, add the following javac compiler task attributes: +source="1.6" target="1.6". For live +applications you can also disable debug info with debug="off". +

    + +

    +When you don't want to stop the JSP generation at first JSP syntax error, use +failOnError="false" and with +showSuccess="true" all successful JSP to Java +generation are printed out. Sometimes it is very helpful, when you cleanup the +generate java source files at ${webapp.path}/WEB-INF/src +and the compile JSP servlet classes at +${webapp.path}/WEB-INF/classes/org/apache/jsp. +

    + +

    Hints:

    +
      +
    • When you switch to another Tomcat release, then regenerate and recompile +your JSP's with the new Tomcat version.
    • +
    • Use java system property at server runtime to disable PageContext pooling +org.apache.jasper.runtime.JspFactoryImpl.USE_POOL=false. +and limit the buffering with +org.apache.jasper.runtime.BodyContentImpl.LIMIT_BUFFER=true. Note +that changing from the defaults may affect performance, but it will vary +depending on the application.
    • +
    +

    Optimisation

    +

    +There are a number of extension points provided within Jasper that enable the +user to optimise the behaviour for their environment. +

    + +

    +The first of these extension points is the tag plug-in mechanism. This allows +alternative implementations of tag handlers to be provided for a web application +to use. Tag plug-ins are registered via a tagPlugins.xml file +located under WEB-INF. A sample plug-in for the JSTL is included +with Jasper. +

    + +

    +The second extension point is the Expression Language interpreter. Alternative +interpreters may be configured through the ServletContext. See the +ELInterpreterFactory javadoc for details of how to configure an +alternative EL interpreter. +

    +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/jdbc-pool.html b/tomcat/docs/jdbc-pool.html new file mode 100644 index 0000000..ab9498b --- /dev/null +++ b/tomcat/docs/jdbc-pool.html @@ -0,0 +1,929 @@ + +Apache Tomcat 8 (8.5.43) - The Tomcat JDBC Connection Pool

    The Tomcat JDBC Connection Pool

    Table of Contents

    Introduction

    + +

    The JDBC Connection Pool org.apache.tomcat.jdbc.pool + is a replacement or an alternative to the Apache Commons DBCP + connection pool.

    + +

    So why do we need a new connection pool?

    + +

    Here are a few of the reasons:

    +
      +
    1. Commons DBCP 1.x is single threaded. In order to be thread safe + Commons locks the entire pool for short periods during both object + allocation and object return. Note that this does not apply to + Commons DBCP 2.x.
    2. +
    3. Commons DBCP 1.x can be slow. As the number of logical CPUs grows and + the number of concurrent threads attempting to borrow or return + objects increases, the performance suffers. For highly concurrent + systems the impact can be significant. Note that this does not apply + to Commons DBCP 2.x.
    4. +
    5. Commons DBCP is over 60 classes. tomcat-jdbc-pool core is 8 classes, + hence modifications for future requirement will require much less + changes. This is all you need to run the connection pool itself, the + rest is gravy.
    6. +
    7. Commons DBCP uses static interfaces. This means you have to use the + right version for a given JRE version or you may see + NoSuchMethodException exceptions.
    8. +
    9. It's not worth rewriting over 60 classes, when a connection pool can + be accomplished with a much simpler implementation.
    10. +
    11. Tomcat jdbc pool implements the ability retrieve a connection + asynchronously, without adding additional threads to the library + itself.
    12. +
    13. Tomcat jdbc pool is a Tomcat module, it depends on Tomcat JULI, a + simplified logging framework used in Tomcat.
    14. +
    15. Retrieve the underlying connection using the + javax.sql.PooledConnection interface.
    16. +
    17. Starvation proof. If a pool is empty, and threads are waiting for a + connection, when a connection is returned, the pool will awake the + correct thread waiting. Most pools will simply starve.
    18. +
    + +

    Features added over other connection pool implementations

    +
      +
    1. Support for highly concurrent environments and multi core/cpu systems.
    2. +
    3. Dynamic implementation of interface, will support java.sql and javax.sql interfaces for + your runtime environment (as long as your JDBC driver does the same), even when compiled with a lower version of the JDK.
    4. +
    5. Validation intervals - we don't have to validate every single time we use the connection, we can do this + when we borrow or return the connection, just not more frequent than an interval we can configure.
    6. +
    7. Run-Once query, a configurable query that will be run only once, when the connection to the database is established. + Very useful to setup session settings, that you want to exist during the entire time the connection is established.
    8. +
    9. Ability to configure custom interceptors. + This allows you to write custom interceptors to enhance the functionality. You can use interceptors to gather query stats, + cache session states, reconnect the connection upon failures, retry queries, cache query results, and so on. + Your options are endless and the interceptors are dynamic, not tied to a JDK version of a + java.sql/javax.sql interface.
    10. +
    11. High performance - we will show some differences in performance later on
    12. +
    13. Extremely simple, due to the very simplified implementation, the line count and source file count are very low, compare with c3p0 + that has over 200 source files(last time we checked), Tomcat jdbc has a core of 8 files, the connection pool itself is about half + that. As bugs may occur, they will be faster to track down, and easier to fix. Complexity reduction has been a focus from inception.
    14. +
    15. Asynchronous connection retrieval - you can queue your request for a connection and receive a Future<Connection> back.
    16. +
    17. Better idle connection handling. Instead of closing connections directly, it can still pool connections and sizes the idle pool with a smarter algorithm.
    18. +
    19. You can decide at what moment connections are considered abandoned, is it when the pool is full, or directly at a timeout + by specifying a pool usage threshold. +
    20. +
    21. The abandon connection timer will reset upon a statement/query activity. Allowing a connections that is in use for a long time to not timeout. + This is achieved using the ResetAbandonedTimer +
    22. +
    23. Close connections after they have been connected for a certain time. Age based close upon return to the pool. +
    24. +
    25. Get JMX notifications and log entries when connections are suspected for being abandoned. This is similar to + the removeAbandonedTimeout but it doesn't take any action, only reports the information. + This is achieved using the suspectTimeout attribute.
    26. +
    27. Connections can be retrieved from a java.sql.Driver, javax.sql.DataSource or javax.sql.XADataSource + This is achieved using the dataSource and dataSourceJNDI attributes.
    28. +
    29. XA connection support
    30. +
    + + +

    How to use

    +

    + Usage of the Tomcat connection pool has been made to be as simple as possible, for those of you that are familiar with commons-dbcp, the + transition will be very simple. Moving from other connection pools is also fairly straight forward. +

    +

    Additional features

    +

    The Tomcat connection pool offers a few additional features over what most other pools let you do:

    +
      +
    • initSQL - the ability to run a SQL statement exactly once, when the connection is created
    • +
    • validationInterval - in addition to running validations on connections, avoid running them too frequently.
    • +
    • jdbcInterceptors - flexible and pluggable interceptors to create any customizations around the pool, + the query execution and the result set handling. More on this in the advanced section.
    • +
    • fairQueue - Set the fair flag to true to achieve thread fairness or to use asynchronous connection retrieval
    • +
    +
    +

    Inside the Apache Tomcat Container

    +

    + The Tomcat Connection pool is configured as a resource described in The Tomcat JDBC documentation + With the only difference being that you have to specify the factory attribute and set the value to + org.apache.tomcat.jdbc.pool.DataSourceFactory +

    +
    +

    Standalone

    +

    + The connection pool only has another dependency, and that is on tomcat-juli.jar. + To configure the pool in a stand alone project using bean instantiation, the bean to instantiate is + org.apache.tomcat.jdbc.pool.DataSource. The same attributes (documented below) as you use to configure a connection + pool as a JNDI resource, are used to configure a data source as a bean. +

    +
    +

    JMX

    +

    + The connection pool object exposes an MBean that can be registered. + In order for the connection pool object to create the MBean, the flag jmxEnabled has to be set to true. + This doesn't imply that the pool will be registered with an MBean server, merely that the MBean is created. + In a container like Tomcat, Tomcat itself registers the DataSource with the MBean server, the + org.apache.tomcat.jdbc.pool.DataSource object will then register the actual + connection pool MBean. + If you're running outside of a container, you can register the DataSource yourself under any object name you specify, + and it propagates the registration to the underlying pool. To do this you would call mBeanServer.registerMBean(dataSource.getPool().getJmxPool(),objectname). + Prior to this call, ensure that the pool has been created by calling dataSource.createPool(). +

    +
    + +

    Attributes

    +

    To provide a very simple switch to and from commons-dbcp and tomcat-jdbc-pool, + Most attributes are the same and have the same meaning.

    +

    JNDI Factory and Type

    +
    + Attribute + + Description +
    factory +

    factory is required, and the value should be org.apache.tomcat.jdbc.pool.DataSourceFactory

    +
    type +

    Type should always be javax.sql.DataSource or javax.sql.XADataSource

    +

    Depending on the type a org.apache.tomcat.jdbc.pool.DataSource or a org.apache.tomcat.jdbc.pool.XADataSource will be created.

    +
    +
    + +

    System Properties

    +

    System properties are JVM wide, affect all pools created in the JVM

    +
    + Attribute + + Description +
    org.apache.tomcat.jdbc.pool.onlyAttemptCurrentClassLoader +

    (boolean) Controls classloading of dynamic classes, such as + JDBC drivers, interceptors and validators. If set to + false, default value, the pool will first attempt + to load using the current loader (i.e. the class loader that + loaded the pool classes) and if class loading fails attempt to + load using the thread context loader. Set this value to + true, if you wish to remain backwards compatible + with Apache Tomcat 8.0.8 and earlier, and only attempt the + current loader. + If not set then the default value is false. +

    +
    +
    + +

    Common Attributes

    +

    These attributes are shared between commons-dbcp and tomcat-jdbc-pool, in some cases default values are different.

    +
    + Attribute + + Description +
    defaultAutoCommit +

    (boolean) The default auto-commit state of connections created by this pool. If not set, default is JDBC driver default (If not set then the setAutoCommit method will not be called.)

    +
    defaultReadOnly +

    (boolean) The default read-only state of connections created by this pool. If not set then the setReadOnly method will not be called. (Some drivers don't support read only mode, ex: Informix)

    +
    defaultTransactionIsolation +

    (String) The default TransactionIsolation state of connections created by this pool. One of the following: (see javadoc )

    +
      +
    • NONE
    • +
    • READ_COMMITTED
    • +
    • READ_UNCOMMITTED
    • +
    • REPEATABLE_READ
    • +
    • SERIALIZABLE
    • +
    +

    If not set, the method will not be called and it defaults to the JDBC driver.

    +
    defaultCatalog +

    (String) The default catalog of connections created by this pool.

    +
    driverClassName +

    (String) The fully qualified Java class name of the JDBC driver to be used. The driver has to be accessible + from the same classloader as tomcat-jdbc.jar +

    +
    username +

    (String) The connection username to be passed to our JDBC driver to establish a connection. + Note that method DataSource.getConnection(username,password) + by default will not use credentials passed into the method, + but will use the ones configured here. See alternateUsernameAllowed + property for more details. +

    +
    password +

    (String) The connection password to be passed to our JDBC driver to establish a connection. + Note that method DataSource.getConnection(username,password) + by default will not use credentials passed into the method, + but will use the ones configured here. See alternateUsernameAllowed + property for more details. +

    +
    maxActive +

    (int) The maximum number of active connections that can be allocated from this pool at the same time. + The default value is 100

    +
    maxIdle +

    (int) The maximum number of connections that should be kept in the pool at all times. + Default value is maxActive:100 + Idle connections are checked periodically (if enabled) and + connections that been idle for longer than minEvictableIdleTimeMillis + will be released. (also see testWhileIdle)

    +
    minIdle +

    + (int) The minimum number of established connections that should be kept in the pool at all times. + The connection pool can shrink below this number if validation queries fail. + Default value is derived from initialSize:10 (also see testWhileIdle) +

    +
    initialSize +

    (int)The initial number of connections that are created when the pool is started. + Default value is 10

    +
    maxWait +

    (int) The maximum number of milliseconds that the pool will wait (when there are no available connections) + for a connection to be returned before throwing an exception. + Default value is 30000 (30 seconds)

    +
    testOnBorrow +

    (boolean) The indication of whether objects will be validated before being borrowed from the pool. + If the object fails to validate, it will be dropped from the pool, and we will attempt to borrow another. + In order to have a more efficient validation, see validationInterval. + Default value is false +

    +
    testOnConnect +

    (boolean) The indication of whether objects will be validated when a connection is first created. + If an object fails to validate, it will be throw SQLException. + Default value is false +

    +
    testOnReturn +

    (boolean) The indication of whether objects will be validated before being returned to the pool. + The default value is false. +

    +
    testWhileIdle +

    (boolean) The indication of whether objects will be validated by the idle object evictor (if any). + If an object fails to validate, it will be dropped from the pool. + The default value is false and this property has to be set in order for the + pool cleaner/test thread is to run (also see timeBetweenEvictionRunsMillis) +

    +
    validationQuery +

    (String) The SQL query that will be used to validate connections from this pool before returning them to the caller. + If specified, this query does not have to return any data, it just can't throw a SQLException. + The default value is null. + If not specified, connections will be validation by the isValid() method. + Example values are SELECT 1(mysql), select 1 from dual(oracle), SELECT 1(MS Sql Server) +

    +
    validationQueryTimeout +

    (int) The timeout in seconds before a connection validation queries fail. This works by calling + java.sql.Statement.setQueryTimeout(seconds) on the statement that executes the validationQuery. + The pool itself doesn't timeout the query, it is still up to the JDBC driver to enforce query timeouts. + A value less than or equal to zero will disable this feature. + The default value is -1. +

    +
    validatorClassName +

    (String) The name of a class which implements the + org.apache.tomcat.jdbc.pool.Validator interface and + provides a no-arg constructor (may be implicit). If specified, the + class will be used to create a Validator instance which is then used + instead of any validation query to validate connections. The default + value is null. An example value is + com.mycompany.project.SimpleValidator. +

    +
    timeBetweenEvictionRunsMillis +

    (int) The number of milliseconds to sleep between runs of the idle connection validation/cleaner thread. + This value should not be set under 1 second. It dictates how often we check for idle, abandoned connections, and how often + we validate idle connections. + The default value is 5000 (5 seconds).
    +

    +
    numTestsPerEvictionRun +

    (int) Property not used in tomcat-jdbc-pool.

    +
    minEvictableIdleTimeMillis +

    (int) The minimum amount of time an object may sit idle in the pool before it is eligible for eviction. + The default value is 60000 (60 seconds).

    +
    accessToUnderlyingConnectionAllowed +

    (boolean) Property not used. Access can be achieved by calling unwrap on the pooled connection. + see javax.sql.DataSource interface, or call getConnection through reflection or + cast the object as javax.sql.PooledConnection

    +
    removeAbandoned +

    (boolean) Flag to remove abandoned connections if they exceed the removeAbandonedTimeout. + If set to true a connection is considered abandoned and eligible for removal if it has been in use + longer than the removeAbandonedTimeout Setting this to true can recover db connections from + applications that fail to close a connection. See also logAbandoned + The default value is false.

    +
    removeAbandonedTimeout +

    (int) Timeout in seconds before an abandoned(in use) connection can be removed. + The default value is 60 (60 seconds). The value should be set to the longest running query your applications + might have.

    +
    logAbandoned +

    (boolean) Flag to log stack traces for application code which abandoned a Connection. + Logging of abandoned Connections adds overhead for every Connection borrow because a stack trace has to be generated. + The default value is false.

    +
    connectionProperties +

    (String) The connection properties that will be sent to our JDBC driver when establishing new connections. + Format of the string must be [propertyName=property;]* + NOTE - The "user" and "password" properties will be passed explicitly, so they do not need to be included here. + The default value is null.

    +
    poolPreparedStatements +

    (boolean) Property not used.

    +
    maxOpenPreparedStatements +

    (int) Property not used.

    +
    + +
    + +

    Tomcat JDBC Enhanced Attributes

    + +
    + Attribute + + Description +
    initSQL +

    (String) A custom query to be run when a connection is first created. + The default value is null.

    +
    jdbcInterceptors +

    (String) A semicolon separated list of classnames extending + org.apache.tomcat.jdbc.pool.JdbcInterceptor class. + See Configuring JDBC interceptors + below for more detailed description of syntax and examples. +

    +

    + These interceptors will be inserted as an interceptor into the chain + of operations on a java.sql.Connection object. + The default value is null. +

    +

    + Predefined interceptors:
    + org.apache.tomcat.jdbc.pool.interceptor.
    ConnectionState
    + - keeps track of auto commit, read only, catalog and transaction isolation level.
    + org.apache.tomcat.jdbc.pool.interceptor.
    StatementFinalizer
    + - keeps track of opened statements, and closes them when the connection is returned to the pool. +

    +

    + More predefined interceptors are described in detail in the + JDBC Interceptors section. +

    +
    validationInterval +

    (long) avoid excess validation, only run validation at most at this frequency - time in milliseconds. + If a connection is due for validation, but has been validated previously within this interval, it will not be validated again. + The default value is 3000 (3 seconds).

    +
    jmxEnabled +

    (boolean) Register the pool with JMX or not. + The default value is true.

    +
    fairQueue +

    (boolean) Set to true if you wish that calls to getConnection should be treated + fairly in a true FIFO fashion. This uses the org.apache.tomcat.jdbc.pool.FairBlockingQueue + implementation for the list of the idle connections. The default value is true. + This flag is required when you want to use asynchronous connection retrieval.
    + Setting this flag ensures that threads receive connections in the order they arrive.
    + During performance tests, there is a very large difference in how locks + and lock waiting is implemented. When fairQueue=true + there is a decision making process based on what operating system the system is running. + If the system is running on Linux (property os.name=Linux. + To disable this Linux specific behavior and still use the fair queue, simply add the property + org.apache.tomcat.jdbc.pool.FairBlockingQueue.ignoreOS=true to your system properties + before the connection pool classes are loaded. +

    +
    abandonWhenPercentageFull +

    (int) Connections that have been abandoned (timed out) wont get closed and reported up unless + the number of connections in use are above the percentage defined by abandonWhenPercentageFull. + The value should be between 0-100. + The default value is 0, which implies that connections are eligible for closure as soon + as removeAbandonedTimeout has been reached.

    +
    maxAge +

    (long) Time in milliseconds to keep this connection. This attribute + works both when returning connection and when borrowing connection. + When a connection is borrowed from the pool, the pool will check to see + if the now - time-when-connected > maxAge has been reached + , and if so, it reconnects before borrow it. When a connection is + returned to the pool, the pool will check to see if the + now - time-when-connected > maxAge has been reached, and + if so, it closes the connection rather than returning it to the pool. + The default value is 0, which implies that connections + will be left open and no age check will be done upon borrowing from the + pool and returning the connection to the pool.

    +
    useEquals +

    (boolean) Set to true if you wish the ProxyConnection class to use String.equals and set to false + when you wish to use == when comparing method names. This property does not apply to added interceptors as those are configured individually. + The default value is true. +

    +
    suspectTimeout +

    (int) Timeout value in seconds. Default value is 0.
    + Similar to to the removeAbandonedTimeout value but instead of treating the connection + as abandoned, and potentially closing the connection, this simply logs the warning if + logAbandoned is set to true. If this value is equal or less than 0, no suspect + checking will be performed. Suspect checking only takes place if the timeout value is larger than 0 and + the connection was not abandoned or if abandon check is disabled. If a connection is suspect a WARN message gets + logged and a JMX notification gets sent once. +

    +
    rollbackOnReturn +

    (boolean) If autoCommit==false then the pool can terminate the transaction by calling rollback on the connection as it is returned to the pool + Default value is false.
    +

    +
    commitOnReturn +

    (boolean) If autoCommit==false then the pool can complete the transaction by calling commit on the connection as it is returned to the pool + If rollbackOnReturn==true then this attribute is ignored. + Default value is false.
    +

    +
    alternateUsernameAllowed +

    (boolean) By default, the jdbc-pool will ignore the + DataSource.getConnection(username,password) + call, and simply return a previously pooled connection under the globally configured properties username and password, for performance reasons. +

    +

    + The pool can however be configured to allow use of different credentials + each time a connection is requested. To enable the functionality described in the + DataSource.getConnection(username,password) + call, simply set the property alternateUsernameAllowed + to true.
    + Should you request a connection with the credentials user1/password1 and the connection + was previously connected using different user2/password2, the connection will be closed, + and reopened with the requested credentials. This way, the pool size is still managed + on a global level, and not on a per schema level.
    + The default value is false.
    + This property was added as an enhancement to bug 50025. +

    +
    dataSource +

    (javax.sql.DataSource) Inject a data source to the connection pool, and the pool will use the data source to retrieve connections instead of establishing them using the java.sql.Driver interface. + This is useful when you wish to pool XA connections or connections established using a data source instead of a connection string. Default value is null +

    +
    dataSourceJNDI +

    (String) The JNDI name for a data source to be looked up in JNDI and then used to establish connections to the database. See the dataSource attribute. Default value is null +

    +
    useDisposableConnectionFacade +

    (boolean) Set this to true if you wish to put a facade on your connection so that it cannot be reused after it has been closed. This prevents a thread holding on to a + reference of a connection it has already called closed on, to execute queries on it. Default value is true. +

    +
    logValidationErrors +

    (boolean) Set this to true to log errors during the validation phase to the log file. If set to true, errors will be logged as SEVERE. Default value is false for backwards compatibility. +

    +
    propagateInterruptState +

    (boolean) Set this to true to propagate the interrupt state for a thread that has been interrupted (not clearing the interrupt state). Default value is false for backwards compatibility. +

    +
    ignoreExceptionOnPreLoad +

    (boolean) Flag whether ignore error of connection creation while initializing the pool. + Set to true if you want to ignore error of connection creation while initializing the pool. + Set to false if you want to fail the initialization of the pool by throwing exception. + The default value is false. +

    +
    useStatementFacade +

    (boolean) Set this to true if you wish to wrap statements in order to + enable equals() and hashCode() methods to be + called on the closed statements if any statement proxy is set. + Default value is true. +

    +
    +
    +

    Advanced usage

    +

    JDBC interceptors

    +

    To see an example of how to use an interceptor, take a look at + org.apache.tomcat.jdbc.pool.interceptor.ConnectionState. + This simple interceptor is a cache of three attributes, transaction isolation level, auto commit and read only state, + in order for the system to avoid not needed roundtrips to the database. +

    +

    Further interceptors will be added to the core of the pool as the need arises. Contributions are always welcome!

    +

    Interceptors are of course not limited to just java.sql.Connection but can be used to wrap any + of the results from a method invocation as well. You could build query performance analyzer that provides JMX notifications when a + query is running longer than the expected time.

    +
    +

    Configuring JDBC interceptors

    +

    Configuring JDBC interceptors is done using the jdbcInterceptors property. + The property contains a list of semicolon separated class names. If the + classname is not fully qualified it will be prefixed with the + org.apache.tomcat.jdbc.pool.interceptor. prefix. +

    +

    Example:
    + + jdbcInterceptors="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState; + org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer" + +
    + is the same as +
    + jdbcInterceptors="ConnectionState;StatementFinalizer" +

    +

    + Interceptors can have properties as well. Properties for an interceptor + are specified within parentheses after the class name. Several properties + are separated by commas. +

    +

    Example:
    + + jdbcInterceptors="ConnectionState;StatementFinalizer(useEquals=true)" + +

    +

    + Extra whitespace characters around class names, property names and values + are ignored. +

    +
    +

    org.apache.tomcat.jdbc.pool.JdbcInterceptor

    +

    Abstract base class for all interceptors, cannot be instantiated.

    +
    + Attribute + + Description +
    useEquals +

    (boolean) Set to true if you wish the ProxyConnection class to use String.equals and set to false + when you wish to use == when comparing method names. + The default value is true. +

    +
    +
    +

    org.apache.tomcat.jdbc.pool.interceptor.ConnectionState

    +

    Caches the connection for the following attributes autoCommit, readOnly, + transactionIsolation and catalog. + It is a performance enhancement to avoid roundtrip to the database when getters are called or setters are called with an already set value. +

    +
    + Attribute + + Description +
    +
    +

    org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer

    +

    Keeps track of all statements created using createStatement, prepareStatement or prepareCall + and closes these statements when the connection is returned to the pool. +

    +
    + Attribute + + Description +
    trace +

    (boolean as String) Enable tracing of unclosed statements. + When enabled and a connection is closed, and statements are not closed, + the interceptor will log all stack traces. + The default value is false. +

    +
    +
    +

    org.apache.tomcat.jdbc.pool.interceptor.StatementCache

    +

    Caches PreparedStatement and/or CallableStatement + instances on a connection. +

    +

    The statements are cached per connection. + The count limit is counted globally for all connections that belong to + the same pool. Once the count reaches max, subsequent + statements are not returned to the cache and are closed immediately. +

    +
    + Attribute + + Description +
    prepared +

    (boolean as String) Enable caching of PreparedStatement + instances created using prepareStatement calls. + The default value is true. +

    +
    callable +

    (boolean as String) Enable caching of CallableStatement + instances created using prepareCall calls. + The default value is false. +

    +
    max +

    (int as String) Limit on the count of cached statements across + the connection pool. + The default value is 50. +

    +
    +
    +

    org.apache.tomcat.jdbc.pool.interceptor.StatementDecoratorInterceptor

    +

    See 48392. Interceptor to wrap statements and result sets in order to prevent access to the actual connection + using the methods ResultSet.getStatement().getConnection() and Statement.getConnection() +

    +
    + Attribute + + Description +
    +
    +

    org.apache.tomcat.jdbc.pool.interceptor.QueryTimeoutInterceptor

    +

    Automatically calls java.sql.Statement.setQueryTimeout(seconds) when a new statement is created. + The pool itself doesn't timeout the query, it is still up to the JDBC driver to enforce query timeouts. +

    +
    + Attribute + + Description +
    queryTimeout +

    (int as String) The number of seconds to set for the query timeout. + A value less than or equal to zero will disable this feature. + The default value is 1 seconds. +

    +
    +
    +

    org.apache.tomcat.jdbc.pool.interceptor.SlowQueryReport

    +

    Keeps track of query performance and issues log entries when queries exceed a time threshold of fail. + The log level used is WARN +

    +
    + Attribute + + Description +
    threshold +

    (int as String) The number of milliseconds a query has to exceed before issuing a log alert. + The default value is 1000 milliseconds. +

    +
    maxQueries +

    (int as String) The maximum number of queries to keep track of in order to preserve memory space. + A value less than or equal to 0 will disable this feature. + The default value is 1000. +

    +
    logSlow +

    (boolean as String) Set to true if you wish to log slow queries. + The default value is true. +

    +
    logFailed +

    (boolean as String) Set to true if you wish to log failed queries. + The default value is false. +

    +
    +
    +

    org.apache.tomcat.jdbc.pool.interceptor.SlowQueryReportJmx

    +

    Extends the SlowQueryReport and in addition to log entries it issues JMX notification + for monitoring tools to react to. Inherits all the attributes from its parent class. + This class uses Tomcat's JMX engine so it wont work outside of the Tomcat container. + By default, JMX notifications are sent through the ConnectionPool mbean if it is enabled. + The SlowQueryReportJmx can also register an MBean if notifyPool=false +

    +
    + Attribute + + Description +
    notifyPool +

    (boolean as String) Set to false if you want JMX notifications to go to the SlowQueryReportJmx MBean + The default value is true. +

    +
    objectName +

    (String) Define a valid javax.management.ObjectName string that will be used to register this object with the platform mbean server + The default value is null and the object will be registered using + tomcat.jdbc:type=org.apache.tomcat.jdbc.pool.interceptor.SlowQueryReportJmx,name=the-name-of-the-pool +

    +
    +
    +

    org.apache.tomcat.jdbc.pool.interceptor.ResetAbandonedTimer

    +

    + The abandoned timer starts when a connection is checked out from the pool. + This means if you have a 30second timeout and run 10x10second queries using the connection + it will be marked abandoned and potentially reclaimed depending on the abandonWhenPercentageFull + attribute. + Using this interceptor it will reset the checkout timer every time you perform an operation on the connection or execute a + query successfully. +

    +
    + Attribute + + Description +
    +
    +

    Code Example

    +

    Other examples of Tomcat configuration for JDBC usage can be found in the Tomcat documentation.

    +

    Plain Ol' Java

    +

    Here is a simple example of how to create and use a data source.

    +
      import java.sql.Connection;
    +  import java.sql.ResultSet;
    +  import java.sql.Statement;
    +
    +  import org.apache.tomcat.jdbc.pool.DataSource;
    +  import org.apache.tomcat.jdbc.pool.PoolProperties;
    +
    +  public class SimplePOJOExample {
    +
    +      public static void main(String[] args) throws Exception {
    +          PoolProperties p = new PoolProperties();
    +          p.setUrl("jdbc:mysql://localhost:3306/mysql");
    +          p.setDriverClassName("com.mysql.jdbc.Driver");
    +          p.setUsername("root");
    +          p.setPassword("password");
    +          p.setJmxEnabled(true);
    +          p.setTestWhileIdle(false);
    +          p.setTestOnBorrow(true);
    +          p.setValidationQuery("SELECT 1");
    +          p.setTestOnReturn(false);
    +          p.setValidationInterval(30000);
    +          p.setTimeBetweenEvictionRunsMillis(30000);
    +          p.setMaxActive(100);
    +          p.setInitialSize(10);
    +          p.setMaxWait(10000);
    +          p.setRemoveAbandonedTimeout(60);
    +          p.setMinEvictableIdleTimeMillis(30000);
    +          p.setMinIdle(10);
    +          p.setLogAbandoned(true);
    +          p.setRemoveAbandoned(true);
    +          p.setJdbcInterceptors(
    +            "org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"+
    +            "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
    +          DataSource datasource = new DataSource();
    +          datasource.setPoolProperties(p);
    +
    +          Connection con = null;
    +          try {
    +            con = datasource.getConnection();
    +            Statement st = con.createStatement();
    +            ResultSet rs = st.executeQuery("select * from user");
    +            int cnt = 1;
    +            while (rs.next()) {
    +                System.out.println((cnt++)+". Host:" +rs.getString("Host")+
    +                  " User:"+rs.getString("User")+" Password:"+rs.getString("Password"));
    +            }
    +            rs.close();
    +            st.close();
    +          } finally {
    +            if (con!=null) try {con.close();}catch (Exception ignore) {}
    +          }
    +      }
    +
    +  }
    +
    +

    As a Resource

    +

    And here is an example on how to configure a resource for JNDI lookups

    +
    <Resource name="jdbc/TestDB"
    +          auth="Container"
    +          type="javax.sql.DataSource"
    +          factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
    +          testWhileIdle="true"
    +          testOnBorrow="true"
    +          testOnReturn="false"
    +          validationQuery="SELECT 1"
    +          validationInterval="30000"
    +          timeBetweenEvictionRunsMillis="30000"
    +          maxActive="100"
    +          minIdle="10"
    +          maxWait="10000"
    +          initialSize="10"
    +          removeAbandonedTimeout="60"
    +          removeAbandoned="true"
    +          logAbandoned="true"
    +          minEvictableIdleTimeMillis="30000"
    +          jmxEnabled="true"
    +          jdbcInterceptors="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;
    +            org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"
    +          username="root"
    +          password="password"
    +          driverClassName="com.mysql.jdbc.Driver"
    +          url="jdbc:mysql://localhost:3306/mysql"/>
    + +
    +

    Asynchronous Connection Retrieval

    +

    The Tomcat JDBC connection pool supports asynchronous connection retrieval without adding additional threads to the + pool library. It does this by adding a method to the data source called Future<Connection> getConnectionAsync(). + In order to use the async retrieval, two conditions must be met: +

    +
      +
    1. You must configure the fairQueue property to be true.
    2. +
    3. You will have to cast the data source to org.apache.tomcat.jdbc.pool.DataSource
    4. +
    + An example of using the async feature is show below. +
      Connection con = null;
    +  try {
    +    Future<Connection> future = datasource.getConnectionAsync();
    +    while (!future.isDone()) {
    +      System.out.println("Connection is not yet available. Do some background work");
    +      try {
    +        Thread.sleep(100); //simulate work
    +      }catch (InterruptedException x) {
    +        Thread.currentThread().interrupt();
    +      }
    +    }
    +    con = future.get(); //should return instantly
    +    Statement st = con.createStatement();
    +    ResultSet rs = st.executeQuery("select * from user");
    + +
    +

    Interceptors

    +

    Interceptors are a powerful way to enable, disable or modify functionality on a specific connection or its sub components. + There are many different use cases for when interceptors are useful. By default, and for performance reasons, the connection pool is stateless. + The only state the pool itself inserts are defaultAutoCommit, defaultReadOnly, defaultTransactionIsolation, defaultCatalog if + these are set. These 4 properties are only set upon connection creation. Should these properties be modified during the usage of the connection, + the pool itself will not reset them.

    +

    An interceptor has to extend the org.apache.tomcat.jdbc.pool.JdbcInterceptor class. This class is fairly simple, + You will need to have a no arg constructor

    +
      public JdbcInterceptor() {
    +  }
    +

    + When a connection is borrowed from the pool, the interceptor can initialize or in some other way react to the event by implementing the +

    +
      public abstract void reset(ConnectionPool parent, PooledConnection con);
    +

    + method. This method gets called with two parameters, a reference to the connection pool itself ConnectionPool parent + and a reference to the underlying connection PooledConnection con. +

    +

    + When a method on the java.sql.Connection object is invoked, it will cause the +

    +
      public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
    +

    + method to get invoked. The Method method is the actual method invoked, and Object[] args are the arguments. + To look at a very simple example, where we demonstrate how to make the invocation to java.sql.Connection.close() a noop + if the connection has been closed +

    +
      if (CLOSE_VAL==method.getName()) {
    +      if (isClosed()) return null; //noop for already closed.
    +  }
    +  return super.invoke(proxy,method,args);
    +

    + There is an observation being made. It is the comparison of the method name. One way to do this would be to do + "close".equals(method.getName()). + Above we see a direct reference comparison between the method name and static final String reference. + According to the JVM spec, method names and static final String end up in a shared constant pool, so the reference comparison should work. + One could of course do this as well: +

    +
      if (compare(CLOSE_VAL,method)) {
    +      if (isClosed()) return null; //noop for already closed.
    +  }
    +  return super.invoke(proxy,method,args);
    +

    + The compare(String,Method) will use the useEquals flag on an interceptor and do either reference comparison or + a string value comparison when the useEquals=true flag is set. +

    +

    Pool start/stop
    + When the connection pool is started or closed, you can be notifed. You will only be notified once per interceptor class + even though it is an instance method. and you will be notified using an interceptor currently not attached to a pool. +

    +
      public void poolStarted(ConnectionPool pool) {
    +  }
    +
    +  public void poolClosed(ConnectionPool pool) {
    +  }
    +

    + When overriding these methods, don't forget to call super if you are extending a class other than JdbcInterceptor +

    +

    Configuring interceptors
    + Interceptors are configured using the jdbcInterceptors property or the setJdbcInterceptors method. + An interceptor can have properties, and would be configured like this +

    +
      String jdbcInterceptors=
    +    "org.apache.tomcat.jdbc.pool.interceptor.ConnectionState(useEquals=true,fast=yes)"
    + +

    Interceptor properties
    + Since interceptors can have properties, you need to be able to read the values of these properties within your + interceptor. Taking an example like the one above, you can override the setProperties method. +

    +
      public void setProperties(Map<String, InterceptorProperty> properties) {
    +     super.setProperties(properties);
    +     final String myprop = "myprop";
    +     InterceptorProperty p1 = properties.get(myprop);
    +     if (p1!=null) {
    +         setMyprop(Long.parseLong(p1.getValue()));
    +     }
    +  }
    + +
    +

    Getting the actual JDBC connection

    +

    Connection pools create wrappers around the actual connection in order to properly pool them. + We also create interceptors in these wrappers to be able to perform certain functions. + If there is a need to retrieve the actual connection, one can do so using the javax.sql.PooledConnection + interface. +

    +
      Connection con = datasource.getConnection();
    +  Connection actual = ((javax.sql.PooledConnection)con).getConnection();
    + +
    + +

    Building

    +

    We build the JDBC pool code with 1.6, but it is backwards compatible down to 1.5 for runtime environment. For unit test, we use 1.6 and higher

    +

    Other examples of Tomcat configuration for JDBC usage can be found in the Tomcat documentation.

    +

    Building from source

    +

    Building is pretty simple. The pool has a dependency on tomcat-juli.jar and in case you want the SlowQueryReportJmx

    +
      javac -classpath tomcat-juli.jar \
    +        -d . \
    +        org/apache/tomcat/jdbc/pool/*.java \
    +        org/apache/tomcat/jdbc/pool/interceptor/*.java \
    +        org/apache/tomcat/jdbc/pool/jmx/*.java
    +

    + A build file can be found in the Tomcat source repository. +

    +

    + As a convenience, a build file is also included where a simple build command will generate all files needed. +

    +
      ant download  (downloads dependencies)
    +  ant build     (compiles and generates .jar files)
    +  ant dist      (creates a release package)
    +  ant test      (runs tests, expects a test database to be setup)
    + +

    + The system is structured for a Maven build, but does generate release artifacts. Just the library itself. +

    +
    +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/jndi-datasource-examples-howto.html b/tomcat/docs/jndi-datasource-examples-howto.html new file mode 100644 index 0000000..a6c1584 --- /dev/null +++ b/tomcat/docs/jndi-datasource-examples-howto.html @@ -0,0 +1,679 @@ + +Apache Tomcat 8 (8.5.43) - JNDI Datasource How-To

    JNDI Datasource How-To

    Table of Contents

    Introduction

    + +

    JNDI Datasource configuration is covered extensively in the +JNDI-Resources-HOWTO. However, feedback from tomcat-user has +shown that specifics for individual configurations can be rather tricky.

    + +

    Here then are some example configurations that have been posted to +tomcat-user for popular databases and some general tips for db usage.

    + +

    You should be aware that since these notes are derived from configuration +and/or feedback posted to tomcat-user YMMV :-). Please let us +know if you have any other tested configurations that you feel may be of use +to the wider audience, or if you feel we can improve this section in anyway.

    + +

    +Please note that JNDI resource configuration changed somewhat between +Tomcat 7.x and Tomcat 8.x as they are using different versions of +Apache Commons DBCP library. You will most likely need to modify older +JNDI resource configurations to match the syntax in the example below in order +to make them work in Tomcat 8. +See Tomcat Migration Guide +for details. +

    + +

    +Also, please note that JNDI DataSource configuration in general, and this +tutorial in particular, assumes that you have read and understood the +Context and +Host configuration references, including +the section about Automatic Application Deployment in the latter reference. +

    +

    DriverManager, the service provider mechanism and memory leaks

    + +

    java.sql.DriverManager supports the +service +provider mechanism. This feature is that all the available JDBC drivers +that announce themselves by providing a META-INF/services/java.sql.Driver +file are automatically discovered, loaded and registered, +relieving you from the need to load the database driver explicitly before +you create a JDBC connection. +However, the implementation is fundamentally broken in all Java versions for +a servlet container environment. The problem is that +java.sql.DriverManager will scan for the drivers only once.

    + +

    The JRE Memory Leak Prevention Listener +that is included with Apache Tomcat solves this by triggering the driver scan +during Tomcat startup. This is enabled by default. It means that only +libraries visible to the common class loader and its parents will be scanned for +database drivers. This include drivers in $CATALINA_HOME/lib, +$CATALINA_BASE/lib, the class path and (where the JRE supports it) +the endorsed directory. Drivers packaged in web applications (in +WEB-INF/lib) and in the shared class loader (where configured) will +not be visible and will not be loaded automatically. If you are considering +disabling this feature, note that the scan would be triggered by the first web +application that is using JDBC, leading to failures when this web application is +reloaded and for other web applications that rely on this feature. +

    + +

    Thus, the web applications that have database drivers in their +WEB-INF/lib directory cannot rely on the service provider +mechanism and should register the drivers explicitly.

    + +

    The list of drivers in java.sql.DriverManager is also +a known source of memory leaks. Any Drivers registered +by a web application must be deregistered when the web application stops. +Tomcat will attempt to automatically discover and deregister any +JDBC drivers loaded by the web application class loader when the web +application stops. +However, it is expected that applications do this for themselves via +a ServletContextListener. +

    + +

    Database Connection Pool (DBCP 2) Configurations

    + +

    The default database connection pool implementation in Apache Tomcat +relies on the libraries from the +Apache Commons project. +The following libraries are used: +

    + +
      +
    • Commons DBCP 2
    • +
    • Commons Pool 2
    • +
    + +

    +These libraries are located in a single JAR at +$CATALINA_HOME/lib/tomcat-dbcp.jar. However, +only the classes needed for connection pooling have been included, and the +packages have been renamed to avoid interfering with applications. +

    + +

    DBCP 2 provides support for JDBC 4.1.

    + +

    Installation

    + +

    See the +DBCP 2 documentation for a complete list of configuration parameters. +

    + +
    + +

    Preventing database connection pool leaks

    + +

    +A database connection pool creates and manages a pool of connections +to a database. Recycling and reusing already existing connections +to a database is more efficient than opening a new connection. +

    + +

    +There is one problem with connection pooling. A web application has +to explicitly close ResultSet's, Statement's, and Connection's. +Failure of a web application to close these resources can result in +them never being available again for reuse, a database connection pool "leak". +This can eventually result in your web application database connections failing +if there are no more available connections.

    + +

    +There is a solution to this problem. The Apache Commons DBCP 2 can be +configured to track and recover these abandoned database connections. Not +only can it recover them, but also generate a stack trace for the code +which opened these resources and never closed them.

    + +

    +To configure a DBCP 2 DataSource so that abandoned database connections are +removed and recycled, add one or both of the following attributes to the +Resource configuration for your DBCP 2 DataSource: +

    +
    removeAbandonedOnBorrow=true
    +
    removeAbandonedOnMaintenance=true
    +

    The default for both of these attributes is false. Note that +removeAbandonedOnMaintenance has no effect unless pool +maintenance is enabled by setting timeBetweenEvictionRunsMillis +to a positive value. See the + +DBCP 2 documentation for full documentation on these attributes. +

    + +

    +Use the removeAbandonedTimeout attribute to set the number +of seconds a database connection has been idle before it is considered abandoned. +

    + +
    removeAbandonedTimeout="60"
    + +

    +The default timeout for removing abandoned connections is 300 seconds. +

    + +

    +The logAbandoned attribute can be set to true +if you want DBCP 2 to log a stack trace of the code which abandoned the +database connection resources. +

    +
    logAbandoned="true"
    +

    +The default is false. +

    + +
    + +

    MySQL DBCP 2 Example

    + +
    0. Introduction
    +

    Versions of MySQL and JDBC +drivers that have been reported to work: +

    +
      +
    • MySQL 3.23.47, MySQL 3.23.47 using InnoDB,, MySQL 3.23.58, MySQL 4.0.1alpha
    • +
    • Connector/J 3.0.11-stable (the official JDBC Driver)
    • +
    • mm.mysql 2.0.14 (an old 3rd party JDBC Driver)
    • +
    + +

    Before you proceed, don't forget to copy the JDBC Driver's jar into $CATALINA_HOME/lib.

    + +
    1. MySQL configuration
    +

    +Ensure that you follow these instructions as variations can cause problems. +

    + +

    Create a new test user, a new database and a single test table. +Your MySQL user must have a password assigned. The driver +will fail if you try to connect with an empty password. +

    +
    mysql> GRANT ALL PRIVILEGES ON *.* TO javauser@localhost
    +    ->   IDENTIFIED BY 'javadude' WITH GRANT OPTION;
    +mysql> create database javatest;
    +mysql> use javatest;
    +mysql> create table testdata (
    +    ->   id int not null auto_increment primary key,
    +    ->   foo varchar(25),
    +    ->   bar int);
    +
    +Note: the above user should be removed once testing is +complete! +
    + +

    Next insert some test data into the testdata table. +

    +
    mysql> insert into testdata values(null, 'hello', 12345);
    +Query OK, 1 row affected (0.00 sec)
    +
    +mysql> select * from testdata;
    ++----+-------+-------+
    +| ID | FOO   | BAR   |
    ++----+-------+-------+
    +|  1 | hello | 12345 |
    ++----+-------+-------+
    +1 row in set (0.00 sec)
    +
    +mysql>
    + +
    2. Context configuration
    +

    Configure the JNDI DataSource in Tomcat by adding a declaration for your +resource to your Context.

    +

    For example:

    +
    <Context>
    +
    +    <!-- maxTotal: Maximum number of database connections in pool. Make sure you
    +         configure your mysqld max_connections large enough to handle
    +         all of your db connections. Set to -1 for no limit.
    +         -->
    +
    +    <!-- maxIdle: Maximum number of idle database connections to retain in pool.
    +         Set to -1 for no limit.  See also the DBCP 2 documentation on this
    +         and the minEvictableIdleTimeMillis configuration parameter.
    +         -->
    +
    +    <!-- maxWaitMillis: Maximum time to wait for a database connection to become available
    +         in ms, in this example 10 seconds. An Exception is thrown if
    +         this timeout is exceeded.  Set to -1 to wait indefinitely.
    +         -->
    +
    +    <!-- username and password: MySQL username and password for database connections  -->
    +
    +    <!-- driverClassName: Class name for the old mm.mysql JDBC driver is
    +         org.gjt.mm.mysql.Driver - we recommend using Connector/J though.
    +         Class name for the official MySQL Connector/J driver is com.mysql.jdbc.Driver.
    +         -->
    +
    +    <!-- url: The JDBC connection url for connecting to your MySQL database.
    +         -->
    +
    +  <Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
    +               maxTotal="100" maxIdle="30" maxWaitMillis="10000"
    +               username="javauser" password="javadude" driverClassName="com.mysql.jdbc.Driver"
    +               url="jdbc:mysql://localhost:3306/javatest"/>
    +
    +</Context>
    + +
    3. web.xml configuration
    + +

    Now create a WEB-INF/web.xml for this test application.

    +
    <web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    +    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    +    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    +http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    +    version="2.4">
    +  <description>MySQL Test App</description>
    +  <resource-ref>
    +      <description>DB Connection</description>
    +      <res-ref-name>jdbc/TestDB</res-ref-name>
    +      <res-type>javax.sql.DataSource</res-type>
    +      <res-auth>Container</res-auth>
    +  </resource-ref>
    +</web-app>
    + +
    4. Test code
    +

    Now create a simple test.jsp page for use later.

    +
    <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
    +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    +
    +<sql:query var="rs" dataSource="jdbc/TestDB">
    +select id, foo, bar from testdata
    +</sql:query>
    +
    +<html>
    +  <head>
    +    <title>DB Test</title>
    +  </head>
    +  <body>
    +
    +  <h2>Results</h2>
    +
    +<c:forEach var="row" items="${rs.rows}">
    +    Foo ${row.foo}<br/>
    +    Bar ${row.bar}<br/>
    +</c:forEach>
    +
    +  </body>
    +</html>
    + +

    That JSP page makes use of +JSTL's +SQL and Core taglibs. You can get it from +Apache Tomcat Taglibs - Standard Tag Library +project — just make sure you get a 1.1.x or later release. Once you have +JSTL, copy jstl.jar and standard.jar to your web app's +WEB-INF/lib directory. + +

    + +

    Finally deploy your web app into $CATALINA_BASE/webapps either +as a warfile called DBTest.war or into a sub-directory called +DBTest

    +

    Once deployed, point a browser at +http://localhost:8080/DBTest/test.jsp to view the fruits of +your hard work.

    + +
    + +

    Oracle 8i, 9i & 10g

    +
    0. Introduction
    + +

    Oracle requires minimal changes from the MySQL configuration except for the +usual gotchas :-)

    +

    Drivers for older Oracle versions may be distributed as *.zip files rather +than *.jar files. Tomcat will only use *.jar files installed in +$CATALINA_HOME/lib. Therefore classes111.zip +or classes12.zip will need to be renamed with a .jar +extension. Since jarfiles are zipfiles, there is no need to unzip and jar these +files - a simple rename will suffice.

    + +

    For Oracle 9i onwards you should use oracle.jdbc.OracleDriver +rather than oracle.jdbc.driver.OracleDriver as Oracle have stated +that oracle.jdbc.driver.OracleDriver is deprecated and support +for this driver class will be discontinued in the next major release. +

    + +
    1. Context configuration
    +

    In a similar manner to the mysql config above, you will need to define your +Datasource in your Context. Here we define a +Datasource called myoracle using the thin driver to connect as user scott, +password tiger to the sid called mysid. (Note: with the thin driver this sid is +not the same as the tnsname). The schema used will be the default schema for the +user scott.

    + +

    Use of the OCI driver should simply involve a changing thin to oci in the URL string. +

    +
    <Resource name="jdbc/myoracle" auth="Container"
    +              type="javax.sql.DataSource" driverClassName="oracle.jdbc.OracleDriver"
    +              url="jdbc:oracle:thin:@127.0.0.1:1521:mysid"
    +              username="scott" password="tiger" maxTotal="20" maxIdle="10"
    +              maxWaitMillis="-1"/>
    + +
    2. web.xml configuration
    +

    You should ensure that you respect the element ordering defined by the DTD when you +create you applications web.xml file.

    +
    <resource-ref>
    + <description>Oracle Datasource example</description>
    + <res-ref-name>jdbc/myoracle</res-ref-name>
    + <res-type>javax.sql.DataSource</res-type>
    + <res-auth>Container</res-auth>
    +</resource-ref>
    +
    3. Code example
    +

    You can use the same example application as above (assuming you create the required DB +instance, tables etc.) replacing the Datasource code with something like

    +
    Context initContext = new InitialContext();
    +Context envContext  = (Context)initContext.lookup("java:/comp/env");
    +DataSource ds = (DataSource)envContext.lookup("jdbc/myoracle");
    +Connection conn = ds.getConnection();
    +//etc.
    +
    + + +

    PostgreSQL

    +
    0. Introduction
    +

    PostgreSQL is configured in a similar manner to Oracle.

    + +
    1. Required files
    +

    +Copy the Postgres JDBC jar to $CATALINA_HOME/lib. As with Oracle, the +jars need to be in this directory in order for DBCP 2's Classloader to find +them. This has to be done regardless of which configuration step you take next. +

    + +
    2. Resource configuration
    + +

    +You have two choices here: define a datasource that is shared across all Tomcat +applications, or define a datasource specifically for one application. +

    + +
    2a. Shared resource configuration
    +

    +Use this option if you wish to define a datasource that is shared across +multiple Tomcat applications, or if you just prefer defining your datasource +in this file. +

    +

    This author has not had success here, although others have reported so. +Clarification would be appreciated here.

    + +
    <Resource name="jdbc/postgres" auth="Container"
    +          type="javax.sql.DataSource" driverClassName="org.postgresql.Driver"
    +          url="jdbc:postgresql://127.0.0.1:5432/mydb"
    +          username="myuser" password="mypasswd" maxTotal="20" maxIdle="10" maxWaitMillis="-1"/>
    +
    2b. Application-specific resource configuration
    + +

    +Use this option if you wish to define a datasource specific to your application, +not visible to other Tomcat applications. This method is less invasive to your +Tomcat installation. +

    + +

    +Create a resource definition for your Context. +The Context element should look something like the following. +

    + +
    <Context>
    +
    +<Resource name="jdbc/postgres" auth="Container"
    +          type="javax.sql.DataSource" driverClassName="org.postgresql.Driver"
    +          url="jdbc:postgresql://127.0.0.1:5432/mydb"
    +          username="myuser" password="mypasswd" maxTotal="20" maxIdle="10"
    +maxWaitMillis="-1"/>
    +</Context>
    + +
    3. web.xml configuration
    +
    <resource-ref>
    + <description>postgreSQL Datasource example</description>
    + <res-ref-name>jdbc/postgres</res-ref-name>
    + <res-type>javax.sql.DataSource</res-type>
    + <res-auth>Container</res-auth>
    +</resource-ref>
    + +
    4. Accessing the datasource
    +

    +When accessing the datasource programmatically, remember to prepend +java:/comp/env to your JNDI lookup, as in the following snippet of +code. Note also that "jdbc/postgres" can be replaced with any value you prefer, provided +you change it in the above resource definition file as well. +

    + +
    InitialContext cxt = new InitialContext();
    +if ( cxt == null ) {
    +   throw new Exception("Uh oh -- no context!");
    +}
    +
    +DataSource ds = (DataSource) cxt.lookup( "java:/comp/env/jdbc/postgres" );
    +
    +if ( ds == null ) {
    +   throw new Exception("Data source not found!");
    +}
    + +
    +

    Non-DBCP Solutions

    +

    +These solutions either utilise a single connection to the database (not recommended for anything other +than testing!) or some other pooling technology. +

    +

    Oracle 8i with OCI client

    +

    Introduction

    +

    Whilst not strictly addressing the creation of a JNDI DataSource using the OCI client, these notes can be combined with the +Oracle and DBCP 2 solution above.

    +

    +In order to use OCI driver, you should have an Oracle client installed. You should have installed +Oracle8i(8.1.7) client from cd, and download the suitable JDBC/OCI +driver(Oracle8i 8.1.7.1 JDBC/OCI Driver) from otn.oracle.com. +

    +

    +After renaming classes12.zip file to classes12.jar +for Tomcat, copy it into $CATALINA_HOME/lib. +You may also have to remove the javax.sql.* classes +from this file depending upon the version of Tomcat and JDK you are using. +

    +
    + +

    Putting it all together

    +

    +Ensure that you have the ocijdbc8.dll or .so in your $PATH or LD_LIBRARY_PATH + (possibly in $ORAHOME\bin) and also confirm that the native library can be loaded by a simple test program +using System.loadLibrary("ocijdbc8"); +

    +

    +You should next create a simple test servlet or JSP that has these +critical lines: +

    +
    DriverManager.registerDriver(new
    +oracle.jdbc.driver.OracleDriver());
    +conn =
    +DriverManager.getConnection("jdbc:oracle:oci8:@database","username","password");
    +

    +where database is of the form host:port:SID Now if you try to access the URL of your +test servlet/JSP and what you get is a +ServletException with a root cause of java.lang.UnsatisfiedLinkError:get_env_handle. +

    +

    +First, the UnsatisfiedLinkError indicates that you have +

    +
      +
    • a mismatch between your JDBC classes file and +your Oracle client version. The giveaway here is the message stating that a needed library file cannot be +found. For example, you may be using a classes12.zip file from Oracle Version 8.1.6 with a Version 8.1.5 +Oracle client. The classesXXX.zip file and Oracle client software versions must match. +
    • +
    • A $PATH, LD_LIBRARY_PATH problem.
    • +
    • It has been reported that ignoring the driver you have downloaded from otn and using +the classes12.zip file from the directory $ORAHOME\jdbc\lib will also work. +
    • +
    +

    +Next you may experience the error ORA-06401 NETCMN: invalid driver designator +

    +

    +The Oracle documentation says : "Cause: The login (connect) string contains an invalid +driver designator. Action: Correct the string and re-submit." + +Change the database connect string (of the form host:port:SID) with this one: +(description=(address=(host=myhost)(protocol=tcp)(port=1521))(connect_data=(sid=orcl))) +

    +

    +Ed. Hmm, I don't think this is really needed if you sort out your TNSNames - but I'm not an Oracle DBA :-) +

    +
    +

    Common Problems

    +

    Here are some common problems encountered with a web application which +uses a database and tips for how to solve them.

    + +

    Intermittent Database Connection Failures

    +

    +Tomcat runs within a JVM. The JVM periodically performs garbage collection +(GC) to remove java objects which are no longer being used. When the JVM +performs GC execution of code within Tomcat freezes. If the maximum time +configured for establishment of a database connection is less than the amount +of time garbage collection took you can get a database connection failure. +

    + +

    To collect data on how long garbage collection is taking add the +-verbose:gc argument to your CATALINA_OPTS +environment variable when starting Tomcat. When verbose gc is enabled +your $CATALINA_BASE/logs/catalina.out log file will include +data for every garbage collection including how long it took.

    + +

    When your JVM is tuned correctly 99% of the time a GC will take less +than one second. The remainder will only take a few seconds. Rarely, +if ever should a GC take more than 10 seconds.

    + +

    Make sure that the db connection timeout is set to 10-15 seconds. +For DBCP 2 you set this using the parameter maxWaitMillis.

    + +
    + +

    Random Connection Closed Exceptions

    +

    +These can occur when one request gets a db connection from the connection +pool and closes it twice. When using a connection pool, closing the +connection just returns it to the pool for reuse by another request, +it doesn't close the connection. And Tomcat uses multiple threads to +handle concurrent requests. Here is an example of the sequence +of events which could cause this error in Tomcat: +

    +
    +  Request 1 running in Thread 1 gets a db connection.
    +
    +  Request 1 closes the db connection.
    +
    +  The JVM switches the running thread to Thread 2
    +
    +  Request 2 running in Thread 2 gets a db connection
    +  (the same db connection just closed by Request 1).
    +
    +  The JVM switches the running thread back to Thread 1
    +
    +  Request 1 closes the db connection a second time in a finally block.
    +
    +  The JVM switches the running thread back to Thread 2
    +
    +  Request 2 Thread 2 tries to use the db connection but fails
    +  because Request 1 closed it.
    +
    +

    +Here is an example of properly written code to use a database connection +obtained from a connection pool: +

    +
      Connection conn = null;
    +  Statement stmt = null;  // Or PreparedStatement if needed
    +  ResultSet rs = null;
    +  try {
    +    conn = ... get connection from connection pool ...
    +    stmt = conn.createStatement("select ...");
    +    rs = stmt.executeQuery();
    +    ... iterate through the result set ...
    +    rs.close();
    +    rs = null;
    +    stmt.close();
    +    stmt = null;
    +    conn.close(); // Return to connection pool
    +    conn = null;  // Make sure we don't close it twice
    +  } catch (SQLException e) {
    +    ... deal with errors ...
    +  } finally {
    +    // Always make sure result sets and statements are closed,
    +    // and the connection is returned to the pool
    +    if (rs != null) {
    +      try { rs.close(); } catch (SQLException e) { ; }
    +      rs = null;
    +    }
    +    if (stmt != null) {
    +      try { stmt.close(); } catch (SQLException e) { ; }
    +      stmt = null;
    +    }
    +    if (conn != null) {
    +      try { conn.close(); } catch (SQLException e) { ; }
    +      conn = null;
    +    }
    +  }
    + +
    + +

    Context versus GlobalNamingResources

    +

    + Please note that although the above instructions place the JNDI declarations in a Context + element, it is possible and sometimes desirable to place these declarations in the + GlobalNamingResources section of the server + configuration file. A resource placed in the GlobalNamingResources section will be shared + among the Contexts of the server. +

    +
    + +

    JNDI Resource Naming and Realm Interaction

    +

    + In order to get Realms to work, the realm must refer to the datasource as + defined in the <GlobalNamingResources> or <Context> section, not a datasource as renamed + using <ResourceLink>. +

    +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/jndi-resources-howto.html b/tomcat/docs/jndi-resources-howto.html new file mode 100644 index 0000000..91f5ec4 --- /dev/null +++ b/tomcat/docs/jndi-resources-howto.html @@ -0,0 +1,1066 @@ + +Apache Tomcat 8 (8.5.43) - JNDI Resources How-To

    JNDI Resources How-To

    Table of Contents

    Introduction

    + +

    Tomcat provides a JNDI InitialContext implementation +instance for each web application running under it, in a manner that is +compatible with those provided by a + +Java Enterprise Edition application server. The Java EE standard provides +a standard set of elements in the /WEB-INF/web.xml file to +reference/define resources.

    + +

    See the following Specifications for more information about programming APIs +for JNDI, and for the features supported by Java Enterprise Edition (Java EE) +servers, which Tomcat emulates for the services that it provides:

    + + +

    web.xml configuration

    + +

    The following elements may be used in the web application deployment +descriptor (/WEB-INF/web.xml) of your web application to define +resources:

    +
      +
    • <env-entry> - Environment entry, a + single-value parameter that can be used to configure how the application + will operate.
    • +
    • <resource-ref> - Resource reference, + which is typically to an object factory for resources such as a JDBC + DataSource, a JavaMail Session, or custom + object factories configured into Tomcat.
    • +
    • <resource-env-ref> - Resource + environment reference, a new variation of resource-ref + added in Servlet 2.4 that is simpler to configure for resources + that do not require authentication information.
    • +
    + +

    Providing that Tomcat is able to identify an appropriate resource factory to +use to create the resource and that no further configuration information is +required, Tomcat will use the information in /WEB-INF/web.xml to +create the resource.

    + +

    Tomcat provides a number of Tomcat specific options for JNDI resources that +cannot be specified in web.xml. These include closeMethod that +enables faster cleaning-up of JNDI resources when a web application stops and +singleton that controls whether or not a new instance of the +resource is created for every JNDI lookup. To use these configuration options +the resource must be specified in a web application's +<Context> element or in the + +<GlobalNamingResources> element of +$CATALINA_BASE/conf/server.xml.

    + +

    context.xml configuration

    + +

    If Tomcat is unable to identify the appropriate resource factory and/or +additional configuration information is required, additional Tomcat specific +configuration must be specified before Tomcat can create the resource. +Tomcat specific resource configuration is entered in +the <Context> elements that +can be specified in either $CATALINA_BASE/conf/server.xml or, +preferably, the per-web-application context XML file +(META-INF/context.xml).

    + +

    Tomcat specific resource configuration is performed using the following +elements in the <Context> +element:

    + +
      +
    • <Environment> - + Configure names and values for scalar environment entries that will be + exposed to the web application through the JNDI + InitialContext (equivalent to the inclusion of an + <env-entry> element in the web application + deployment descriptor).
    • +
    • <Resource> - + Configure the name and data type of a resource made available to the + application (equivalent to the inclusion of a + <resource-ref> element in the web application + deployment descriptor).
    • +
    • <ResourceLink> - + Add a link to a resource defined in the global JNDI context. Use resource + links to give a web application access to a resource defined in + the <GlobalNamingResources> + child element of the <Server> + element.
    • +
    • <Transaction> - + Add a resource factory for instantiating the UserTransaction object + instance that is available at java:comp/UserTransaction.
    • + +
    + +

    Any number of these elements may be nested inside a +<Context> element and will +be associated only with that particular web application.

    + +

    If a resource has been defined in a +<Context> element it is not +necessary for that resource to be defined in /WEB-INF/web.xml. +However, it is recommended to keep the entry in /WEB-INF/web.xml +to document the resource requirements for the web application.

    + +

    Where the same resource name has been defined for a +<env-entry> element included in the web application +deployment descriptor (/WEB-INF/web.xml) and in an +<Environment> element as part of the +<Context> element for the +web application, the values in the deployment descriptor will take precedence +only if allowed by the corresponding +<Environment> element (by setting the override +attribute to "true").

    + +

    Global configuration

    + +

    Tomcat maintains a separate namespace of global resources for the +entire server. These are configured in the + +<GlobalNamingResources> element of +$CATALINA_BASE/conf/server.xml. You may expose these resources to +web applications by using a +<ResourceLink> to +include it in the per-web-application context.

    + +

    If a resource has been defined using a +<ResourceLink>, it is not +necessary for that resource to be defined in /WEB-INF/web.xml. +However, it is recommended to keep the entry in /WEB-INF/web.xml +to document the resource requirements for the web application.

    + +

    Using resources

    + +

    The InitialContext is configured as a web application is +initially deployed, and is made available to web application components (for +read-only access). All configured entries and resources are placed in +the java:comp/env portion of the JNDI namespace, so a typical +access to a resource - in this case, to a JDBC DataSource - +would look something like this:

    + +
    // Obtain our environment naming context
    +Context initCtx = new InitialContext();
    +Context envCtx = (Context) initCtx.lookup("java:comp/env");
    +
    +// Look up our data source
    +DataSource ds = (DataSource)
    +  envCtx.lookup("jdbc/EmployeeDB");
    +
    +// Allocate and use a connection from the pool
    +Connection conn = ds.getConnection();
    +... use this connection to access the database ...
    +conn.close();
    + +

    Tomcat Standard Resource Factories

    + +

    Tomcat includes a series of standard resource factories that can + provide services to your web applications, but give you configuration + flexibility (via the + <Context> element) + without modifying the web application or the deployment descriptor. Each + subsection below details the configuration and usage of the standard resource + factories.

    + +

    See Adding Custom + Resource Factories for information about how to create, install, + configure, and use your own custom resource factory classes with + Tomcat.

    + +

    NOTE - Of the standard resource factories, only the + "JDBC Data Source" and "User Transaction" factories are mandated to + be available on other platforms, and then they are required only if + the platform implements the Java Enterprise Edition (Java EE) specs. + All other standard resource factories, plus custom resource factories + that you write yourself, are specific to Tomcat and cannot be assumed + to be available on other containers.

    + +

    Generic JavaBean Resources

    + +
    0. Introduction
    + +

    This resource factory can be used to create objects of any + Java class that conforms to standard JavaBeans naming conventions (i.e. + it has a zero-arguments constructor, and has property setters that + conform to the setFoo() naming pattern. The resource factory will + only create a new instance of the appropriate bean class every time a + lookup() for this entry is made if the singleton + attribute of the factory is set to false.

    + +

    The steps required to use this facility are described below.

    + +
    1. Create Your JavaBean Class
    + +

    Create the JavaBean class which will be instantiated each time + that the resource factory is looked up. For this example, assume + you create a class com.mycompany.MyBean, which looks + like this:

    + +
    package com.mycompany;
    +
    +public class MyBean {
    +
    +  private String foo = "Default Foo";
    +
    +  public String getFoo() {
    +    return (this.foo);
    +  }
    +
    +  public void setFoo(String foo) {
    +    this.foo = foo;
    +  }
    +
    +  private int bar = 0;
    +
    +  public int getBar() {
    +    return (this.bar);
    +  }
    +
    +  public void setBar(int bar) {
    +    this.bar = bar;
    +  }
    +
    +
    +}
    + +
    2. Declare Your Resource Requirements
    + +

    Next, modify your web application deployment descriptor + (/WEB-INF/web.xml) to declare the JNDI name under which + you will request new instances of this bean. The simplest approach is + to use a <resource-env-ref> element, like this:

    + +
    <resource-env-ref>
    +  <description>
    +    Object factory for MyBean instances.
    +  </description>
    +  <resource-env-ref-name>
    +    bean/MyBeanFactory
    +  </resource-env-ref-name>
    +  <resource-env-ref-type>
    +    com.mycompany.MyBean
    +  </resource-env-ref-type>
    +</resource-env-ref>
    + +

    WARNING - Be sure you respect the element ordering + that is required by the DTD for web application deployment descriptors! + See the + Servlet + Specification for details.

    + +
    3. Code Your Application's Use Of This Resource
    + +

    A typical use of this resource environment reference might look + like this:

    + +
    Context initCtx = new InitialContext();
    +Context envCtx = (Context) initCtx.lookup("java:comp/env");
    +MyBean bean = (MyBean) envCtx.lookup("bean/MyBeanFactory");
    +
    +writer.println("foo = " + bean.getFoo() + ", bar = " +
    +               bean.getBar());
    + +
    4. Configure Tomcat's Resource Factory
    + +

    To configure Tomcat's resource factory, add an element like this to the + <Context> element for + this web application.

    + +
    <Context ...>
    +  ...
    +  <Resource name="bean/MyBeanFactory" auth="Container"
    +            type="com.mycompany.MyBean"
    +            factory="org.apache.naming.factory.BeanFactory"
    +            bar="23"/>
    +  ...
    +</Context>
    + +

    Note that the resource name (here, bean/MyBeanFactory + must match the value specified in the web application deployment + descriptor. We are also initializing the value of the bar + property, which will cause setBar(23) to be called before + the new bean is returned. Because we are not initializing the + foo property (although we could have), the bean will + contain whatever default value is set up by its constructor.

    + +

    Some beans have properties with types that cannot automatically be + converted from a string value. Setting such properties using the Tomcat + BeanFactory will fail with a NamingException. In cases were those beans + provide methods to set the properties from a string value, the Tomcat + BeanFactory can be configured to use these methods. The configuration is + done with the forceString attribute.

    + +

    Assume our bean looks like this:

    + +
    package com.mycompany;
    +
    +import java.net.InetAddress;
    +import java.net.UnknownHostException;
    +
    +public class MyBean2 {
    +
    +  private InetAddress local = null;
    +
    +  public InetAddress getLocal() {
    +    return local;
    +  }
    +
    +  public void setLocal(InetAddress ip) {
    +    local = ip;
    +  }
    +
    +  public void setLocal(String localHost) {
    +    try {
    +      local = InetAddress.getByName(localHost);
    +    } catch (UnknownHostException ex) {
    +    }
    +  }
    +
    +  private InetAddress remote = null;
    +
    +  public InetAddress getRemote() {
    +    return remote;
    +  }
    +
    +  public void setRemote(InetAddress ip) {
    +    remote = ip;
    +  }
    +
    +  public void host(String remoteHost) {
    +    try {
    +      remote = InetAddress.getByName(remoteHost);
    +    } catch (UnknownHostException ex) {
    +    }
    +  }
    +
    +}
    + +

    The bean has two properties, both are of type InetAddress. + The first property local has an additional setter taking a + string argument. By default the Tomcat BeanFactory would try to use the + automatically detected setter with the same argument type as the property + type and then throw a NamingException, because it is not prepared to convert + the given string attribute value to InetAddress. + We can tell the Tomcat BeanFactory to use the other setter like that:

    + +
    <Context ...>
    +  ...
    +  <Resource name="bean/MyBeanFactory" auth="Container"
    +            type="com.mycompany.MyBean2"
    +            factory="org.apache.naming.factory.BeanFactory"
    +            forceString="local"
    +            local="localhost"/>
    +  ...
    +</Context>
    + +

    The bean property remote can also be set from a string, + but one has to use the non-standard method name host. + To set local and remote use the following + configuration:

    + +
    <Context ...>
    +  ...
    +  <Resource name="bean/MyBeanFactory" auth="Container"
    +            type="com.mycompany.MyBean2"
    +            factory="org.apache.naming.factory.BeanFactory"
    +            forceString="local,remote=host"
    +            local="localhost"
    +            remote="tomcat.apache.org"/>
    +  ...
    +</Context>
    + +

    Multiple property descriptions can be combined in + forceString by concatenation with comma as a separator. + Each property description consists of either only the property name + in which case the BeanFactory calls the setter method. Or it consist + of name=method in which case the property named + name is set by calling method method. + For properties of types String or of primitive type + or of their associated primitive wrapper classes using + forceString is not needed. The correct setter will be + automatically detected and argument conversion will be applied.

    + +
    + + +

    UserDatabase Resources

    + +
    0. Introduction
    + +

    UserDatabase resources are typically configured as global resources for + use by a UserDatabase realm. Tomcat includes a UserDatabaseFactory that + creates UserDatabase resources backed by an XML file - usually + tomcat-users.xml

    + +

    The steps required to set up a global UserDatabase resource are described + below.

    + +
    1. Create/edit the XML file
    + +

    The XML file is typically located at + $CATALINA_BASE/conf/tomcat-users.xml however, you are free to + locate the file anywhere on the file system. It is recommended that the XML + files are placed in $CATALINA_BASE/conf. A typical XML would + look like:

    + +
    <?xml version="1.0" encoding="UTF-8"?>
    +<tomcat-users>
    +  <role rolename="tomcat"/>
    +  <role rolename="role1"/>
    +  <user username="tomcat" password="tomcat" roles="tomcat"/>
    +  <user username="both" password="tomcat" roles="tomcat,role1"/>
    +  <user username="role1" password="tomcat" roles="role1"/>
    +</tomcat-users>
    + +
    2. Declare Your Resource
    + +

    Next, modify $CATALINA_BASE/conf/server.xml to create the + UserDatabase resource based on your XML file. It should look something like + this:

    + +
    <Resource name="UserDatabase"
    +          auth="Container"
    +          type="org.apache.catalina.UserDatabase"
    +          description="User database that can be updated and saved"
    +          factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
    +          pathname="conf/tomcat-users.xml"
    +          readonly="false" />
    + +

    The pathname attribute can be a URL, an absolute path or a + relative path. If relative, it is relative to $CATALINA_BASE. +

    + +

    The readonly attribute is optional and defaults to + true if not supplied. If the XML is writeable then it will be + written to when Tomcat starts. WARNING: When the file is + written it will inherit the default file permissions for the user Tomcat + is running as. Ensure that these are appropriate to maintain the security + of your installation.

    + +

    If referenced in a Realm, the MemoryUserDatabse will, by default, monitor + pathname for changes and reload the file if a change in the + last modified time is observed. This can be disabled by setting the + watchSource attribute to false. +

    + +
    3. Configure the Realm
    + +

    Configure a UserDatabase Realm to use this resource as described in the + Realm configuration documentation.

    + +
    + + +

    JavaMail Sessions

    + +
    0. Introduction
    + +

    In many web applications, sending electronic mail messages is a + required part of the system's functionality. The + Java Mail API + makes this process relatively straightforward, but requires many + configuration details that the client application must be aware of + (including the name of the SMTP host to be used for message sending).

    + +

    Tomcat includes a standard resource factory that will create + javax.mail.Session session instances for you, already + configured to connect to an SMTP server. + In this way, the application is totally insulated from changes in the + email server configuration environment - it simply asks for, and receives, + a preconfigured session whenever needed.

    + +

    The steps required for this are outlined below.

    + +
    1. Declare Your Resource Requirements
    + +

    The first thing you should do is modify the web application deployment + descriptor (/WEB-INF/web.xml) to declare the JNDI name under + which you will look up preconfigured sessions. By convention, all such + names should resolve to the mail subcontext (relative to the + standard java:comp/env naming context that is the root of + all provided resource factories. A typical web.xml entry + might look like this:

    +
    <resource-ref>
    +  <description>
    +    Resource reference to a factory for javax.mail.Session
    +    instances that may be used for sending electronic mail
    +    messages, preconfigured to connect to the appropriate
    +    SMTP server.
    +  </description>
    +  <res-ref-name>
    +    mail/Session
    +  </res-ref-name>
    +  <res-type>
    +    javax.mail.Session
    +  </res-type>
    +  <res-auth>
    +    Container
    +  </res-auth>
    +</resource-ref>
    + +

    WARNING - Be sure you respect the element ordering + that is required by the DTD for web application deployment descriptors! + See the + Servlet + Specification for details.

    + +
    2. Code Your Application's Use Of This Resource
    + +

    A typical use of this resource reference might look like this:

    +
    Context initCtx = new InitialContext();
    +Context envCtx = (Context) initCtx.lookup("java:comp/env");
    +Session session = (Session) envCtx.lookup("mail/Session");
    +
    +Message message = new MimeMessage(session);
    +message.setFrom(new InternetAddress(request.getParameter("from")));
    +InternetAddress to[] = new InternetAddress[1];
    +to[0] = new InternetAddress(request.getParameter("to"));
    +message.setRecipients(Message.RecipientType.TO, to);
    +message.setSubject(request.getParameter("subject"));
    +message.setContent(request.getParameter("content"), "text/plain");
    +Transport.send(message);
    + +

    Note that the application uses the same resource reference name + that was declared in the web application deployment descriptor. This + is matched up against the resource factory that is configured in the + <Context> element + for the web application as described below.

    + +
    3. Configure Tomcat's Resource Factory
    + +

    To configure Tomcat's resource factory, add an elements like this to the + <Context> element for + this web application.

    + +
    <Context ...>
    +  ...
    +  <Resource name="mail/Session" auth="Container"
    +            type="javax.mail.Session"
    +            mail.smtp.host="localhost"/>
    +  ...
    +</Context>
    + +

    Note that the resource name (here, mail/Session) must + match the value specified in the web application deployment descriptor. + Customize the value of the mail.smtp.host parameter to + point at the server that provides SMTP service for your network.

    + +

    Additional resource attributes and values will be converted to properties + and values and passed to + javax.mail.Session.getInstance(java.util.Properties) as part of + the java.util.Properties collection. In addition to the + properties defined in Annex A of the JavaMail specification, individual + providers may also support additional properties. +

    + +

    If the resource is configured with a password attribute and + either a mail.smtp.user or mail.user attribute + then Tomcat's resource factory will configure and add a + javax.mail.Authenticator to the mail session.

    + +
    4. Install the JavaMail libraries
    + +

    + Download the JavaMail API.

    + +

    Unpackage the distribution and place mail.jar into $CATALINA_HOME/lib so + that it is available to Tomcat during the initialization of the mail Session + Resource. Note: placing this jar in both $CATALINA_HOME/lib + and a web application's lib folder will cause an error, so ensure you have + it in the $CATALINA_HOME/lib location only. +

    + +
    5. Restart Tomcat
    + +

    For the additional JAR to be visible to Tomcat, it is necessary for the + Tomcat instance to be restarted.

    + + +
    Example Application
    + +

    The /examples application included with Tomcat contains + an example of utilizing this resource factory. It is accessed via the + "JSP Examples" link. The source code for the servlet that actually + sends the mail message is in + /WEB-INF/classes/SendMailServlet.java.

    + +

    WARNING - The default configuration assumes that there + is an SMTP server listing on port 25 on localhost. If this is + not the case, edit the + <Context> element for + this web application and modify the parameter value for the + mail.smtp.host parameter to be the host name of an SMTP server + on your network.

    + +
    + +

    JDBC Data Sources

    + +
    0. Introduction
    + +

    Many web applications need to access a database via a JDBC driver, + to support the functionality required by that application. The Java EE + Platform Specification requires Java EE Application Servers to make + available a DataSource implementation (that is, a connection + pool for JDBC connections) for this purpose. Tomcat offers exactly + the same support, so that database-based applications you develop on + Tomcat using this service will run unchanged on any Java EE server.

    + +

    For information about JDBC, you should consult the following:

    + + +

    NOTE - The default data source support in Tomcat + is based on the DBCP 2 connection pool from the + Commons + project. However, it is possible to use any other connection pool + that implements javax.sql.DataSource, by writing your + own custom resource factory, as described + below.

    + +
    1. Install Your JDBC Driver
    + +

    Use of the JDBC Data Sources JNDI Resource Factory requires + that you make an appropriate JDBC driver available to both Tomcat internal + classes and to your web application. This is most easily accomplished by + installing the driver's JAR file(s) into the + $CATALINA_HOME/lib directory, which makes the driver + available both to the resource factory and to your application.

    + +
    2. Declare Your Resource Requirements
    + +

    Next, modify the web application deployment descriptor + (/WEB-INF/web.xml) to declare the JNDI name under + which you will look up preconfigured data source. By convention, all such + names should resolve to the jdbc subcontext (relative to the + standard java:comp/env naming context that is the root of + all provided resource factories. A typical web.xml entry + might look like this:

    +
    <resource-ref>
    +  <description>
    +    Resource reference to a factory for java.sql.Connection
    +    instances that may be used for talking to a particular
    +    database that is configured in the <Context>
    +    configuration for the web application.
    +  </description>
    +  <res-ref-name>
    +    jdbc/EmployeeDB
    +  </res-ref-name>
    +  <res-type>
    +    javax.sql.DataSource
    +  </res-type>
    +  <res-auth>
    +    Container
    +  </res-auth>
    +</resource-ref>
    + +

    WARNING - Be sure you respect the element ordering + that is required by the DTD for web application deployment descriptors! + See the + Servlet + Specification for details.

    + +
    3. Code Your Application's Use Of This Resource
    + +

    A typical use of this resource reference might look like this:

    +
    Context initCtx = new InitialContext();
    +Context envCtx = (Context) initCtx.lookup("java:comp/env");
    +DataSource ds = (DataSource)
    +  envCtx.lookup("jdbc/EmployeeDB");
    +
    +Connection conn = ds.getConnection();
    +... use this connection to access the database ...
    +conn.close();
    + +

    Note that the application uses the same resource reference name that was + declared in the web application deployment descriptor. This is matched up + against the resource factory that is configured in the + <Context> element for + the web application as described below.

    + +
    4. Configure Tomcat's Resource Factory
    + +

    To configure Tomcat's resource factory, add an element like this to the + <Context> element for + the web application.

    + +
    <Context ...>
    +  ...
    +  <Resource name="jdbc/EmployeeDB"
    +            auth="Container"
    +            type="javax.sql.DataSource"
    +            username="dbusername"
    +            password="dbpassword"
    +            driverClassName="org.hsql.jdbcDriver"
    +            url="jdbc:HypersonicSQL:database"
    +            maxTotal="8"
    +            maxIdle="4"/>
    +  ...
    +</Context>
    + +

    Note that the resource name (here, jdbc/EmployeeDB) must + match the value specified in the web application deployment descriptor.

    + +

    This example assumes that you are using the HypersonicSQL database + JDBC driver. Customize the driverClassName and + driverName parameters to match your actual database's + JDBC driver and connection URL.

    + +

    The configuration properties for Tomcat's standard data source + resource factory + (org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory) are + as follows:

    +
      +
    • driverClassName - Fully qualified Java class name + of the JDBC driver to be used.
    • +
    • username - Database username to be passed to our + JDBC driver.
    • +
    • password - Database password to be passed to our + JDBC driver.
    • +
    • url - Connection URL to be passed to our JDBC driver. + (For backwards compatibility, the property driverName + is also recognized.)
    • +
    • initialSize - The initial number of connections + that will be created in the pool during pool initialization. Default: 0
    • +
    • maxTotal - The maximum number of connections + that can be allocated from this pool at the same time. Default: 8
    • +
    • minIdle - The minimum number of connections that + will sit idle in this pool at the same time. Default: 0
    • +
    • maxIdle - The maximum number of connections that + can sit idle in this pool at the same time. Default: 8
    • +
    • maxWaitMillis - The maximum number of milliseconds that the + pool will wait (when there are no available connections) for a + connection to be returned before throwing an exception. Default: -1 (infinite)
    • +
    +

    Some additional properties handle connection validation:

    +
      +
    • validationQuery - SQL query that can be used by the + pool to validate connections before they are returned to the + application. If specified, this query MUST be an SQL SELECT + statement that returns at least one row.
    • +
    • validationQueryTimeout - Timeout in seconds + for the validation query to return. Default: -1 (infinite)
    • +
    • testOnBorrow - true or false: whether a connection + should be validated using the validation query each time it is + borrowed from the pool. Default: true
    • +
    • testOnReturn - true or false: whether a connection + should be validated using the validation query each time it is + returned to the pool. Default: false
    • +
    +

    The optional evictor thread is responsible for shrinking the pool + by removing any connections which are idle for a long time. The evictor + does not respect minIdle. Note that you do not need to + activate the evictor thread if you only want the pool to shrink according + to the configured maxIdle property.

    +

    The evictor is disabled by default and can be configured using + the following properties:

    +
      +
    • timeBetweenEvictionRunsMillis - The number of + milliseconds between consecutive runs of the evictor. + Default: -1 (disabled)
    • +
    • numTestsPerEvictionRun - The number of connections + that will be checked for idleness by the evictor during each + run of the evictor. Default: 3
    • +
    • minEvictableIdleTimeMillis - The idle time in + milliseconds after which a connection can be removed from the pool + by the evictor. Default: 30*60*1000 (30 minutes)
    • +
    • testWhileIdle - true or false: whether a connection + should be validated by the evictor thread using the validation query + while sitting idle in the pool. Default: false
    • +
    +

    Another optional feature is the removal of abandoned connections. + A connection is called abandoned if the application does not return it + to the pool for a long time. The pool can close such connections + automatically and remove them from the pool. This is a workaround + for applications leaking connections.

    +

    The abandoning feature is disabled by default and can be configured + using the following properties:

    +
      +
    • removeAbandonedOnBorrow - true or false: whether to + remove abandoned connections from the pool when a connection is + borrowed. Default: false
    • +
    • removeAbandonedOnMaintenance - true or false: whether + to remove abandoned connections from the pool during pool maintenance. + Default: false
    • +
    • removeAbandonedTimeout - The number of + seconds after which a borrowed connection is assumed to be abandoned. + Default: 300
    • +
    • logAbandoned - true or false: whether to log + stack traces for application code which abandoned a statement + or connection. This adds serious overhead. Default: false
    • +
    +

    Finally there are various properties that allow further fine tuning + of the pool behaviour:

    +
      +
    • defaultAutoCommit - true or false: default + auto-commit state of the connections created by this pool. + Default: true
    • +
    • defaultReadOnly - true or false: default + read-only state of the connections created by this pool. + Default: false
    • +
    • defaultTransactionIsolation - This sets the + default transaction isolation level. Can be one of + NONE, READ_COMMITTED, + READ_UNCOMMITTED, REPEATABLE_READ, + SERIALIZABLE. Default: no default set
    • +
    • poolPreparedStatements - true or false: whether to + pool PreparedStatements and CallableStatements. Default: false
    • +
    • maxOpenPreparedStatements - The maximum number of open + statements that can be allocated from the statement pool at the same time. + Default: -1 (unlimited)
    • +
    • defaultCatalog - The name of the default catalog. + Default: not set
    • +
    • connectionInitSqls - A list of SQL statements + run once after a Connection is created. Separate multiple statements + by semicolons (;). Default: no statement
    • +
    • connectionProperties - A list of driver specific + properties passed to the driver for creating connections. Each + property is given as name=value, multiple properties + are separated by semicolons (;). Default: no properties
    • +
    • accessToUnderlyingConnectionAllowed - true or false: whether + accessing the underlying connections is allowed. Default: false
    • +
    +

    For more details, please refer to the Commons DBCP 2 documentation.

    + +
    + +

    Adding Custom Resource Factories

    + +

    If none of the standard resource factories meet your needs, you can write + your own factory and integrate it into Tomcat, and then configure the use + of this factory in the + <Context> element for + the web application. In the example below, we will create a factory that only + knows how to create com.mycompany.MyBean beans from the + Generic JavaBean Resources example + above.

    + +

    1. Write A Resource Factory Class

    + +

    You must write a class that implements the JNDI service provider + javax.naming.spi.ObjectFactory interface. Every time your + web application calls lookup() on a context entry that is + bound to this factory (assuming that the factory is configured with + singleton="false"), the + getObjectInstance() method is called, with the following + arguments:

    +
      +
    • Object obj - The (possibly null) object containing + location or reference information that can be used in creating an object. + For Tomcat, this will always be an object of type + javax.naming.Reference, which contains the class name of + this factory class, as well as the configuration properties (from the + <Context> for the + web application) to use in creating objects to be returned.
    • +
    • Name name - The name to which this factory is bound + relative to nameCtx, or null if no name + is specified.
    • +
    • Context nameCtx - The context relative to which the + name parameter is specified, or null if + name is relative to the default initial context.
    • +
    • Hashtable environment - The (possibly null) + environment that is used in creating this object. This is generally + ignored in Tomcat object factories.
    • +
    + +

    To create a resource factory that knows how to produce MyBean + instances, you might create a class like this:

    + +
    package com.mycompany;
    +
    +import java.util.Enumeration;
    +import java.util.Hashtable;
    +import javax.naming.Context;
    +import javax.naming.Name;
    +import javax.naming.NamingException;
    +import javax.naming.RefAddr;
    +import javax.naming.Reference;
    +import javax.naming.spi.ObjectFactory;
    +
    +public class MyBeanFactory implements ObjectFactory {
    +
    +  public Object getObjectInstance(Object obj,
    +      Name name2, Context nameCtx, Hashtable environment)
    +      throws NamingException {
    +
    +      // Acquire an instance of our specified bean class
    +      MyBean bean = new MyBean();
    +
    +      // Customize the bean properties from our attributes
    +      Reference ref = (Reference) obj;
    +      Enumeration addrs = ref.getAll();
    +      while (addrs.hasMoreElements()) {
    +          RefAddr addr = (RefAddr) addrs.nextElement();
    +          String name = addr.getType();
    +          String value = (String) addr.getContent();
    +          if (name.equals("foo")) {
    +              bean.setFoo(value);
    +          } else if (name.equals("bar")) {
    +              try {
    +                  bean.setBar(Integer.parseInt(value));
    +              } catch (NumberFormatException e) {
    +                  throw new NamingException("Invalid 'bar' value " + value);
    +              }
    +          }
    +      }
    +
    +      // Return the customized instance
    +      return (bean);
    +
    +  }
    +
    +}
    + +

    In this example, we are unconditionally creating a new instance of + the com.mycompany.MyBean class, and populating its properties + based on the parameters included in the <ResourceParams> + element that configures this factory (see below). You should note that any + parameter named factory should be skipped - that parameter is + used to specify the name of the factory class itself (in this case, + com.mycompany.MyBeanFactory) rather than a property of the + bean being configured.

    + +

    For more information about ObjectFactory, see the + + JNDI Service Provider Interface (SPI) Specification.

    + +

    You will need to compile this class against a class path that includes + all of the JAR files in the $CATALINA_HOME/lib directory. When you are through, + place the factory class (and the corresponding bean class) unpacked under + $CATALINA_HOME/lib, or in a JAR file inside + $CATALINA_HOME/lib. In this way, the required class + files are visible to both Catalina internal resources and your web + application.

    + +

    2. Declare Your Resource Requirements

    + +

    Next, modify your web application deployment descriptor + (/WEB-INF/web.xml) to declare the JNDI name under which + you will request new instances of this bean. The simplest approach is + to use a <resource-env-ref> element, like this:

    + +
    <resource-env-ref>
    +  <description>
    +    Object factory for MyBean instances.
    +  </description>
    +  <resource-env-ref-name>
    +    bean/MyBeanFactory
    +  </resource-env-ref-name>
    +  <resource-env-ref-type>
    +    com.mycompany.MyBean
    +  </resource-env-ref-type>
    +</resource-env-ref>
    + +

    WARNING - Be sure you respect the element ordering + that is required by the DTD for web application deployment descriptors! + See the + Servlet + Specification for details.

    + +

    3. Code Your Application's Use Of This Resource

    + +

    A typical use of this resource environment reference might look + like this:

    + +
    Context initCtx = new InitialContext();
    +Context envCtx = (Context) initCtx.lookup("java:comp/env");
    +MyBean bean = (MyBean) envCtx.lookup("bean/MyBeanFactory");
    +
    +writer.println("foo = " + bean.getFoo() + ", bar = " +
    +               bean.getBar());
    + +

    4. Configure Tomcat's Resource Factory

    + +

    To configure Tomcat's resource factory, add an elements like this to the + <Context> element for + this web application.

    + +
    <Context ...>
    +  ...
    +  <Resource name="bean/MyBeanFactory" auth="Container"
    +            type="com.mycompany.MyBean"
    +            factory="com.mycompany.MyBeanFactory"
    +            singleton="false"
    +            bar="23"/>
    +  ...
    +</Context>
    + +

    Note that the resource name (here, bean/MyBeanFactory + must match the value specified in the web application deployment + descriptor. We are also initializing the value of the bar + property, which will cause setBar(23) to be called before + the new bean is returned. Because we are not initializing the + foo property (although we could have), the bean will + contain whatever default value is set up by its constructor.

    + +

    You will also note that, from the application developer's perspective, + the declaration of the resource environment reference, and the programming + used to request new instances, is identical to the approach used for the + Generic JavaBean Resources example. This illustrates one of the + advantages of using JNDI resources to encapsulate functionality - you can + change the underlying implementation without necessarily having to + modify applications using the resources, as long as you maintain + compatible APIs.

    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/jspapi/index.html b/tomcat/docs/jspapi/index.html new file mode 100644 index 0000000..958a657 --- /dev/null +++ b/tomcat/docs/jspapi/index.html @@ -0,0 +1,34 @@ + + + + + + API docs + + + + +The JSP Javadoc is not installed by default. Download and install +the "fulldocs" package to get it. + +You can also access the javadoc online in the Tomcat + +documentation bundle. + + + diff --git a/tomcat/docs/logging.html b/tomcat/docs/logging.html new file mode 100644 index 0000000..31cbbce --- /dev/null +++ b/tomcat/docs/logging.html @@ -0,0 +1,437 @@ + +Apache Tomcat 8 (8.5.43) - Logging in Tomcat

    Logging in Tomcat

    Table of Contents

    Introduction

    +

    + The internal logging for Apache Tomcat uses JULI, a packaged renamed fork + of Apache Commons Logging + that is hard-coded to use the java.util.logging framework. + This ensures that Tomcat's internal logging and any web application + logging will remain independent, even if a web application uses Apache + Commons Logging. +

    + +

    + To configure Tomcat to use an alternative logging framework for its + internal logging, follow the instructions provided by the alternative + logging framework for redirecting logging for applications that use + java.util.logging. Keep in mind that the alternative logging + framework will need to be capable of working in an environment where + different loggers with the same name may exist in different class loaders. +

    + +

    + A web application running on Apache Tomcat can: +

    +
      +
    • + Use any logging framework of its choice. +
    • +
    • + Use system logging API, java.util.logging. +
    • +
    • + Use the logging API provided by the Java Servlets specification, + javax.servlet.ServletContext.log(...) +
    • +
    + +

    + The logging frameworks used by different web applications are independent. + See class loading for more details. + The exception to this rule is java.util.logging. If it used + directly or indirectly by your logging library then elements of it will be + shared across web applications because it is loaded by the system class + loader. +

    + +

    Java logging API — java.util.logging

    + +

    + Apache Tomcat has its own implementation of several key elements of + java.util.logging API. This implementation is called JULI. + The key component there is a custom LogManager implementation, + that is aware of different web applications running on Tomcat (and + their different class loaders). It supports private per-application + logging configurations. It is also notified by Tomcat when a web application + is unloaded from memory, so that the references to its classes can be + cleared, preventing memory leaks. +

    + +

    + This java.util.logging implementation is enabled by providing + certain system properties when starting Java. The Apache Tomcat startup + scripts do this for you, but if you are using different tools to run + Tomcat (such as jsvc, or running Tomcat from within an IDE), you should + take care of them by yourself. +

    + +

    + More details about java.util.logging may be found in the documentation + for your JDK and on its Javadoc pages for the java.util.logging + package. +

    + +

    + More details about Tomcat JULI may be found below. +

    + +
    + +

    Servlets logging API

    + +

    + The calls to javax.servlet.ServletContext.log(...) to write + log messages are handled by internal Tomcat logging. Such messages are + logged to the category named +

    +
    org.apache.catalina.core.ContainerBase.[${engine}].[${host}].[${context}]
    +

    + This logging is performed according to the Tomcat logging configuration. You + cannot overwrite it in a web application. +

    + +

    + The Servlets logging API predates the java.util.logging API + that is now provided by Java. As such, it does not offer you much options. + E.g., you cannot control the log levels. It can be noted, though, that + in Apache Tomcat implementation the calls to ServletContext.log(String) + or GenericServlet.log(String) are logged at the INFO level. + The calls to ServletContext.log(String, Throwable) or + GenericServlet.log(String, Throwable) + are logged at the SEVERE level. +

    + +
    + +

    Console

    + +

    + When running Tomcat on unixes, the console output is usually redirected + to the file named catalina.out. The name is configurable + using an environment variable. (See the startup scripts). + Whatever is written to System.err/out will be caught into + that file. That may include: +

    + +
      +
    • Uncaught exceptions printed by java.lang.ThreadGroup.uncaughtException(..)
    • +
    • Thread dumps, if you requested them via a system signal
    • +
    + +

    + When running as a service on Windows, the console output is also caught + and redirected, but the file names are different. +

    + +

    + The default logging configuration in Apache Tomcat writes the same + messages to the console and to a log file. This is great when using + Tomcat for development, but usually is not needed in production. +

    + +

    + Old applications that still use System.out or System.err + can be tricked by setting swallowOutput attribute on a + Context. If the attribute is set to + true, the calls to System.out/err during request + processing will be intercepted, and their output will be fed to the + logging subsystem using the + javax.servlet.ServletContext.log(...) calls.
    + Note, that the swallowOutput feature is + actually a trick, and it has its limitations. + It works only with direct calls to System.out/err, + and only during request processing cycle. It may not work in other + threads that might be created by the application. It cannot be used to + intercept logging frameworks that themselves write to the system streams, + as those start early and may obtain a direct reference to the streams + before the redirection takes place. +

    + +
    + +

    Access logging

    + +

    + Access logging is a related but different feature, which is + implemented as a Valve. It uses self-contained + logic to write its log files. The essential requirement for + access logging is to handle a large continuous stream of data + with low overhead, so it only uses Apache Commons Logging for + its own debug messages. This implementation approach avoids + additional overhead and potentially complex configuration. + Please refer to the Valves + documentation for more details on its configuration, including + the various report formats. +

    + +
    + +

    Using java.util.logging (default)

    + +

    + The default implementation of java.util.logging provided in the JDK is too + limited to be useful. The key limitation is the inability to have per-web + application logging, as the configuration is per-VM. As a result, Tomcat + will, in the default configuration, replace the default LogManager + implementation with a container friendly implementation called JULI, which + addresses these shortcomings. +

    +

    + JULI supports the same configuration mechanisms as the standard JDK + java.util.logging, using either a programmatic approach, or + properties files. The main difference is that per-classloader properties + files can be set (which enables easy redeployment friendly webapp + configuration), and the properties files support extended constructs which + allows more freedom for defining handlers and assigning them to loggers. +

    +

    + JULI is enabled by default, and supports per classloader configuration, in + addition to the regular global java.util.logging configuration. This means + that logging can be configured at the following layers: +

    +
      +
    • Globally. That is usually done in the + ${catalina.base}/conf/logging.properties file. + The file is specified by the java.util.logging.config.file + System property which is set by the startup scripts. + If it is not readable or is not configured, the default is to use the + ${java.home}/lib/logging.properties file in the JRE. +
    • +
    • In the web application. The file will be + WEB-INF/classes/logging.properties +
    • +
    +

    + The default logging.properties in the JRE specifies a + ConsoleHandler that routes logging to System.err. + The default conf/logging.properties in Apache Tomcat also + adds several AsyncFileHandlers that write to files. +

    +

    + A handler's log level threshold is INFO by default and can be set using + SEVERE, WARNING, INFO, CONFIG, + FINE, FINER, FINEST or ALL. + You can also target specific packages to collect logging from and specify + a level. +

    +

    + To enable debug logging for part of Tomcat's internals, you should + configure both the appropriate logger(s) and the appropriate handler(s) to + use the FINEST or ALL level. e.g.: +

    +
    org.apache.catalina.session.level=ALL
    +java.util.logging.ConsoleHandler.level=ALL
    +

    + When enabling debug logging it is recommended that it is enabled for the + narrowest possible scope as debug logging can generate large amounts of + information. +

    +

    + The configuration used by JULI is the same as the one supported by plain + java.util.logging, but uses a few extensions to allow better + flexibility in configuring loggers and handlers. The main differences are: +

    +
      +
    • A prefix may be added to handler names, so that multiple handlers of a + single class may be instantiated. A prefix is a String which starts with a + digit, and ends with '.'. For example, 22foobar. is a valid + prefix.
    • +
    • System property replacement is performed for property values which + contain ${systemPropertyName}.
    • +
    • If using a class loader that implements the + org.apache.juli.WebappProperties interface (Tomcat's + web application class loader does) then property replacement is also + performed for ${classloader.webappName}, + ${classloader.hostName} and + ${classloader.serviceName} which are replaced with the + web application name, the host name and the service name respectively. +
    • +
    • By default, loggers will not delegate to their parent if they have + associated handlers. This may be changed per logger using the + loggerName.useParentHandlers property, which accepts a + boolean value.
    • +
    • The root logger can define its set of handlers using the + .handlers property.
    • +
    • By default the log files will be kept on the file system forever. + This may be changed per handler using the + handlerName.maxDays property. If the specified value for the + property is ≤0 then the log files will be kept on the + file system forever, otherwise they will be kept the specified maximum + days.
    • +
    +

    + There are several additional implementation classes, that can be used + together with the ones provided by Java. The notable ones are + org.apache.juli.FileHandler and org.apache.juli.AsyncFileHandler. +

    +

    + org.apache.juli.FileHandler supports buffering of the + logs. The buffering is not enabled by default. To configure it, use the + bufferSize property of a handler. The value of 0 + uses system default buffering (typically an 8K buffer will be used). A + value of <0 forces a writer flush upon each log write. A + value >0 uses a BufferedOutputStream with the defined + value but note that the system default buffering will also be + applied. +

    +

    + org.apache.juli.AsyncFileHandler is a subclass of FileHandler + that queues the log messages and writes them asynchronously to the log files. + Its additional behaviour can be configured by setting some + system properties. +

    +

    + Example logging.properties file to be placed in $CATALINA_BASE/conf: +

    +
    handlers = 1catalina.org.apache.juli.FileHandler, \
    +           2localhost.org.apache.juli.FileHandler, \
    +           3manager.org.apache.juli.FileHandler, \
    +           java.util.logging.ConsoleHandler
    +
    +.handlers = 1catalina.org.apache.juli.FileHandler, java.util.logging.ConsoleHandler
    +
    +############################################################
    +# Handler specific properties.
    +# Describes specific configuration info for Handlers.
    +############################################################
    +
    +1catalina.org.apache.juli.FileHandler.level = FINE
    +1catalina.org.apache.juli.FileHandler.directory = ${catalina.base}/logs
    +1catalina.org.apache.juli.FileHandler.prefix = catalina.
    +1catalina.org.apache.juli.FileHandler.maxDays = 90
    +1catalina.org.apache.juli.FileHandler.encoding = UTF-8
    +
    +2localhost.org.apache.juli.FileHandler.level = FINE
    +2localhost.org.apache.juli.FileHandler.directory = ${catalina.base}/logs
    +2localhost.org.apache.juli.FileHandler.prefix = localhost.
    +2localhost.org.apache.juli.FileHandler.maxDays = 90
    +2localhost.org.apache.juli.FileHandler.encoding = UTF-8
    +
    +3manager.org.apache.juli.FileHandler.level = FINE
    +3manager.org.apache.juli.FileHandler.directory = ${catalina.base}/logs
    +3manager.org.apache.juli.FileHandler.prefix = manager.
    +3manager.org.apache.juli.FileHandler.bufferSize = 16384
    +3manager.org.apache.juli.FileHandler.maxDays = 90
    +3manager.org.apache.juli.FileHandler.encoding = UTF-8
    +
    +java.util.logging.ConsoleHandler.level = FINE
    +java.util.logging.ConsoleHandler.formatter = java.util.logging.OneLineFormatter
    +java.util.logging.ConsoleHandler.encoding = UTF-8
    +
    +############################################################
    +# Facility specific properties.
    +# Provides extra control for each logger.
    +############################################################
    +
    +org.apache.catalina.core.ContainerBase.[Catalina].[localhost].level = INFO
    +org.apache.catalina.core.ContainerBase.[Catalina].[localhost].handlers = \
    +   2localhost.org.apache.juli.FileHandler
    +
    +org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager].level = INFO
    +org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager].handlers = \
    +   3manager.org.apache.juli.FileHandler
    +
    +# For example, set the org.apache.catalina.util.LifecycleBase logger to log
    +# each component that extends LifecycleBase changing state:
    +#org.apache.catalina.util.LifecycleBase.level = FINE
    + +

    + Example logging.properties for the servlet-examples web application to be + placed in WEB-INF/classes inside the web application: +

    +
    handlers = org.apache.juli.FileHandler, java.util.logging.ConsoleHandler
    +
    +############################################################
    +# Handler specific properties.
    +# Describes specific configuration info for Handlers.
    +############################################################
    +
    +org.apache.juli.FileHandler.level = FINE
    +org.apache.juli.FileHandler.directory = ${catalina.base}/logs
    +org.apache.juli.FileHandler.prefix = ${classloader.webappName}.
    +
    +java.util.logging.ConsoleHandler.level = FINE
    +java.util.logging.ConsoleHandler.formatter = java.util.logging.OneLineFormatter
    + + +

    Documentation references

    +

    See the following resources for additional information:

    + +
    + +

    Considerations for production usage

    +

    You may want to take note of the following:

    +
      +
    • Consider removing ConsoleHandler from configuration. By + default (thanks to the .handlers setting) logging goes both + to a FileHandler and to a ConsoleHandler. The + output of the latter one is usually captured into a file, such as + catalina.out. Thus you end up with two copies of the same + messages.
    • +
    • Consider removing FileHandlers for the applications + that you do not use. E.g., the one for host-manager.
    • +
    • The handlers by default use the system default encoding to write + the log files. It can be configured with encoding property. + See Javadoc for details.
    • +
    • Consider configuring an + Access log.
    • +
    +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/manager-howto.html b/tomcat/docs/manager-howto.html new file mode 100644 index 0000000..6e3a818 --- /dev/null +++ b/tomcat/docs/manager-howto.html @@ -0,0 +1,1460 @@ + +Apache Tomcat 8 (8.5.43) - Manager App How-To

    Manager App How-To

    Table of Contents

    Introduction

    + +

    In many production environments, it is very useful to have the capability +to deploy a new web application, or undeploy an existing one, without having +to shut down and restart the entire container. In addition, you can request +an existing application to reload itself, even if you have not declared it +to be reloadable in the Tomcat server +configuration file.

    + +

    To support these capabilities, Tomcat includes a web application +(installed by default on context path /manager) that supports +the following functions:

    +
      +
    • Deploy a new web application from the uploaded contents of a WAR file.
    • +
    • Deploy a new web application, on a specified context path, from the + server file system.
    • +
    • List the currently deployed web applications, as well as the + sessions that are currently active for those web apps.
    • +
    • Reload an existing web application, to reflect changes in the + contents of /WEB-INF/classes or /WEB-INF/lib. +
    • +
    • List the OS and JVM property values.
    • +
    • List the available global JNDI resources, for use in deployment + tools that are preparing <ResourceLink> elements + nested in a <Context> deployment description.
    • +
    • Start a stopped application (thus making it available again).
    • +
    • Stop an existing application (so that it becomes unavailable), but + do not undeploy it.
    • +
    • Undeploy a deployed web application and delete its document base + directory (unless it was deployed from file system).
    • +
    + +

    A default Tomcat installation includes the Manager. To add an instance of the +Manager web application Context to a new host install the +manager.xml context configuration file in the +$CATALINA_BASE/conf/[enginename]/[hostname] folder. Here is an +example:

    +
    <Context privileged="true" antiResourceLocking="false"
    +         docBase="${catalina.home}/webapps/manager">
    +  <Valve className="org.apache.catalina.valves.RemoteAddrValve"
    +         allow="127\.0\.0\.1" />
    +</Context>
    + +

    If you have Tomcat configured to support multiple virtual hosts +(websites) you would need to configure a Manager for each.

    + +

    There are three ways to use the Manager web application.

    +
      +
    • As an application with a user interface you use in your browser. +Here is an example URL where you can replace localhost with +your website host name: http://localhost:8080/manager/html .
    • +
    • A minimal version using HTTP requests only which is suitable for use +by scripts setup by system administrators. Commands are given as part of the +request URI, and responses are in the form of simple text that can be easily +parsed and processed. See +Supported Manager Commands for more information.
    • +
    • A convenient set of task definitions for the Ant +(version 1.4 or later) build tool. See +Executing Manager Commands +With Ant for more information.
    • +
    + +

    Configuring Manager Application Access

    + + +

    The description below uses the variable name $CATALINA_BASE to refer the + base directory against which most relative paths are resolved. If you have + not configured Tomcat for multiple instances by setting a CATALINA_BASE + directory, then $CATALINA_BASE will be set to the value of $CATALINA_HOME, + the directory into which you have installed Tomcat.

    + + +

    It would be quite unsafe to ship Tomcat with default settings that allowed +anyone on the Internet to execute the Manager application on your server. +Therefore, the Manager application is shipped with the requirement that anyone +who attempts to use it must authenticate themselves, using a username and +password that have one of manager-xxx roles associated with +them (the role name depends on what functionality is required). +Further, there is no username in the default users file +($CATALINA_BASE/conf/tomcat-users.xml) that is assigned to those +roles. Therefore, access to the Manager application is completely disabled +by default.

    + +

    You can find the role names in the web.xml file of the Manager +web application. The available roles are:

    + +
      +
    • manager-gui — Access to the HTML interface.
    • +
    • manager-status — Access to the "Server Status" + page only.
    • +
    • manager-script — Access to the tools-friendly + plain text interface that is described in this document, + and to the "Server Status" page.
    • +
    • manager-jmx — Access to JMX proxy interface + and to the "Server Status" page.
    • +
    + +

    The HTML interface is protected against CSRF (Cross-Site Request Forgery) +attacks, but the text and JMX interfaces cannot be protected. It means that +users who are allowed access to the text and JMX interfaces have to be cautious +when accessing the Manager application with a web browser. +To maintain the CSRF protection:

    + +
      +
    • If you use web browser to access the Manager application using + a user that has either manager-script or + manager-jmx roles (for example for testing + the plain text or JMX interfaces), you MUST close all windows + of the browser afterwards to terminate the session. + If you do not close the browser and visit other sites, you may become + victim of a CSRF attack.
    • +
    • It is recommended to never grant + the manager-script or manager-jmx + roles to users that have the manager-gui role.
    • +
    + +

    Note that JMX proxy interface is effectively low-level root-like +administrative interface of Tomcat. One can do a lot, if he knows +what commands to call. You should be cautious when enabling the +manager-jmx role.

    + +

    To enable access to the Manager web application, you must either create +a new username/password combination and associate one of the +manager-xxx roles with it, or add a +manager-xxx role +to some existing username/password combination. +As the majority of this document describes the using the text interface, this +example will use the role name manager-script. +Exactly how the usernames/passwords are configured depends on which +Realm implementation you are using:

    +
      +
    • UserDatabaseRealm plus MemoryUserDatabase, or MemoryRealm + — The UserDatabaseRealm and MemoryUserDatabase are + configured in the default $CATALINA_BASE/conf/server.xml. + Both MemoryUserDatabase and MemoryRealm read an + XML-format file by default stored at + $CATALINA_BASE/conf/tomcat-users.xml, which can be + edited with any text editor. This file contains an XML + <user> for each individual user, which might + look something like this: +
      <user username="craigmcc" password="secret" roles="standard,manager-script" />
      + which defines the username and password used by this individual to + log on, and the role names he or she is associated with. You can + add the manager-script role to the comma-delimited + roles attribute for one or more existing users, and/or + create new users with that assigned role.
    • +
    • DataSourceRealm or JDBCRealm + — Your user and role information is stored in + a database accessed via JDBC. Add the manager-script role + to one or more existing users, and/or create one or more new users + with this role assigned, following the standard procedures for your + environment.
    • +
    • JNDIRealm — Your user and role information is stored in + a directory server accessed via LDAP. Add the + manager-script role to one or more existing users, + and/or create one or more new users with this role assigned, following + the standard procedures for your environment.
    • +
    + +

    The first time you attempt to issue one of the Manager commands +described in the next section, you will be challenged to log on using +BASIC authentication. The username and password you enter do not matter, +as long as they identify a valid user in the users database who possesses +the role manager-script.

    + +

    In addition to the password restrictions, access to the Manager web +application can be restricted by the remote IP address or host +by adding a RemoteAddrValve or RemoteHostValve. +See valves documentation +for details. Here is +an example of restricting access to the localhost by IP address:

    +
    <Context privileged="true">
    +         <Valve className="org.apache.catalina.valves.RemoteAddrValve"
    +                allow="127\.0\.0\.1"/>
    +</Context>
    + +

    HTML User-friendly Interface

    + +

    The user-friendly HTML interface of Manager web application is located at

    + +
    http://{host}:{port}/manager/html
    + +

    As has already been mentioned above, you need manager-gui +role to be allowed to access it. There is a separate document that provides +help on this interface. See:

    + + + +

    The HTML interface is protected against CSRF (Cross-Site Request Forgery) +attacks. Each access to the HTML pages generates a random token, which is +stored in your session and is included in all links on the page. If your next +action does not have correct value of the token, the action will be denied. +If the token has expired you can start again from the main page or +List Applications page of Manager.

    + +

    Supported Manager Commands

    + +

    All commands that the Manager application knows how to process are +specified in a single request URI like this:

    +
    http://{host}:{port}/manager/text/{command}?{parameters}
    +

    where {host} and {port} represent the hostname +and port number on which Tomcat is running, {command} +represents the Manager command you wish to execute, and +{parameters} represents the query parameters +that are specific to that command. In the illustrations below, customize +the host and port appropriately for your installation.

    + +

    The commands are usually executed by HTTP GET requests. The +/deploy command has a form that is executed by an HTTP PUT request.

    + +

    Common Parameters

    + +

    Most commands accept one or more of the following query parameters:

    +
      +
    • path - The context path (including the leading slash) + of the web application you are dealing with. To select the ROOT web + application, specify "/". NOTE: + It is not possible to perform administrative commands on the + Manager application itself.
    • +
    • version - The version of this web application as used by + the parallel deployment feature. If you + use parallel deployment wherever a path is required you must specify a + version in addition to the path and it is the combination of path and + version that must be unique rather than just the path.
    • +
    • war - URL of a web application archive (WAR) file, or + pathname of a directory which contains the web application, or a + Context configuration ".xml" file. You can use URLs in any of the + following formats: +
        +
      • file:/absolute/path/to/a/directory - The absolute + path of a directory that contains the unpacked version of a web + application. This directory will be attached to the context path + you specify without any changes.
      • +
      • file:/absolute/path/to/a/webapp.war - The absolute + path of a web application archive (WAR) file. This is valid + only for the /deploy command, and is + the only acceptable format to that command.
      • +
      • file:/absolute/path/to/a/context.xml - The + absolute path of a web application Context configuration ".xml" + file which contains the Context configuration element.
      • +
      • directory - The directory name for the web + application context in the Host's application base directory.
      • +
      • webapp.war - The name of a web application war file + located in the Host's application base directory.
      • +
    • +
    + +

    Each command will return a response in text/plain format +(i.e. plain ASCII with no HTML markup), making it easy for both humans and +programs to read). The first line of the response will begin with either +OK or FAIL, indicating whether the requested +command was successful or not. In the case of failure, the rest of the first +line will contain a description of the problem that was encountered. Some +commands include additional lines of information as described below.

    + +

    Internationalization Note - The Manager application looks up +its message strings in resource bundles, so it is possible that the strings +have been translated for your platform. The examples below show the English +version of the messages.

    + +
    + +

    Deploy A New Application Archive (WAR) Remotely

    + +
    http://localhost:8080/manager/text/deploy?path=/foo
    + +

    Upload the web application archive (WAR) file that is specified as the +request data in this HTTP PUT request, install it into the appBase +directory of our corresponding virtual host, and start, deriving the name for +the WAR file added to the appBase from the specified path. The +application can later be undeployed (and the corresponding WAR file removed) by +use of the /undeploy command.

    + +

    This command is executed by an HTTP PUT request.

    + +

    The .WAR file may include Tomcat specific deployment configuration, by +including a Context configuration XML file in +/META-INF/context.xml.

    + +

    URL parameters include:

    +
      +
    • update: When set to true, any existing update will be + undeployed first. The default value is set to false.
    • +
    • tag: Specifying a tag name, this allows associating the + deployed webapp with a tag or label. If the web application is undeployed, + it can be later redeployed when needed using only the tag.
    • +
    + +

    NOTE - This command is the logical +opposite of the /undeploy command.

    + +

    If installation and startup is successful, you will receive a response +like this:

    +
    OK - Deployed application at context path /foo
    + +

    Otherwise, the response will start with FAIL and include an +error message. Possible causes for problems include:

    +
      +
    • Application already exists at path /foo +

      The context paths for all currently running web applications must be + unique. Therefore, you must undeploy the existing web + application using this context path, or choose a different context path + for the new one. The update parameter may be specified as + a parameter on the URL, with a value of true to avoid this + error. In that case, an undeploy will be performed on an existing + application before performing the deployment.

      +
    • +
    • Encountered exception +

      An exception was encountered trying to start the new web application. + Check the Tomcat logs for the details, but likely explanations include + problems parsing your /WEB-INF/web.xml file, or missing + classes encountered when initializing application event listeners and + filters.

      +
    • +
    + +
    + +

    Deploy A New Application from a Local Path

    + +

    Deploy and start a new web application, attached to the specified context +path (which must not be in use by any other web application). +This command is the logical opposite of the /undeploy command.

    + +

    This command is executed by an HTTP GET request. +There are a number of different ways the deploy command can be used.

    + +

    Deploy a previously deployed webapp

    + +
    http://localhost:8080/manager/text/deploy?path=/footoo&tag=footag
    + +

    This can be used to deploy a previously deployed web application, which +has been deployed using the tag attribute. Note that the work +directory of the Manager webapp will contain the previously deployed WARs; +removing it would make the deployment fail.

    + +
    + +

    Deploy a Directory or WAR by URL

    + +

    Deploy a web application directory or ".war" file located on the Tomcat +server. If no path is specified, the path and version are derived +from the directory name or the war file name. The war parameter +specifies a URL (including the file: scheme) for either +a directory or a web application archive (WAR) file. The supported syntax for +a URL referring to a WAR file is described on the Javadocs page for the +java.net.JarURLConnection class. Use only URLs that refer to +the entire WAR file.

    + +

    In this example the web application located in the directory +/path/to/foo on the Tomcat server is deployed as the +web application context named /footoo.

    +
    http://localhost:8080/manager/text/deploy?path=/footoo&war=file:/path/to/foo
    + + +

    In this example the ".war" file /path/to/bar.war on the +Tomcat server is deployed as the web application context named +/bar. Notice that there is no path parameter +so the context path defaults to the name of the web application archive +file without the ".war" extension.

    +
    http://localhost:8080/manager/text/deploy?war=file:/path/to/bar.war
    + +
    + +

    Deploy a Directory or War from the Host appBase

    + +

    Deploy a web application directory or ".war" file located in your Host +appBase directory. The path and optional version are derived from the directory +or war file name.

    + +

    In this example the web application located in a sub directory named +foo in the Host appBase directory of the Tomcat server is +deployed as the web application context named /foo. Notice +that the context path used is the name of the web application directory.

    +
    http://localhost:8080/manager/text/deploy?war=foo
    + + +

    In this example the ".war" file bar.war located in your +Host appBase directory on the Tomcat server is deployed as the web +application context named /bar.

    +
    http://localhost:8080/manager/text/deploy?war=bar.war
    + +
    + +

    Deploy using a Context configuration ".xml" file

    + +

    If the Host deployXML flag is set to true you can deploy a web +application using a Context configuration ".xml" file and an optional +".war" file or web application directory. The context path +is not used when deploying a web application using a context ".xml" +configuration file.

    + +

    A Context configuration ".xml" file can contain valid XML for a +web application Context just as if it were configured in your +Tomcat server.xml configuration file. Here is an +example:

    +
    <Context path="/foobar" docBase="/path/to/application/foobar">
    +</Context>
    + + +

    When the optional war parameter is set to the URL +for a web application ".war" file or directory it overrides any +docBase configured in the context configuration ".xml" file.

    + +

    Here is an example of deploying an application using a Context +configuration ".xml" file.

    +
    http://localhost:8080/manager/text/deploy?config=file:/path/context.xml
    + + +

    Here is an example of deploying an application using a Context +configuration ".xml" file and a web application ".war" file located +on the server.

    +
    http://localhost:8080/manager/text/deploy
    + ?config=file:/path/context.xml&war=file:/path/bar.war
    + +
    + +

    Deployment Notes

    + +

    If the Host is configured with unpackWARs=true and you deploy a war +file, the war will be unpacked into a directory in your Host appBase +directory.

    + +

    If the application war or directory is installed in your Host appBase +directory and either the Host is configured with autoDeploy=true or the +Context path must match the directory name or war file name without the +".war" extension.

    + +

    For security when untrusted users can manage web applications, the +Host deployXML flag can be set to false. This prevents untrusted users +from deploying web applications using a configuration XML file and +also prevents them from deploying application directories or ".war" +files located outside of their Host appBase.

    + +
    + +

    Deploy Response

    + +

    If installation and startup is successful, you will receive a response +like this:

    +
    OK - Deployed application at context path /foo
    + +

    Otherwise, the response will start with FAIL and include an +error message. Possible causes for problems include:

    +
      +
    • Application already exists at path /foo +

      The context paths for all currently running web applications must be + unique. Therefore, you must undeploy the existing web + application using this context path, or choose a different context path + for the new one. The update parameter may be specified as + a parameter on the URL, with a value of true to avoid this + error. In that case, an undeploy will be performed on an existing + application before performing the deployment.

      +
    • +
    • Document base does not exist or is not a readable directory +

      The URL specified by the war parameter must identify a + directory on this server that contains the "unpacked" version of a + web application, or the absolute URL of a web application archive (WAR) + file that contains this application. Correct the value specified by + the war parameter.

      +
    • +
    • Encountered exception +

      An exception was encountered trying to start the new web application. + Check the Tomcat logs for the details, but likely explanations include + problems parsing your /WEB-INF/web.xml file, or missing + classes encountered when initializing application event listeners and + filters.

      +
    • +
    • Invalid application URL was specified +

      The URL for the directory or web application that you specified + was not valid. Such URLs must start with file:, and URLs + for a WAR file must end in ".war".

      +
    • +
    • Invalid context path was specified +

      The context path must start with a slash character. To reference the + ROOT web application use "/".

      +
    • +
    • Context path must match the directory or WAR file name: +

      If the application war or directory is installed in your Host appBase + directory and either the Host is configured with autoDeploy=true the + Context path must match the directory name or war file name without + the ".war" extension.

      +
    • +
    • Only web applications in the Host web application directory can + be installed +

      + If the Host deployXML flag is set to false this error will happen + if an attempt is made to deploy a web application directory or + ".war" file outside of the Host appBase directory. +

    • +
    + +
    +
    + +

    List Currently Deployed Applications

    + +
    http://localhost:8080/manager/text/list
    + +

    List the context paths, current status (running or +stopped), and number of active sessions for all currently +deployed web applications. A typical response immediately +after starting Tomcat might look like this:

    +
    OK - Listed applications for virtual host localhost
    +/webdav:running:0:webdav
    +/examples:running:0:examples
    +/manager:running:0:manager
    +/:running:0:ROOT
    +/test:running:0:test##2
    +/test:running:0:test##1
    + +
    + +

    Reload An Existing Application

    + +
    http://localhost:8080/manager/text/reload?path=/examples
    + +

    Signal an existing application to shut itself down and reload. This can +be useful when the web application context is not reloadable and you have +updated classes or property files in the /WEB-INF/classes +directory or when you have added or updated jar files in the +/WEB-INF/lib directory. +

    + +

    If this command succeeds, you will see a response like this:

    +
    OK - Reloaded application at context path /examples
    + +

    Otherwise, the response will start with FAIL and include an +error message. Possible causes for problems include:

    +
      +
    • Encountered exception +

      An exception was encountered trying to restart the web application. + Check the Tomcat logs for the details.

      +
    • +
    • Invalid context path was specified +

      The context path must start with a slash character. To reference the + ROOT web application use "/".

      +
    • +
    • No context exists for path /foo +

      There is no deployed application on the context path + that you specified.

      +
    • +
    • No context path was specified +

      + The path parameter is required. +

    • +
    • Reload not supported on WAR deployed at path /foo +

      + Currently, application reloading (to pick up changes to the classes or + web.xml file) is not supported when a web application is + deployed directly from a WAR file. It only works when the web application + is deployed from an unpacked directory. If you are using a WAR file, + you should undeploy and then deploy or + deploy with the update parameter the + application again to pick up your changes. +

    • +
    + +
    + +

    List OS and JVM Properties

    + +
    http://localhost:8080/manager/text/serverinfo
    + +

    Lists information about the Tomcat version, OS, and JVM properties.

    + +

    If an error occurs, the response will start with FAIL and +include an error message. Possible causes for problems include:

    +
      +
    • Encountered exception +

      An exception was encountered trying to enumerate the system properties. + Check the Tomcat logs for the details.

      +
    • +
    + +
    + +

    List Available Global JNDI Resources

    + +
    http://localhost:8080/manager/text/resources[?type=xxxxx]
    + +

    List the global JNDI resources that are available for use in resource +links for context configuration files. If you specify the type +request parameter, the value must be the fully qualified Java class name of +the resource type you are interested in (for example, you would specify +javax.sql.DataSource to acquire the names of all available +JDBC data sources). If you do not specify the type request +parameter, resources of all types will be returned.

    + +

    Depending on whether the type request parameter is specified +or not, the first line of a normal response will be:

    +
    OK - Listed global resources of all types
    +

    or

    +
    OK - Listed global resources of type xxxxx
    +

    followed by one line for each resource. Each line is composed of fields +delimited by colon characters (":"), as follows:

    +
      +
    • Global Resource Name - The name of this global JNDI resource, + which would be used in the global attribute of a + <ResourceLink> element.
    • +
    • Global Resource Type - The fully qualified Java class name of + this global JNDI resource.
    • +
    + +

    If an error occurs, the response will start with FAIL and +include an error message. Possible causes for problems include:

    +
      +
    • Encountered exception +

      An exception was encountered trying to enumerate the global JNDI + resources. Check the Tomcat logs for the details.

      +
    • +
    • No global JNDI resources are available +

      The Tomcat server you are running has been configured without + global JNDI resources.

      +
    • +
    + + +
    + +

    Session Statistics

    + +
    http://localhost:8080/manager/text/sessions?path=/examples
    + +

    Display the default session timeout for a web application, and the +number of currently active sessions that fall within one-minute ranges of +their actual timeout times. For example, after restarting Tomcat and then +executing one of the JSP samples in the /examples web app, +you might get something like this:

    + +
    OK - Session information for application at context path /examples
    +Default maximum session inactive interval 30 minutes
    +<1 minutes: 1 sessions
    +1 - <2 minutes: 1 sessions
    + +
    + +

    Expire Sessions

    + +
    http://localhost:8080/manager/text/expire?path=/examples&idle=num
    + +

    Display the session statistics (like the above /sessions +command) and expire sessions that are idle for longer than num +minutes. To expire all sessions, use &idle=0 .

    + +
    OK - Session information for application at context path /examples
    +Default maximum session inactive interval 30 minutes
    +1 - <2 minutes: 1 sessions
    +3 - <4 minutes: 1 sessions
    +>0 minutes: 2 sessions were expired
    + +

    Actually /sessions and /expire are synonyms for +the same command. The difference is in the presence of idle +parameter.

    + +
    + +

    Start an Existing Application

    + +
    http://localhost:8080/manager/text/start?path=/examples
    + +

    Signal a stopped application to restart, and make itself available again. +Stopping and starting is useful, for example, if the database required by +your application becomes temporarily unavailable. It is usually better to +stop the web application that relies on this database rather than letting +users continuously encounter database exceptions.

    + +

    If this command succeeds, you will see a response like this:

    +
    OK - Started application at context path /examples
    + +

    Otherwise, the response will start with FAIL and include an +error message. Possible causes for problems include:

    +
      +
    • Encountered exception +

      An exception was encountered trying to start the web application. + Check the Tomcat logs for the details.

      +
    • +
    • Invalid context path was specified +

      The context path must start with a slash character. To reference the + ROOT web application use "/".

      +
    • +
    • No context exists for path /foo +

      There is no deployed application on the context path + that you specified.

      +
    • +
    • No context path was specified +

      + The path parameter is required. +

    • +
    + +
    + +

    Stop an Existing Application

    + +
    http://localhost:8080/manager/text/stop?path=/examples
    + +

    Signal an existing application to make itself unavailable, but leave it +deployed. Any request that comes in while an application is +stopped will see an HTTP error 404, and this application will show as +"stopped" on a list applications command.

    + +

    If this command succeeds, you will see a response like this:

    +
    OK - Stopped application at context path /examples
    + +

    Otherwise, the response will start with FAIL and include an +error message. Possible causes for problems include:

    +
      +
    • Encountered exception +

      An exception was encountered trying to stop the web application. + Check the Tomcat logs for the details.

      +
    • +
    • Invalid context path was specified +

      The context path must start with a slash character. To reference the + ROOT web application use "/".

      +
    • +
    • No context exists for path /foo +

      There is no deployed application on the context path + that you specified.

      +
    • +
    • No context path was specified + The path parameter is required. +
    • +
    + +
    + + +

    Undeploy an Existing Application

    + +
    http://localhost:8080/manager/text/undeploy?path=/examples
    + +

    WARNING - This command will delete any web +application artifacts that exist within appBase directory +(typically "webapps") for this virtual host. +This will delete the application .WAR, if present, +the application directory resulting either from a deploy in unpacked form +or from .WAR expansion as well as the XML Context definition from +$CATALINA_BASE/conf/[enginename]/[hostname]/ directory. +If you simply want to take an application +out of service, you should use the /stop command instead.

    + +

    Signal an existing application to gracefully shut itself down, and +remove it from Tomcat (which also makes this context path available for +reuse later). In addition, the document root directory is removed, if it +exists in the appBase directory (typically "webapps") for +this virtual host. This command is the logical opposite of the +/deploy command.

    + +

    If this command succeeds, you will see a response like this:

    +
    OK - Undeployed application at context path /examples
    + +

    Otherwise, the response will start with FAIL and include an +error message. Possible causes for problems include:

    +
      +
    • Encountered exception +

      An exception was encountered trying to undeploy the web application. + Check the Tomcat logs for the details.

      +
    • +
    • Invalid context path was specified +

      The context path must start with a slash character. To reference the + ROOT web application use "/".

      +
    • +
    • No context exists named /foo +

      There is no deployed application with the name that you specified.

      +
    • +
    • No context path was specified + The path parameter is required. +
    • +
    + +
    + +

    Finding memory leaks

    + +
    http://localhost:8080/manager/text/findleaks[?statusLine=[true|false]]
    + +

    The find leaks diagnostic triggers a full garbage collection. It +should be used with extreme caution on production systems.

    + +

    The find leaks diagnostic attempts to identify web applications that have +caused memory leaks when they were stopped, reloaded or undeployed. Results +should always be confirmed +with a profiler. The diagnostic uses additional functionality provided by the +StandardHost implementation. It will not work if a custom host is used that +does not extend StandardHost.

    + +

    Explicitly triggering a full garbage collection from Java code is documented +to be unreliable. Furthermore, depending on the JVM used, there are options to +disable explicit GC triggering, like -XX:+DisableExplicitGC. +If you want to make sure, that the diagnostics were successfully running a full +GC, you will need to check using tools like GC logging, JConsole or similar.

    + +

    If this command succeeds, you will see a response like this:

    +
    /leaking-webapp
    + +

    If you wish to see a status line included in the response then include the +statusLine query parameter in the request with a value of +true.

    + +

    Each context path for a web application that was stopped, reloaded or +undeployed, but which classes from the previous runs are still loaded in memory, +thus causing a memory leak, will be listed on a new line. If an application +has been reloaded several times, it may be listed several times.

    + +

    If the command does not succeed, the response will start with +FAIL and include an error message.

    + +
    + +

    Connector SSL/TLS cipher information

    + +
    http://localhost:8080/manager/text/sslConnectorCiphers
    + +

    The SSL Connector/Ciphers diagnostic lists the SSL/TLS ciphers that are currently +configured for each connector. For NIO and NIO2, the names of the individual +cipher suites are listed. For APR, the value of SSLCipherSuite is returned.

    + +

    The response will look something like this:

    +
    OK - Connector / SSL Cipher information
    +Connector[HTTP/1.1-8080]
    +  SSL is not enabled for this connector
    +Connector[HTTP/1.1-8443]
    +  TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA
    +  TLS_DHE_RSA_WITH_AES_128_CBC_SHA
    +  TLS_ECDH_RSA_WITH_AES_128_CBC_SHA
    +  TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA
    +  ...
    + +
    + +

    Connector SSL/TLS certificate chain information

    + +
    http://localhost:8080/manager/text/sslConnectorCerts
    + +

    The SSL Connector/Certs diagnostic lists the certificate chain that is +currently configured for each virtual host.

    + +

    The response will look something like this:

    +
    OK - Connector / Certificate Chain information
    +Connector[HTTP/1.1-8080]
    +SSL is not enabled for this connector
    +Connector[HTTP/1.1-8443]-_default_-RSA
    +[
    +[
    +  Version: V3
    +  Subject: CN=localhost, OU=Apache Tomcat PMC, O=The Apache Software Foundation, L=Wakefield, ST=MA, C=US
    +  Signature Algorithm: SHA256withRSA, OID = 1.2.840.113549.1.1.11
    +  ...
    + +
    + +

    Connector SSL/TLS trusted certificate information

    + +
    http://localhost:8080/manager/text/sslConnectorTrustedCerts
    + +

    The SSL Connector/Certs diagnostic lists the trusted certificates that are +currently configured for each virtual host.

    + +

    The response will look something like this:

    +
    OK - Connector / Trusted Certificate information
    +Connector[HTTP/1.1-8080]
    +SSL is not enabled for this connector
    +Connector[AJP/1.3-8009]
    +SSL is not enabled for this connector
    +Connector[HTTP/1.1-8443]-_default_
    +[
    +[
    +  Version: V3
    +  Subject: CN=Apache Tomcat Test CA, OU=Apache Tomcat PMC, O=The Apache Software Foundation, L=Wakefield, ST=MA, C=US
    +  ...
    + +
    + +

    Reload TLS configuration

    + +
    http://localhost:8080/manager/text/sslReload?tlsHostName=name
    + +

    Reload the TLS configuration files (the certificate and key files, this does +not trigger a re-parsing of server.xml). To reload the files for all hosts don't +specify the tlsHostName parameter.

    + +
    OK - Reloaded TLS configuration for [_default_]
    + +
    + +

    Thread Dump

    + +
    http://localhost:8080/manager/text/threaddump
    + +

    Write a JVM thread dump.

    + +

    The response will look something like this:

    +
    OK - JVM thread dump
    +2014-12-08 07:24:40.080
    +Full thread dump Java HotSpot(TM) Client VM (25.25-b02 mixed mode):
    +
    +"http-nio-8080-exec-2" Id=26 cpu=46800300 ns usr=46800300 ns blocked 0 for -1 ms waited 0 for -1 ms
    +   java.lang.Thread.State: RUNNABLE
    +        locks java.util.concurrent.ThreadPoolExecutor$Worker@1738ad4
    +        at sun.management.ThreadImpl.dumpThreads0(Native Method)
    +        at sun.management.ThreadImpl.dumpAllThreads(ThreadImpl.java:446)
    +        at org.apache.tomcat.util.Diagnostics.getThreadDump(Diagnostics.java:440)
    +        at org.apache.tomcat.util.Diagnostics.getThreadDump(Diagnostics.java:409)
    +        at org.apache.catalina.manager.ManagerServlet.threadDump(ManagerServlet.java:557)
    +        at org.apache.catalina.manager.ManagerServlet.doGet(ManagerServlet.java:371)
    +        at javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
    +        at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    +...
    +
    + +
    + +

    VM Info

    + +
    http://localhost:8080/manager/text/vminfo
    + +

    Write some diagnostic information about Java Virtual Machine.

    + +

    The response will look something like this:

    +
    OK - VM info
    +2014-12-08 07:27:32.578
    +Runtime information:
    +  vmName: Java HotSpot(TM) Client VM
    +  vmVersion: 25.25-b02
    +  vmVendor: Oracle Corporation
    +  specName: Java Virtual Machine Specification
    +  specVersion: 1.8
    +  specVendor: Oracle Corporation
    +  managementSpecVersion: 1.2
    +  name: ...
    +  startTime: 1418012458849
    +  uptime: 393855
    +  isBootClassPathSupported: true
    +
    +OS information:
    +...
    +
    + +
    + +

    Save Configuration

    + +
    http://localhost:8080/manager/text/save
    + +

    If specified without any parameters, this command saves the current +configuration of the server to server.xml. The existing file will be renamed as +a backup if required.

    + +

    If specified with a path parameter that matches the path of +a deployed web application then the configuration for that web application will +be saved to an appropriately named context.xml file in the xmlBase +for the current Host.

    + +

    To use the command a StoreConfig MBean must be present. Typically this is +configured using the StoreConfigLifecycleListener. +

    + +

    If the command does not succeed, the response will start with +FAIL and include an error message.

    + +
    + +

    Server Status

    + +

    From the following links you can view Status information about the server. +Any one of manager-xxx roles allows access to this page.

    + +
    http://localhost:8080/manager/status
    +http://localhost:8080/manager/status/all
    + +

    Displays server status information in HTML format.

    + +
    http://localhost:8080/manager/status?XML=true
    +http://localhost:8080/manager/status/all?XML=true
    + +

    Displays server status information in XML format.

    + +

    First, you have the server and JVM version number, JVM provider, OS name +and number followed by the architecture type.

    + +

    Second, there is information about the memory usage of the JVM.

    + +

    Then, there is information about the Tomcat AJP and HTTP connectors. +The same information is available for both of them : +

    +
      +
    • Threads information : Max threads, min and max spare threads, + current thread count and current thread busy.

    • +
    • Request information : Max processing time and processing time, + request and error count, bytes received and sent.

    • +
    • A table showing Stage, Time, Bytes Sent, Bytes Receive, Client, + VHost and Request. All existing threads are listed in the table. + Here is the list of the possible thread stages :

      +
        +
      • "Parse and Prepare Request" : The request headers are + being parsed or the necessary preparation to read the request body (if + a transfer encoding has been specified) is taking place.

      • +
      • "Service" : The thread is processing a request and + generating the response. This stage follows the "Parse and Prepare + Request" stage and precedes the "Finishing" stage. There is always at + least one thread in this stage (the server-status page).

      • +
      • "Finishing" : The end of the request processing. Any + remainder of the response still in the output buffers is sent to the + client. This stage is followed by "Keep-Alive" if it is appropriate to + keep the connection alive or "Ready" if "Keep-Alive" is not + appropriate.

      • +
      • "Keep-Alive" : The thread keeps the connection open to + the client in case the client sends another request. If another request + is received, the next stage will be "Parse and Prepare Request". If no + request is received before the keep alive times out, the connection will + be closed and the next stage will be "Ready".

      • +
      • "Ready" : The thread is at rest and ready to be + used.

      • +
      +
    • +
    + +

    If you are using /status/all command, additional information +on each of deployed web applications will be available.

    + +

    Using the JMX Proxy Servlet

    + +

    What is JMX Proxy Servlet

    + The JMX Proxy Servlet is a lightweight proxy to get and set the + tomcat internals. (Or any class that has been exposed via an MBean) + Its usage is not very user friendly but the UI is + extremely helpful for integrating command line scripts for monitoring + and changing the internals of tomcat. You can do two things with the proxy: + get information and set information. For you to really understand the + JMX Proxy Servlet, you should have a general understanding of JMX. + If you don't know what JMX is, then prepare to be confused. +
    + +

    JMX Query command

    +

    This takes the form:

    +
    http://webserver/manager/jmxproxy/?qry=STUFF
    +

    Where STUFF is the JMX query you wish to perform. For example, + here are some queries you might wish to run:

    +
      +
    • + qry=*%3Atype%3DRequestProcessor%2C* --> + type=RequestProcessor which will locate all + workers which can process requests and report + their state. +
    • +
    • + qry=*%3Aj2eeType=Servlet%2c* --> + j2eeType=Servlet which return all loaded servlets. +
    • +
    • + qry=Catalina%3Atype%3DEnvironment%2Cresourcetype%3DGlobal%2Cname%3DsimpleValue --> + Catalina:type=Environment,resourcetype=Global,name=simpleValue + which look for a specific MBean by the given name. +
    • +
    +

    + You'll need to experiment with this to really understand its capabilities + If you provide no qry parameter, then all of the MBeans will + be displayed. We really recommend looking at the tomcat source code and + understand the JMX spec to get a better understanding of all the queries + you may run. +

    +
    + +

    JMX Get command

    +

    + The JXMProxyServlet also supports a "get" command that you can use to + fetch the value of a specific MBean's attribute. The general form of + the get command is: +

    + +
    http://webserver/manager/jmxproxy/?get=BEANNAME&att=MYATTRIBUTE&key=MYKEY
    + +

    You must provide the following parameters:

    +
      +
    1. get: The full bean name
    2. +
    3. att: The attribute you wish to fetch
    4. +
    5. key: (optional) The key into a CompositeData MBean attribute
    6. +
    +

    + If all goes well, then it will say OK, otherwise an error message will + be shown. For example, let's say we wish to fetch the current heap memory + data: +

    + +
    http://webserver/manager/jmxproxy/?get=java.lang:type=Memory&att=HeapMemoryUsage
    + +

    Or, if you only want the "used" key:

    + +
    http://webserver/manager/jmxproxy/
    + ?get=java.lang:type=Memory&att=HeapMemoryUsage&key=used
    +
    + +

    JMX Set command

    +

    + Now that you can query an MBean, its time to muck with Tomcat's internals! + The general form of the set command is : +

    +
    http://webserver/manager/jmxproxy/?set=BEANNAME&att=MYATTRIBUTE&val=NEWVALUE
    +

    So you need to provide 3 request parameters:

    +
      +
    1. set: The full bean name
    2. +
    3. att: The attribute you wish to alter
    4. +
    5. val: The new value
    6. +
    +

    + If all goes ok, then it will say OK, otherwise an error message will be + shown. For example, lets say we wish to turn up debugging on the fly for the + ErrorReportValve. The following will set debugging to 10. +

    +
    http://localhost:8080/manager/jmxproxy/
    + ?set=Catalina%3Atype%3DValve%2Cname%3DErrorReportValve%2Chost%3Dlocalhost
    + &att=debug&val=10
    +

    and my result is (YMMV):

    +
    Result: ok
    + +

    Here is what I see if I pass in a bad value. Here is the URL I used, + I try set debugging equal to 'cow':

    +
    http://localhost:8080/manager/jmxproxy/
    + ?set=Catalina%3Atype%3DValve%2Cname%3DErrorReportValve%2Chost%3Dlocalhost
    + &att=debug&val=cow
    +

    When I try that, my result is

    +
    Error: java.lang.NumberFormatException: For input string: "cow"
    +
    + +

    JMX Invoke command

    +

    The invoke command enables methods to be called on MBeans. The + general form of the command is:

    +
    http://webserver/manager/jmxproxy/
    + ?invoke=BEANNAME&op=METHODNAME&ps=COMMASEPARATEDPARAMETERS
    +

    For example, to call the findConnectors() method of the + Service use:

    +
    http://localhost:8080/manager/jmxproxy/
    + ?invoke=Catalina%3Atype%3DService&op=findConnectors&ps=
    +
    +

    Executing Manager Commands With Ant

    + +

    In addition to the ability to execute Manager commands via HTTP requests, +as documented above, Tomcat includes a convenient set of Task definitions +for the Ant (version 1.4 or later) build tool. In order to use these +commands, you must perform the following setup operations:

    +
      +
    • Download the binary distribution of Ant from + https://ant.apache.org. + You must use version 1.4 or later.
    • +
    • Install the Ant distribution in a convenient directory (called + ANT_HOME in the remainder of these instructions).
    • +
    • Add the $ANT_HOME/bin directory to your PATH + environment variable.
    • +
    • Configure at least one username/password combination in your Tomcat + user database that includes the manager-script role.
    • +
    + +

    To use custom tasks within Ant, you must declare them first with an +<import> element. Therefore, your build.xml +file might look something like this:

    + +
    <project name="My Application" default="compile" basedir=".">
    +
    +  <!-- Configure the directory into which the web application is built -->
    +  <property name="build"    value="${basedir}/build"/>
    +
    +  <!-- Configure the context path for this application -->
    +  <property name="path"     value="/myapp"/>
    +
    +  <!-- Configure properties to access the Manager application -->
    +  <property name="url"      value="http://localhost:8080/manager/text"/>
    +  <property name="username" value="myusername"/>
    +  <property name="password" value="mypassword"/>
    +
    +  <!-- Configure the path to the Tomcat installation -->
    +  <property name="catalina.home" value="/usr/local/apache-tomcat"/>
    +
    +  <!-- Configure the custom Ant tasks for the Manager application -->
    +  <import file="${catalina.home}/bin/catalina-tasks.xml"/>
    +
    +  <!-- Executable Targets -->
    +  <target name="compile" description="Compile web application">
    +    <!-- ... construct web application in ${build} subdirectory, and
    +            generated a ${path}.war ... -->
    +  </target>
    +
    +  <target name="deploy" description="Install web application"
    +          depends="compile">
    +    <deploy url="${url}" username="${username}" password="${password}"
    +            path="${path}" war="file:${build}${path}.war"/>
    +  </target>
    +
    +  <target name="reload" description="Reload web application"
    +          depends="compile">
    +    <reload  url="${url}" username="${username}" password="${password}"
    +            path="${path}"/>
    +  </target>
    +
    +  <target name="undeploy" description="Remove web application">
    +    <undeploy url="${url}" username="${username}" password="${password}"
    +            path="${path}"/>
    +  </target>
    +
    +</project>
    + +

    Note: The definition of the resources task via the import above will override +the resources datatype added in Ant 1.7. If you wish to use the resources +datatype you will need to use Ant's namespace support to modify +catalina-tasks.xml to assign the Tomcat tasks to their own +namespace.

    + +

    Now, you can execute commands like ant deploy to deploy the +application to a running instance of Tomcat, or ant reload to +tell Tomcat to reload it. Note also that most of the interesting values in +this build.xml file are defined as replaceable properties, so +you can override their values from the command line. For example, you might +consider it a security risk to include the real manager password in your +build.xml file's source code. To avoid this, omit the password +property, and specify it from the command line:

    +
    ant -Dpassword=secret deploy
    + +

    Tasks output capture

    + +

    Using Ant version 1.6.2 or later, +the Catalina tasks offer the option to capture their output in +properties or external files. They support directly the following subset of the +<redirector> type attributes: +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    AttributeDescriptionRequired
    outputName of a file to which to write the output. If +the error stream is not also redirected to a file or property, it will +appear in this output.No
    errorThe file to which the standard error of the +command should be redirected.No
    logErrorThis attribute is used when you wish to see +error output in Ant's log and you are redirecting output to a +file/property. The error output will not be included in the output +file/property. If you redirect error with the error or errorProperty +attributes, this will have no effect.No
    appendWhether output and error files should be +appended to or overwritten. Defaults to false.No
    createemptyfilesWhether output and error files should be created +even when empty. Defaults to true.No
    outputpropertyThe name of a property in which the output of +the command should be stored. Unless the error stream is redirected to +a separate file or stream, this property will include the error output.No
    errorpropertyThe name of a property in which the standard +error of the command should be stored.No
    + +

    A couple of additional attributes can also be specified: +

    + + + + + + + + + + + + + + + + +
    AttributeDescriptionRequired
    alwaysLogThis attribute is used when you wish to see the +output you are capturing, appearing also in the Ant's log. It must not be +used unless you are capturing task output. +Defaults to false. +This attribute will be supported directly by <redirector> +in Ant 1.6.3No
    failonerrorThis attribute is used when you wish to avoid that +any manager command processing error terminates the ant execution. Defaults to true. +It must be set to false, if you want to capture error output, +otherwise execution will terminate before anything can be captured. +
    +This attribute acts only on manager command execution, +any wrong or missing command attribute will still cause Ant execution termination. +
    No
    + +

    They also support the embedded <redirector> element +in which you can specify +its full set of attributes, but input, inputstring and +inputencoding that, even if accepted, are not used because they have +no meaning in this context. +Refer to ant manual for details on +<redirector> element attributes. +

    + +

    +Here is a sample build file extract that shows how this output redirection support +can be used: +

    + +
        <target name="manager.deploy"
    +        depends="context.status"
    +        if="context.notInstalled">
    +        <deploy url="${mgr.url}"
    +            username="${mgr.username}"
    +            password="${mgr.password}"
    +            path="${mgr.context.path}"
    +            config="${mgr.context.descriptor}"/>
    +    </target>
    +
    +    <target name="manager.deploy.war"
    +        depends="context.status"
    +        if="context.deployable">
    +        <deploy url="${mgr.url}"
    +            username="${mgr.username}"
    +            password="${mgr.password}"
    +            update="${mgr.update}"
    +            path="${mgr.context.path}"
    +            war="${mgr.war.file}"/>
    +    </target>
    +
    +    <target name="context.status">
    +        <property name="running" value="${mgr.context.path}:running"/>
    +        <property name="stopped" value="${mgr.context.path}:stopped"/>
    +
    +        <list url="${mgr.url}"
    +            outputproperty="ctx.status"
    +            username="${mgr.username}"
    +            password="${mgr.password}">
    +        </list>
    +
    +        <condition property="context.running">
    +            <contains string="${ctx.status}" substring="${running}"/>
    +        </condition>
    +        <condition property="context.stopped">
    +            <contains string="${ctx.status}" substring="${stopped}"/>
    +        </condition>
    +        <condition property="context.notInstalled">
    +            <and>
    +                <isfalse value="${context.running}"/>
    +                <isfalse value="${context.stopped}"/>
    +            </and>
    +        </condition>
    +        <condition property="context.deployable">
    +            <or>
    +                <istrue value="${context.notInstalled}"/>
    +                <and>
    +                    <istrue value="${context.running}"/>
    +                    <istrue value="${mgr.update}"/>
    +                </and>
    +                <and>
    +                    <istrue value="${context.stopped}"/>
    +                    <istrue value="${mgr.update}"/>
    +                </and>
    +            </or>
    +        </condition>
    +        <condition property="context.undeployable">
    +            <or>
    +                <istrue value="${context.running}"/>
    +                <istrue value="${context.stopped}"/>
    +            </or>
    +        </condition>
    +    </target>
    + +

    WARNING: even if it doesn't make many sense, and is always a bad idea, +calling a Catalina task more than once, +badly set Ant tasks depends chains may cause that a task be called +more than once in the same Ant run, even if not intended to. A bit of caution should be exercised when you are +capturing output from that task, because this could lead to something unexpected:

    +
      +
    • when capturing in a property you will find in it only the output from the first call, because +Ant properties are immutable and once set they cannot be changed, +
    • +
    • when capturing in a file, each run will overwrite it and you will find in it only the last call +output, unless you are using the append="true" attribute, in which case you will +see the output of each task call appended to the file. +
    • +
    + +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/maven-jars.html b/tomcat/docs/maven-jars.html new file mode 100644 index 0000000..2ce5eb7 --- /dev/null +++ b/tomcat/docs/maven-jars.html @@ -0,0 +1,69 @@ + +Apache Tomcat 8 (8.5.43) - Apache Tomcat - Using Tomcat libraries with Maven

    Apache Tomcat - Using Tomcat libraries with Maven

    Table of Contents

    Using Tomcat libraries With Maven

    +

    Tomcat Snapshots

    + Tomcat snapshots are located in the + Apache Snapshot Repository. + The official URL is
    https://repository.apache.org/content/repositories/snapshots/org/apache/tomcat/
    +

    + Snapshots are done periodically, not on a regular basis, but when changes happen and the Tomcat team deems a new snapshot might + useful. +

    +
    +

    Tomcat Releases

    +

    + Stable releases are published to the + Central + Maven Repositories. The URL for this is +

    +
    https://repo2.maven.org/maven2/org/apache/tomcat/
    +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/mbeans-descriptors-howto.html b/tomcat/docs/mbeans-descriptors-howto.html new file mode 100644 index 0000000..f83a486 --- /dev/null +++ b/tomcat/docs/mbeans-descriptors-howto.html @@ -0,0 +1,94 @@ + +Apache Tomcat 8 (8.5.43) - MBeans Descriptors How To

    MBeans Descriptors How To

    Table of Contents

    Introduction

    + +

    Tomcat uses JMX MBeans as the technology for implementing +manageability of Tomcat.

    + +

    The descriptions of JMX MBeans for Catalina are in the mbeans-descriptors.xml +file in each package.

    + +

    You will need to add MBean descriptions for your custom components +in order to avoid a "ManagedBean is not found" exception.

    + +

    Adding MBean descriptions

    + +

    You may also add MBean descriptions for custom components in +a mbeans-descriptors.xml file, located in the same package as the class files +it describes.

    + +

    The permitted syntax for the mbeans-descriptors.xml is defined by +the DTD file.

    + +

    The entries for a custom LDAP authentication Realm may look like this:

    + +
      <mbean         name="LDAPRealm"
    +            className="org.apache.catalina.mbeans.ClassNameMBean"
    +          description="Custom LDAPRealm"
    +               domain="Catalina"
    +                group="Realm"
    +                 type="com.myfirm.mypackage.LDAPRealm">
    +
    +    <attribute   name="className"
    +          description="Fully qualified class name of the managed object"
    +                 type="java.lang.String"
    +            writeable="false"/>
    +
    +    <attribute   name="debug"
    +          description="The debugging detail level for this component"
    +                 type="int"/>
    +    .
    +    .
    +    .
    +
    +  </mbean>
    + + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/mbeans-descriptors.dtd b/tomcat/docs/mbeans-descriptors.dtd new file mode 100644 index 0000000..f12b8fe --- /dev/null +++ b/tomcat/docs/mbeans-descriptors.dtd @@ -0,0 +1,247 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tomcat/docs/monitoring.html b/tomcat/docs/monitoring.html new file mode 100644 index 0000000..b73be6a --- /dev/null +++ b/tomcat/docs/monitoring.html @@ -0,0 +1,1136 @@ + +Apache Tomcat 8 (8.5.43) - Monitoring and Managing Tomcat

    Monitoring and Managing Tomcat

    Table of Contents

    Introduction

    + +

    Monitoring is a key aspect of system administration. Looking inside a + running server, obtaining some statistics or reconfiguring some aspects of + an application are all daily administration tasks.

    + +

    Enabling JMX Remote

    + +

    Note: This configuration is needed only if you are + going to monitor Tomcat remotely. It is not needed if you are going + to monitor it locally, using the same user that Tomcat runs with.

    + +

    The Oracle website includes the list of options and how to configure + JMX Remote on Java 6: + + http://docs.oracle.com/javase/6/docs/technotes/guides/management/agent.html. +

    +

    The following is a quick configuration guide for Java 6:

    +

    Add the following parameters to setenv.bat script of your + Tomcat (see RUNNING.txt for details).
    + Note: This syntax is for Microsoft Windows. The command has + to be on the same line. It is wrapped to be more readable. If Tomcat is + running as a Windows service, use its configuration dialog to set + java options for the service. + For un*xes remove "set " from beginning of the line. +

    +
    set CATALINA_OPTS=-Dcom.sun.management.jmxremote
    +  -Dcom.sun.management.jmxremote.port=%my.jmx.port%
    +  -Dcom.sun.management.jmxremote.ssl=false
    +  -Dcom.sun.management.jmxremote.authenticate=false
    + +
      +
    1. If you require authorization, add and change this: +
        -Dcom.sun.management.jmxremote.authenticate=true
      +  -Dcom.sun.management.jmxremote.password.file=../conf/jmxremote.password
      +  -Dcom.sun.management.jmxremote.access.file=../conf/jmxremote.access
      +
    2. +
    3. edit the access authorization file $CATALINA_BASE/conf/jmxremote.access: +
      monitorRole readonly
      +controlRole readwrite
      +
    4. +
    5. edit the password file $CATALINA_BASE/conf/jmxremote.password: +
      monitorRole tomcat
      +controlRole tomcat
      + Tip: The password file should be read-only and only accessible by the + operating system user Tomcat is running as. +
    6. +
    +

    Note: The JSR 160 JMX-Adaptor opens a second data channel + on a random port. That is a problem when you have a local firewall installed. + To fix it, configure a JmxRemoteLifecycleListener, as described + in listeners documentation. +

    + +

    Manage Tomcat with JMX remote Ant Tasks

    +

    To simplify JMX usage with Ant 1.6.x, a set of tasks is provided that may + be used with antlib.

    +

    antlib: Copy your catalina-ant.jar from $CATALINA_HOME/lib to $ANT_HOME/lib.

    +

    The following example shows the JMX Accessor usage:
    + Note: The name attribute value was wrapped here to be + more readable. It has to be all on the same line, without spaces.

    +
    <project name="Catalina Ant JMX"
    +      xmlns:jmx="antlib:org.apache.catalina.ant.jmx"
    +      default="state"
    +      basedir=".">
    +  <property name="jmx.server.name" value="localhost" />
    +  <property name="jmx.server.port" value="9012" />
    +  <property name="cluster.server.address" value="192.168.1.75" />
    +  <property name="cluster.server.port" value="9025" />
    +
    +  <target name="state" description="Show JMX Cluster state">
    +    <jmx:open
    +      host="${jmx.server.name}"
    +      port="${jmx.server.port}"
    +      username="controlRole"
    +      password="tomcat"/>
    +    <jmx:get
    +      name=
    +"Catalina:type=IDataSender,host=localhost,
    +senderAddress=${cluster.server.address},senderPort=${cluster.server.port}"
    +      attribute="connected"
    +      resultproperty="IDataSender.backup.connected"
    +      echo="false"
    +    />
    +    <jmx:get
    +      name="Catalina:type=ClusterSender,host=localhost"
    +      attribute="senderObjectNames"
    +      resultproperty="senderObjectNames"
    +      echo="false"
    +    />
    +    <!-- get current maxActiveSession from ClusterTest application
    +       echo it to Ant output and store at
    +       property <em>clustertest.maxActiveSessions.orginal</em>
    +    -->
    +    <jmx:get
    +      name="Catalina:type=Manager,context=/ClusterTest,host=localhost"
    +      attribute="maxActiveSessions"
    +      resultproperty="clustertest.maxActiveSessions.orginal"
    +      echo="true"
    +    />
    +    <!-- set maxActiveSession to 100
    +    -->
    +    <jmx:set
    +      name="Catalina:type=Manager,context=/ClusterTest,host=localhost"
    +      attribute="maxActiveSessions"
    +      value="100"
    +      type="int"
    +    />
    +    <!-- get all sessions and split result as delimiter <em>SPACE</em> for easy
    +       access all session ids directly with Ant property sessions.[0..n].
    +    -->
    +    <jmx:invoke
    +      name="Catalina:type=Manager,context=/ClusterTest,host=localhost"
    +      operation="listSessionIds"
    +      resultproperty="sessions"
    +      echo="false"
    +      delimiter=" "
    +    />
    +    <!-- Access session attribute <em>Hello</em> from first session.
    +    -->
    +    <jmx:invoke
    +      name="Catalina:type=Manager,context=/ClusterTest,host=localhost"
    +      operation="getSessionAttribute"
    +      resultproperty="Hello"
    +      echo="false"
    +    >
    +      <arg value="${sessions.0}"/>
    +      <arg value="Hello"/>
    +    </jmx:invoke>
    +    <!-- Query for all application manager.of the server from all hosts
    +       and bind all attributes from all found manager MBeans.
    +    -->
    +    <jmx:query
    +      name="Catalina:type=Manager,*"
    +      resultproperty="manager"
    +      echo="true"
    +      attributebinding="true"
    +    />
    +    <!-- echo the create properties -->
    +<echo>
    +senderObjectNames: ${senderObjectNames.0}
    +IDataSender.backup.connected: ${IDataSender.backup.connected}
    +session: ${sessions.0}
    +manager.length: ${manager.length}
    +manager.0.name: ${manager.0.name}
    +manager.1.name: ${manager.1.name}
    +hello: ${Hello}
    +manager.ClusterTest.0.name: ${manager.ClusterTest.0.name}
    +manager.ClusterTest.0.activeSessions: ${manager.ClusterTest.0.activeSessions}
    +manager.ClusterTest.0.counterSend_EVT_SESSION_EXPIRED:
    + ${manager.ClusterTest.0.counterSend_EVT_SESSION_EXPIRED}
    +manager.ClusterTest.0.counterSend_EVT_GET_ALL_SESSIONS:
    + ${manager.ClusterTest.0.counterSend_EVT_GET_ALL_SESSIONS}
    +</echo>
    +
    +  </target>
    +
    +</project>
    +

    import: Import the JMX Accessor Project with + <import file="${CATALINA.HOME}/bin/catalina-tasks.xml" /> and + reference the tasks with jmxOpen, jmxSet, jmxGet, + jmxQuery, jmxInvoke, jmxEquals and jmxCondition.

    + +

    JMXAccessorOpenTask - JMX open connection task

    +

    +List of Attributes +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    AttributeDescriptionDefault value
    urlSet JMX connection URL - service:jmx:rmi:///jndi/rmi://localhost:8050/jmxrmi +
    hostSet the host, shortcut the very long URL syntax. + localhost
    portSet the remote connection port + 8050
    usernameremote JMX connection user name. +
    passwordremote JMX connection password. +
    refName of the internal connection reference. With this attribute you can + configure more the one connection inside the same Ant project. + jmx.server
    echoEcho the command usage (for access analysis or debugging) + false
    ifOnly execute if a property of the given name exists in the current project. +
    unlessOnly execute if a property of the given name not exists in the current project. +
    + +

    +Example to open a new JMX connection +

    +
      <jmx:open
    +    host="${jmx.server.name}"
    +    port="${jmx.server.port}"
    +  />
    + +

    +Example to open a JMX connection from URL, with authorization and +store at other reference +

    +
      <jmx:open
    +    url="service:jmx:rmi:///jndi/rmi://localhost:9024/jmxrmi"
    +    ref="jmx.server.9024"
    +    username="controlRole"
    +    password="tomcat"
    +  />
    + +

    +Example to open a JMX connection from URL, with authorization and +store at other reference, but only when property jmx.if exists and +jmx.unless not exists +

    +
      <jmx:open
    +    url="service:jmx:rmi:///jndi/rmi://localhost:9024/jmxrmi"
    +    ref="jmx.server.9024"
    +    username="controlRole"
    +    password="tomcat"
    +    if="jmx.if"
    +    unless="jmx.unless"
    +  />
    + +

    Note: All properties from jmxOpen task also exists at all +other tasks and conditions. +

    + +

    JMXAccessorGetTask: get attribute value Ant task

    +

    +List of Attributes +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    AttributeDescriptionDefault value
    nameFull qualified JMX ObjectName -- Catalina:type=Server +
    attributeExisting MBean attribute (see Tomcat MBean description above) +
    refJMX Connection reference + jmx.server
    echoEcho command usage (access and result) + false
    resultpropertySave result at this project property +
    delimiterSplit result with delimiter (java.util.StringTokenizer) + and use resultproperty as prefix to store tokens. +
    separatearrayresultsWhen return value is an array, save result as property list + ($resultproperty.[0..N] and $resultproperty.length) + true
    + +

    +Example to get remote MBean attribute from default JMX connection +

    +
      <jmx:get
    +    name="Catalina:type=Manager,context=/servlets-examples,host=localhost"
    +    attribute="maxActiveSessions"
    +    resultproperty="servlets-examples.maxActiveSessions"
    +  />
    + +

    +Example to get and result array and split it at separate properties +

    +
      <jmx:get
    +      name="Catalina:type=ClusterSender,host=localhost"
    +      attribute="senderObjectNames"
    +      resultproperty="senderObjectNames"
    +  />
    +

    +Access the senderObjectNames properties with: +

    +
      ${senderObjectNames.length} give the number of returned sender list.
    +  ${senderObjectNames.[0..N]} found all sender object names
    + + +

    +Example to get IDataSender attribute connected only when cluster is configured.
    +Note: The name attribute value was wrapped here to be +more readable. It has to be all on the same line, without spaces. +

    +
    
    +  <jmx:query
    +    failonerror="false"
    +    name="Catalina:type=Cluster,host=${tomcat.application.host}"
    +    resultproperty="cluster"
    +  />
    +  <jmx:get
    +    name=
    +"Catalina:type=IDataSender,host=${tomcat.application.host},
    +senderAddress=${cluster.backup.address},senderPort=${cluster.backup.port}"
    +    attribute="connected"
    +    resultproperty="datasender.connected"
    +    if="cluster.0.name" />
    + +

    JMXAccessorSetTask: set attribute value Ant task

    +

    +List of Attributes +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    AttributeDescriptionDefault value
    nameFull qualified JMX ObjectName -- Catalina:type=Server +
    attributeExisting MBean attribute (see Tomcat MBean description above) +
    valuevalue that set to attribute +
    typetype of the attribute. + java.lang.String
    refJMX Connection reference + jmx.server
    echoEcho command usage (access and result) + false
    + +

    +Example to set remote MBean attribute value +

    +
      <jmx:set
    +    name="Catalina:type=Manager,context=/servlets-examples,host=localhost"
    +    attribute="maxActiveSessions"
    +    value="500"
    +    type="int"
    +  />
    + + +

    JMXAccessorInvokeTask: invoke MBean operation Ant task

    +

    +List of Attributes +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    AttributeDescriptionDefault value
    nameFull qualified JMX ObjectName -- Catalina:type=Server +
    operationExisting MBean operation (see Tomcat + funcspecs/fs-admin-opers.html). +
    refJMX Connection reference + jmx.server
    echoEcho command usage (access and result) + false
    resultpropertySave result at this project property +
    delimiterSplit result with delimiter (java.util.StringTokenizer) + and use resultproperty as prefix to store tokens. +
    separatearrayresultsWhen return value is an array, save result as property list + ($resultproperty.[0..N] and $resultproperty.length) + true
    + +

    +stop an application +

    +
      <jmx:invoke
    +    name="Catalina:type=Manager,context=/servlets-examples,host=localhost"
    +    operation="stop"/>
    +

    +Now you can find the sessionid at ${sessions.[0..N} properties and access the count +with ${sessions.length} property. +

    +

    +Example to get all sessionids +

    +
      <jmx:invoke
    +    name="Catalina:type=Manager,context=/servlets-examples,host=localhost"
    +    operation="listSessionIds"
    +    resultproperty="sessions"
    +    delimiter=" "
    +  />
    +

    +Now you can find the sessionid at ${sessions.[0..N} properties and access the count +with ${sessions.length} property. +

    +

    +Example to get remote MBean session attribute from session ${sessionid.0} +

    +
      <jmx:invoke
    +    name="Catalina:type=Manager,context=/ClusterTest,host=localhost"
    +    operation="getSessionAttribute"
    +    resultproperty="hello">
    +     <arg value="${sessionid.0}"/>
    +     <arg value="Hello" />
    +  </jmx:invoke>
    + +

    +Example to create a new access logger valve at vhost localhost +

    +
     <jmx:invoke
    +         name="Catalina:type=MBeanFactory"
    +         operation="createAccessLoggerValve"
    +         resultproperty="accessLoggerObjectName"
    + >
    +     <arg value="Catalina:type=Host,host=localhost"/>
    + </jmx:invoke>
    +

    +Now you can find new MBean with name stored at ${accessLoggerObjectName} +property. +

    + +

    JMXAccessorQueryTask: query MBean Ant task

    +

    +List of Attributes +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    AttributeDescriptionDefault value
    nameJMX ObjectName query string -- Catalina:type=Manager,* +
    refJMX Connection reference + jmx.server
    echoEcho command usage (access and result) + false
    resultpropertyPrefix project property name to all founded MBeans (mbeans.[0..N].objectname) +
    attributebindingbind ALL MBean attributes in addition to name + false
    delimiterSplit result with delimiter (java.util.StringTokenizer) + and use resultproperty as prefix to store tokens. +
    separatearrayresultsWhen return value is an array, save result as property list + ($resultproperty.[0..N] and $resultproperty.length) + true
    + +

    +Get all Manager ObjectNames from all services and Hosts +

    +
      <jmx:query
    +    name="Catalina:type=Manager,*
    +    resultproperty="manager" />
    +

    +Now you can find the Session Manager at ${manager.[0..N].name} +properties and access the result object counter with ${manager.length} property. +

    +

    +Example to get the Manager from servlet-examples application an bind all MBean properties +

    +
      <jmx:query
    +    name="Catalina:type=Manager,context=/servlet-examples,host=localhost*"
    +    attributebinding="true"
    +    resultproperty="manager.servletExamples" />
    +

    +Now you can find the manager at ${manager.servletExamples.0.name} property +and can access all properties from this manager with ${manager.servletExamples.0.[manager attribute names]}. +The result object counter from MBeans is stored ad ${manager.length} property. +

    + +

    +Example to get all MBeans from a server and store inside an external XML property file +

    +
    <project name="jmx.query"
    +            xmlns:jmx="antlib:org.apache.catalina.ant.jmx"
    +            default="query-all" basedir=".">
    +<property name="jmx.host" value="localhost"/>
    +<property name="jmx.port" value="8050"/>
    +<property name="jmx.username" value="controlRole"/>
    +<property name="jmx.password" value="tomcat"/>
    +
    +<target name="query-all" description="Query all MBeans of a server">
    +  <!-- Configure connection -->
    +  <jmx:open
    +    host="${jmx.host}"
    +    port="${jmx.port}"
    +    ref="jmx.server"
    +    username="${jmx.username}"
    +    password="${jmx.password}"/>
    +
    +  <!-- Query MBean list -->
    +  <jmx:query
    +    name="*:*"
    +    resultproperty="mbeans"
    +    attributebinding="false"/>
    +
    +  <echoproperties
    +    destfile="mbeans.properties"
    +    prefix="mbeans."
    +    format="xml"/>
    +
    +  <!-- Print results -->
    +  <echo message=
    +    "Number of MBeans in server ${jmx.host}:${jmx.port} is ${mbeans.length}"/>
    +</target>
    +</project>
    +

    +Now you can find all MBeans inside the file mbeans.properties. +

    + +

    JMXAccessorCreateTask: remote create MBean Ant task

    +

    +List of Attributes +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    AttributeDescriptionDefault value
    nameFull qualified JMX ObjectName -- Catalina:type=MBeanFactory +
    classNameExisting MBean full qualified class name (see Tomcat MBean description above) +
    classLoaderObjectName of server or web application classloader
    + ( Catalina:type=ServerClassLoader,name=[server,common,shared] or
    + Catalina:type=WebappClassLoader,context=/myapps,host=localhost) +
    refJMX Connection reference + jmx.server
    echoEcho command usage (access and result) + false
    + +

    +Example to create remote MBean +

    +
      <jmx:create
    +    ref="${jmx.reference}"
    +    name="Catalina:type=MBeanFactory"
    +    className="org.apache.commons.modeler.BaseModelMBean"
    +    classLoader="Catalina:type=ServerClassLoader,name=server">
    +    <arg value="org.apache.catalina.mbeans.MBeanFactory" />
    +  </jmx:create>
    + +

    + Warning: Many Tomcat MBeans can't be linked to their parent once
    + created. The Valve, Cluster and Realm MBeans are not automatically
    + connected with their parent. Use the MBeanFactory create
    + operation instead. +

    + +

    JMXAccessorUnregisterTask: remote unregister MBean Ant task

    +

    +List of Attributes +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    AttributeDescriptionDefault value
    nameFull qualified JMX ObjectName -- Catalina:type=MBeanFactory +
    refJMX Connection reference + jmx.server
    echoEcho command usage (access and result) + false
    + +

    +Example to unregister remote MBean +

    +
      <jmx:unregister
    +    name="Catalina:type=MBeanFactory"
    +  />
    + +

    + Warning: A lot of Tomcat MBeans can't be unregister.
    + The MBeans are not unlinked from their parent. Use MBeanFactory
    + remove operation instead. +

    + +

    JMXAccessorCondition: express condition

    +

    +List of Attributes +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    AttributeDescriptionDefault value
    urlSet JMX connection URL - service:jmx:rmi:///jndi/rmi://localhost:8050/jmxrmi +
    hostSet the host, shortcut the very long URL syntax. + localhost
    portSet the remote connection port + 8050
    usernameremote JMX connection user name. +
    passwordremote JMX connection password. +
    refName of the internal connection reference. With this attribute you can + configure more the one connection inside the same Ant project. + jmx.server
    nameFull qualified JMX ObjectName -- Catalina:type=Server +
    echoEcho condition usage (access and result) + false
    ifOnly execute if a property of the given name exists in the current project. +
    unlessOnly execute if a property of the given name not exists in the current project. +
    value (required)Second arg for operation +
    typeValue type to express operation (support long and double) + long
    operation express one +
      +
    • == equals
    • +
    • != not equals
    • +
    • > greater than (&gt;)
    • +
    • >= greater than or equals (&gt;=)
    • +
    • < lesser than (&lt;)
    • +
    • <= lesser than or equals (&lt;=)
    • +
    +
    ==
    + +

    +Wait for server connection and that cluster backup node is accessible +

    +
    <target name="wait">
    +  <waitfor maxwait="${maxwait}" maxwaitunit="second" timeoutproperty="server.timeout" >
    +    <and>
    +      <socket server="${server.name}" port="${server.port}"/>
    +      <http url="${url}"/>
    +      <jmx:condition
    +        operation="=="
    +        host="localhost"
    +        port="9014"
    +        username="controlRole"
    +        password="tomcat"
    +        name=
    +"Catalina:type=IDataSender,host=localhost,senderAddress=192.168.111.1,senderPort=9025"
    +        attribute="connected"
    +        value="true"
    +      />
    +    </and>
    +  </waitfor>
    +  <fail if="server.timeout" message="Server ${url} don't answer inside ${maxwait} sec" />
    +  <echo message="Server ${url} alive" />
    +</target>
    + +

    JMXAccessorEqualsCondition: equals MBean Ant condition

    +

    +List of Attributes +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    AttributeDescriptionDefault value
    urlSet JMX connection URL - service:jmx:rmi:///jndi/rmi://localhost:8050/jmxrmi +
    hostSet the host, shortcut the very long URL syntax. + localhost
    portSet the remote connection port + 8050
    usernameremote JMX connection user name. +
    passwordremote JMX connection password. +
    refName of the internal connection reference. With this attribute you can + configure more the one connection inside the same Ant project. + jmx.server
    nameFull qualified JMX ObjectName -- Catalina:type=Server +
    echoEcho condition usage (access and result) + false
    + +

    +Wait for server connection and that cluster backup node is accessible +

    +
    <target name="wait">
    +  <waitfor maxwait="${maxwait}" maxwaitunit="second" timeoutproperty="server.timeout" >
    +    <and>
    +      <socket server="${server.name}" port="${server.port}"/>
    +      <http url="${url}"/>
    +      <jmx:equals
    +        host="localhost"
    +        port="9014"
    +        username="controlRole"
    +        password="tomcat"
    +        name=
    +"Catalina:type=IDataSender,host=localhost,senderAddress=192.168.111.1,senderPort=9025"
    +        attribute="connected"
    +        value="true"
    +      />
    +    </and>
    +  </waitfor>
    +  <fail if="server.timeout" message="Server ${url} don't answer inside ${maxwait} sec" />
    +  <echo message="Server ${url} alive" />
    +</target>
    + +

    Using the JMXProxyServlet

    + +

    + Tomcat offers an alternative to using remote (or even local) JMX + connections while still giving you access to everything JMX has to offer: + Tomcat's + JMXProxyServlet. +

    + +

    + The JMXProxyServlet allows a client to issue JMX queries via an HTTP + interface. This technique offers the following advantages over using + JMX directly from a client program: +

    + +
      +
    • You don't have to launch a full JVM and make a remote JMX connection + just to ask for one small piece of data from a running server
    • +
    • You don't have to know how to work with JMX connections
    • +
    • You don't need any of the complex configuration covered in the rest + of this page
    • +
    • Your client program does not have to be written in Java
    • +
    + +

    + A perfect example of JMX overkill can be seen in the case of popular + server-monitoring software such as Nagios or Icinga: if you want to + monitor 10 items via JMX, you will have to launch 10 JVMs, make 10 JMX + connections, and then shut them all down every few minutes. With the + JMXProxyServlet, you can make 10 HTTP connections and be done with it. +

    + +

    + You can find out more information about the JMXProxyServlet in the + documentation for the + Tomcat + manager. +

    +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/proxy-howto.html b/tomcat/docs/proxy-howto.html new file mode 100644 index 0000000..82f7f7b --- /dev/null +++ b/tomcat/docs/proxy-howto.html @@ -0,0 +1,153 @@ + +Apache Tomcat 8 (8.5.43) - Proxy Support How-To

    Proxy Support How-To

    Table of Contents

    Introduction

    + +

    Using standard configurations of Tomcat, web applications can ask for +the server name and port number to which the request was directed for +processing. When Tomcat is running standalone with the +HTTP/1.1 Connector, it will generally +report the server name specified in the request, and the port number on +which the Connector is listening. The servlet API +calls of interest, for this purpose, are:

    +
      +
    • ServletRequest.getServerName(): Returns the host name of the server to which the request was sent.
    • +
    • ServletRequest.getServerPort(): Returns the port number of the server to which the request was sent.
    • +
    • ServletRequest.getLocalName(): Returns the host name of the Internet Protocol (IP) interface on which the request was received.
    • +
    • ServletRequest.getLocalPort(): Returns the Internet Protocol (IP) port number of the interface on which the request was received.
    • +
    + +

    When you are running behind a proxy server (or a web server that is +configured to behave like a proxy server), you will sometimes prefer to +manage the values returned by these calls. In particular, you will +generally want the port number to reflect that specified in the original +request, not the one on which the Connector itself is +listening. You can use the proxyName and proxyPort +attributes on the <Connector> element to configure +these values.

    + +

    Proxy support can take many forms. The following sections describe +proxy configurations for several common cases.

    + +

    Apache httpd Proxy Support

    + +

    Apache httpd 1.3 and later versions support an optional module +(mod_proxy) that configures the web server to act as a proxy +server. This can be used to forward requests for a particular web application +to a Tomcat instance, without having to configure a web connector such as +mod_jk. To accomplish this, you need to perform the following +tasks:

    +
      +
    1. Configure your copy of Apache so that it includes the + mod_proxy module. If you are building from source, + the easiest way to do this is to include the + --enable-module=proxy directive on the + ./configure command line.

    2. +
    3. If not already added for you, make sure that you are loading the + mod_proxy module at Apache startup time, by using the + following directives in your httpd.conf file:

      +
      LoadModule proxy_module  {path-to-modules}/mod_proxy.so
      +
    4. +
    5. Include two directives in your httpd.conf file for + each web application that you wish to forward to Tomcat. For + example, to forward an application at context path /myapp:

      +
      ProxyPass         /myapp  http://localhost:8081/myapp
      +ProxyPassReverse  /myapp  http://localhost:8081/myapp
      +

      which tells Apache to forward URLs of the form + http://localhost/myapp/* to the Tomcat connector + listening on port 8081.

    6. +
    7. Configure your copy of Tomcat to include a special + <Connector> element, with appropriate + proxy settings, for example:

      +
      <Connector port="8081" ...
      +              proxyName="www.mycompany.com"
      +              proxyPort="80"/>
      +

      which will cause servlets inside this web application to think that + all proxied requests were directed to www.mycompany.com + on port 80.

    8. +
    9. It is legal to omit the proxyName attribute from the + <Connector> element. If you do so, the value + returned by request.getServerName() will by the host + name on which Tomcat is running. In the example above, it would be + localhost.

    10. +
    11. If you also have a <Connector> listening on port + 8080 (nested within the same Service + element), the requests to either port will share the same set of + virtual hosts and web applications.

    12. +
    13. You might wish to use the IP filtering features of your operating + system to restrict connections to port 8081 (in this example) to + be allowed only from the server that is running + Apache.

    14. +
    15. Alternatively, you can set up a series of web applications that are + only available via proxying, as follows:

      +
        +
      • Configure another <Service> that contains + only a <Connector> for the proxy port.
      • +
      • Configure appropriate Engine, + Host, and + Context elements for the virtual hosts + and web applications accessible via proxying.
      • +
      • Optionally, protect port 8081 with IP filters as described + earlier.
      • +
    16. +
    17. When requests are proxied by Apache, the web server will be recording + these requests in its access log. Therefore, you will generally want to + disable any access logging performed by Tomcat itself.

    18. +
    + +

    When requests are proxied in this manner, all requests +for the configured web applications will be processed by Tomcat (including +requests for static content). You can improve performance by using the +mod_jk web connector instead of mod_proxy. +mod_jk can be configured so that the web server serves static +content that is not processed by filters or security constraints defined +within the web application's deployment descriptor +(/WEB-INF/web.xml).

    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/realm-howto.html b/tomcat/docs/realm-howto.html new file mode 100644 index 0000000..3d1b357 --- /dev/null +++ b/tomcat/docs/realm-howto.html @@ -0,0 +1,1223 @@ + +Apache Tomcat 8 (8.5.43) - Realm Configuration How-To

    Realm Configuration How-To

    Table of Contents

    Quick Start

    + +

    This document describes how to configure Tomcat to support container +managed security, by connecting to an existing "database" of usernames, +passwords, and user roles. You only need to care about this if you are using +a web application that includes one or more +<security-constraint> elements, and a +<login-config> element defining how users are required +to authenticate themselves. If you are not utilizing these features, you can +safely skip this document.

    + +

    For fundamental background information about container managed security, +see the Servlet +Specification (Version 2.4), Section 12.

    + +

    For information about utilizing the Single Sign On feature of +Tomcat (allowing a user to authenticate themselves once across the entire +set of web applications associated with a virtual host), see +here.

    + +

    Overview

    + + +

    What is a Realm?

    + +

    A Realm is a "database" of usernames and passwords that +identify valid users of a web application (or set of web applications), plus +an enumeration of the list of roles associated with each valid user. +You can think of roles as similar to groups in Unix-like operating +systems, because access to specific web application resources is granted to +all users possessing a particular role (rather than enumerating the list of +associated usernames). A particular user can have any number of roles +associated with their username.

    + +

    Although the Servlet Specification describes a portable mechanism for +applications to declare their security requirements (in the +web.xml deployment descriptor), there is no portable API +defining the interface between a servlet container and the associated user +and role information. In many cases, however, it is desirable to "connect" +a servlet container to some existing authentication database or mechanism +that already exists in the production environment. Therefore, Tomcat +defines a Java interface (org.apache.catalina.Realm) that +can be implemented by "plug in" components to establish this connection. +Six standard plug-ins are provided, supporting connections to various +sources of authentication information:

    +
      +
    • JDBCRealm - Accesses authentication information + stored in a relational database, accessed via a JDBC driver.
    • +
    • DataSourceRealm - Accesses authentication + information stored in a relational database, accessed via a named JNDI + JDBC DataSource.
    • +
    • JNDIRealm - Accesses authentication information + stored in an LDAP based directory server, accessed via a JNDI provider. +
    • +
    • UserDatabaseRealm - Accesses authentication + information stored in an UserDatabase JNDI resource, which is typically + backed by an XML document (conf/tomcat-users.xml).
    • +
    • MemoryRealm - Accesses authentication + information stored in an in-memory object collection, which is initialized + from an XML document (conf/tomcat-users.xml).
    • +
    • JAASRealm - Accesses authentication information + through the Java Authentication & Authorization Service (JAAS) + framework.
    • +
    + +

    It is also possible to write your own Realm implementation, +and integrate it with Tomcat. To do so, you need to:

    +
      +
    • Implement org.apache.catalina.Realm,
    • +
    • Place your compiled realm in $CATALINA_HOME/lib,
    • +
    • Declare your realm as described in the "Configuring a Realm" section below,
    • +
    • Declare your realm to the MBeans Descriptors.
    • +
    + +
    + + +

    Configuring a Realm

    + +

    Before getting into the details of the standard Realm implementations, it is +important to understand, in general terms, how a Realm is configured. In +general, you will be adding an XML element to your conf/server.xml +configuration file, that looks something like this:

    + +
    <Realm className="... class name for this implementation"
    +       ... other attributes for this implementation .../>
    + +

    The <Realm> element can be nested inside any one of +of the following Container elements. The location of the +Realm element has a direct impact on the "scope" of that Realm +(i.e. which web applications will share the same authentication information): +

    +
      +
    • Inside an <Engine> element - This Realm will be shared + across ALL web applications on ALL virtual hosts, UNLESS it is overridden + by a Realm element nested inside a subordinate <Host> + or <Context> element.
    • +
    • Inside a <Host> element - This Realm will be shared across + ALL web applications for THIS virtual host, UNLESS it is overridden + by a Realm element nested inside a subordinate <Context> + element.
    • +
    • Inside a <Context> element - This Realm will be used ONLY + for THIS web application.
    • +
    + + +
    + + +

    Common Features

    + + +

    Digested Passwords

    + +

    For each of the standard Realm implementations, the +user's password (by default) is stored in clear text. In many +environments, this is undesirable because casual observers of the +authentication data can collect enough information to log on +successfully, and impersonate other users. To avoid this problem, the +standard implementations support the concept of digesting +user passwords. This allows the stored version of the passwords to be +encoded (in a form that is not easily reversible), but that the +Realm implementation can still utilize for +authentication.

    + +

    When a standard realm authenticates by retrieving the stored +password and comparing it with the value presented by the user, you +can select digested passwords by placing a +CredentialHandler element inside your <Realm> +element. An easy choice to support one of the algorithms SSHA, SHA or MD5 +would be the usage of the MessageDigestCredentialHandler. +This element must be configured to one of the digest algorithms supported +by the java.security.MessageDigest class (SSHA, SHA or MD5). +When you select this option, the contents of the password that is stored +in the Realm must be the cleartext version of the password, +as digested by the specified algorithm.

    + +

    When the authenticate() method of the Realm is called, the +(cleartext) password specified by the user is itself digested by the same +algorithm, and the result is compared with the value returned by the +Realm. An equal match implies that the cleartext version of the +original password is the same as the one presented by the user, so that this +user should be authorized.

    + +

    To calculate the digested value of a cleartext password, two convenience +techniques are supported:

    +
      +
    • If you are writing an application that needs to calculate digested + passwords dynamically, call the static Digest() method of the + org.apache.catalina.realm.RealmBase class, passing the + cleartext password, the digest algorithm name and the encoding as arguments. + This method will return the digested password.
    • +
    • If you want to execute a command line utility to calculate the digested + password, simply execute +
      CATALINA_HOME/bin/digest.[bat|sh] -a {algorithm} {cleartext-password}
      + and the digested version of this cleartext password will be returned to + standard output.
    • +
    + +

    If using digested passwords with DIGEST authentication, the cleartext used + to generate the digest is different and the digest must use one iteration of + the MD5 algorithm with no salt. In the examples above + {cleartext-password} must be replaced with + {username}:{realm}:{cleartext-password}. For example, in a + development environment this might take the form + testUser:Authentication required:testPassword. The value for + {realm} is taken from the <realm-name> + element of the web application's <login-config>. If + not specified in web.xml, the default value of Authentication + required is used.

    + +

    Usernames and/or passwords using encodings other than the platform default +are supported using

    +
    CATALINA_HOME/bin/digest.[bat|sh] -a {algorithm} -e {encoding} {input}
    +

    but care is required to ensure that the input is correctly passed to the +digester. The digester returns {input}:{digest}. If the input +appears corrupted in the return, the digest will be invalid.

    + +

    The output format of the digest is {salt}${iterations}${digest}. +If the salt length is zero and the iteration count is one, the output is +simplified to {digest}.

    + +

    The full syntax of CATALINA_HOME/bin/digest.[bat|sh] is:

    +
    CATALINA_HOME/bin/digest.[bat|sh] [-a <algorithm>] [-e <encoding>]
    +        [-i <iterations>] [-s <salt-length>] [-k <key-length>]
    +        [-h <handler-class-name>] <credentials>
    +
    +
      +
    • -a - The algorithm to use to generate the stored + credential. If not specified, the default for the handler will + be used. If neither handler nor algorithm is specified then a + default of SHA-512 will be used
    • +
    • -e - The encoding to use for any byte to/from character + conversion that may be necessary. If not specified, the + system encoding (Charset#defaultCharset()) will + be used.
    • +
    • -i - The number of iterations to use when generating the + stored credential. If not specified, the default for the + CredentialHandler will be used.
    • +
    • -s - The length (in bytes) of salt to generate and store as + part of the credential. If not specified, the default for + the CredentialHandler will be used.
    • +
    • -k - The length (in bits) of the key(s), if any, created while + generating the credential. If not specified, the default + for the CredentialHandler will be used.
    • +
    • -h - The fully qualified class name of the CredentialHandler + to use. If not specified, the built-in handlers will be + tested in turn (MessageDigestCredentialHandler then + SecretKeyCredentialHandler) and the first one to accept the + specified algorithm will be used.
    • +
    +
    + + + +

    Example Application

    + +

    The example application shipped with Tomcat includes an area that is +protected by a security constraint, utilizing form-based login. To access it, +point your browser at +http://localhost:8080/examples/jsp/security/protected/ +and log on with one of the usernames and passwords described for the default +UserDatabaseRealm.

    + +
    + + +

    Manager Application

    + +

    If you wish to use the Manager Application +to deploy and undeploy applications in a running Tomcat installation, you +MUST add the "manager-gui" role to at least one username in your selected +Realm implementation. This is because the manager web application itself uses a +security constraint that requires role "manager-gui" to access ANY request URI +within the HTML interface of that application.

    + +

    For security reasons, no username in the default Realm (i.e. using +conf/tomcat-users.xml is assigned the "manager-gui" role. +Therefore, no one will be able to utilize the features of this application +until the Tomcat administrator specifically assigns this role to one or more +users.

    + +
    + +

    Realm Logging

    + +

    Debugging and exception messages logged by a Realm will + be recorded by the logging configuration associated with the container + for the realm: its surrounding Context, + Host, or + Engine.

    + +
    + +

    Standard Realm Implementations

    + +

    JDBCRealm

    + +
    Introduction
    + +

    JDBCRealm is an implementation of the Tomcat +Realm interface that looks up users in a relational database +accessed via a JDBC driver. There is substantial configuration flexibility +that lets you adapt to existing table and column names, as long as your +database structure conforms to the following requirements:

    +
      +
    • There must be a table, referenced below as the users table, + that contains one row for every valid user that this Realm + should recognize.
    • +
    • The users table must contain at least two columns (it may + contain more if your existing applications required it): +
        +
      • Username to be recognized by Tomcat when the user logs in.
      • +
      • Password to be recognized by Tomcat when the user logs in. + This value may in cleartext or digested - see below for more + information.
      • +
    • +
    • There must be a table, referenced below as the user roles table, + that contains one row for every valid role that is assigned to a + particular user. It is legal for a user to have zero, one, or more than + one valid role.
    • +
    • The user roles table must contain at least two columns (it may + contain more if your existing applications required it): +
        +
      • Username to be recognized by Tomcat (same value as is specified + in the users table).
      • +
      • Role name of a valid role associated with this user.
      • +
    • +
    + +
    Quick Start
    + +

    To set up Tomcat to use JDBCRealm, you will need to follow these steps:

    +
      +
    1. If you have not yet done so, create tables and columns in your database + that conform to the requirements described above.
    2. +
    3. Configure a database username and password for use by Tomcat, that has + at least read only access to the tables described above. (Tomcat will + never attempt to write to these tables.)
    4. +
    5. Place a copy of the JDBC driver you will be using inside the + $CATALINA_HOME/lib directory. + Note that only JAR files are recognized!
    6. +
    7. Set up a <Realm> element, as described below, in your + $CATALINA_BASE/conf/server.xml file.
    8. +
    9. Restart Tomcat if it is already running.
    10. +
    + +
    Realm Element Attributes
    + +

    To configure JDBCRealm, you will create a <Realm> +element and nest it in your $CATALINA_BASE/conf/server.xml file, +as described above. The attributes for the +JDBCRealm are defined in the Realm configuration +documentation.

    + +
    Example
    + +

    An example SQL script to create the needed tables might look something +like this (adapt the syntax as required for your particular database):

    +
    create table users (
    +  user_name         varchar(15) not null primary key,
    +  user_pass         varchar(15) not null
    +);
    +
    +create table user_roles (
    +  user_name         varchar(15) not null,
    +  role_name         varchar(15) not null,
    +  primary key (user_name, role_name)
    +);
    + +

    Example Realm elements are included (commented out) in the +default $CATALINA_BASE/conf/server.xml file. Here's an example +for using a MySQL database called "authority", configured with the tables +described above, and accessed with username "dbuser" and password "dbpass":

    +
    <Realm className="org.apache.catalina.realm.JDBCRealm"
    +      driverName="org.gjt.mm.mysql.Driver"
    +   connectionURL="jdbc:mysql://localhost/authority?user=dbuser&amp;password=dbpass"
    +       userTable="users" userNameCol="user_name" userCredCol="user_pass"
    +   userRoleTable="user_roles" roleNameCol="role_name"/>
    + +
    Additional Notes
    + +

    JDBCRealm operates according to the following rules:

    +
      +
    • When a user attempts to access a protected resource for the first time, + Tomcat will call the authenticate() method of this + Realm. Thus, any changes you have made to the database + directly (new users, changed passwords or roles, etc.) will be immediately + reflected.
    • +
    • Once a user has been authenticated, the user (and his or her associated + roles) are cached within Tomcat for the duration of the user's login. + (For FORM-based authentication, that means until the session times out or + is invalidated; for BASIC authentication, that means until the user + closes their browser). The cached user is not saved and + restored across sessions serialisations. Any changes to the database + information for an already authenticated user will not be + reflected until the next time that user logs on again.
    • +
    • Administering the information in the users and user roles + table is the responsibility of your own applications. Tomcat does not + provide any built-in capabilities to maintain users and roles.
    • +
    + +
    + + +

    DataSourceRealm

    + +
    Introduction
    + +

    DataSourceRealm is an implementation of the Tomcat +Realm interface that looks up users in a relational database +accessed via a JNDI named JDBC DataSource. There is substantial configuration +flexibility that lets you adapt to existing table and column names, as long +as your database structure conforms to the following requirements:

    +
      +
    • There must be a table, referenced below as the users table, + that contains one row for every valid user that this Realm + should recognize.
    • +
    • The users table must contain at least two columns (it may + contain more if your existing applications required it): +
        +
      • Username to be recognized by Tomcat when the user logs in.
      • +
      • Password to be recognized by Tomcat when the user logs in. + This value may in cleartext or digested - see below for more + information.
      • +
    • +
    • There must be a table, referenced below as the user roles table, + that contains one row for every valid role that is assigned to a + particular user. It is legal for a user to have zero, one, or more than + one valid role.
    • +
    • The user roles table must contain at least two columns (it may + contain more if your existing applications required it): +
        +
      • Username to be recognized by Tomcat (same value as is specified + in the users table).
      • +
      • Role name of a valid role associated with this user.
      • +
    • +
    + +
    Quick Start
    + +

    To set up Tomcat to use DataSourceRealm, you will need to follow these steps:

    +
      +
    1. If you have not yet done so, create tables and columns in your database + that conform to the requirements described above.
    2. +
    3. Configure a database username and password for use by Tomcat, that has + at least read only access to the tables described above. (Tomcat will + never attempt to write to these tables.)
    4. +
    5. Configure a JNDI named JDBC DataSource for your database. Refer to the + JNDI DataSource Example + How-To for information on how to configure a JNDI named JDBC DataSource. + Be sure to set the Realm's localDataSource + attribute appropriately, depending on where the JNDI DataSource is + defined.
    6. +
    7. Set up a <Realm> element, as described below, in your + $CATALINA_BASE/conf/server.xml file.
    8. +
    9. Restart Tomcat if it is already running.
    10. +
    + +
    Realm Element Attributes
    + +

    To configure DataSourceRealm, you will create a <Realm> +element and nest it in your $CATALINA_BASE/conf/server.xml file, +as described above. The attributes for the +DataSourceRealm are defined in the Realm +configuration documentation.

    + +
    Example
    + +

    An example SQL script to create the needed tables might look something +like this (adapt the syntax as required for your particular database):

    +
    create table users (
    +  user_name         varchar(15) not null primary key,
    +  user_pass         varchar(15) not null
    +);
    +
    +create table user_roles (
    +  user_name         varchar(15) not null,
    +  role_name         varchar(15) not null,
    +  primary key (user_name, role_name)
    +);
    + +

    Here is an example for using a MySQL database called "authority", configured +with the tables described above, and accessed with the JNDI JDBC DataSource with +name "java:/comp/env/jdbc/authority".

    +
    <Realm className="org.apache.catalina.realm.DataSourceRealm"
    +   dataSourceName="jdbc/authority"
    +   userTable="users" userNameCol="user_name" userCredCol="user_pass"
    +   userRoleTable="user_roles" roleNameCol="role_name"/>
    + +
    Additional Notes
    + +

    DataSourceRealm operates according to the following rules:

    +
      +
    • When a user attempts to access a protected resource for the first time, + Tomcat will call the authenticate() method of this + Realm. Thus, any changes you have made to the database + directly (new users, changed passwords or roles, etc.) will be immediately + reflected.
    • +
    • Once a user has been authenticated, the user (and his or her associated + roles) are cached within Tomcat for the duration of the user's login. + (For FORM-based authentication, that means until the session times out or + is invalidated; for BASIC authentication, that means until the user + closes their browser). The cached user is not saved and + restored across sessions serialisations. Any changes to the database + information for an already authenticated user will not be + reflected until the next time that user logs on again.
    • +
    • Administering the information in the users and user roles + table is the responsibility of your own applications. Tomcat does not + provide any built-in capabilities to maintain users and roles.
    • +
    + +
    + + +

    JNDIRealm

    + +
    Introduction
    + +

    JNDIRealm is an implementation of the Tomcat +Realm interface that looks up users in an LDAP directory +server accessed by a JNDI provider (typically, the standard LDAP +provider that is available with the JNDI API classes). The realm +supports a variety of approaches to using a directory for +authentication.

    + +
    Connecting to the directory
    + +

    The realm's connection to the directory is defined by the +connectionURL configuration attribute. This is a URL +whose format is defined by the JNDI provider. It is usually an LDAP +URL that specifies the domain name of the directory server to connect +to, and optionally the port number and distinguished name (DN) of the +required root naming context.

    + +

    If you have more than one provider you can configure an +alternateURL. If a socket connection cannot be +made to the provider at the connectionURL an +attempt will be made to use the alternateURL.

    + +

    When making a connection in order to search the directory and +retrieve user and role information, the realm authenticates itself to +the directory with the username and password specified by the +connectionName and +connectionPassword properties. If these properties +are not specified the connection is anonymous. This is sufficient in +many cases. +

    + + +
    Selecting the user's directory entry
    + +

    Each user that can be authenticated must be represented in the +directory by an individual entry that corresponds to an element in the +initial DirContext defined by the +connectionURL attribute. This user entry must have an +attribute containing the username that is presented for +authentication.

    + +

    Often the distinguished name of the user's entry contains the +username presented for authentication but is otherwise the same for +all users. In this case the userPattern attribute may +be used to specify the DN, with "{0}" marking where +the username should be substituted.

    + +

    Otherwise the realm must search the directory to find a unique entry +containing the username. The following attributes configure this +search:

    + +
      +
    • userBase - the entry that is the base of + the subtree containing users. If not specified, the search + base is the top-level context.
    • + +
    • userSubtree - the search scope. Set to + true if you wish to search the entire subtree + rooted at the userBase entry. The default value + of false requests a single-level search + including only the top level.
    • + +
    • userSearch - pattern specifying the LDAP + search filter to use after substitution of the username.
    • + +
    + + +
    Authenticating the user
    + +
      +
    • +

      Bind mode

      + +

      By default the realm authenticates a user by binding to +the directory with the DN of the entry for that user and the password +presented by the user. If this simple bind succeeds the user is considered to +be authenticated.

      + +

      For security reasons a directory may store a digest of the user's +password rather than the clear text version (see +Digested Passwords for more information). In that case, +as part of the simple bind operation the directory automatically +computes the correct digest of the plaintext password presented by the +user before validating it against the stored value. In bind mode, +therefore, the realm is not involved in digest processing. The +digest attribute is not used, and will be ignored if +set.

      +
    • + +
    • +

      Comparison mode

      +

      Alternatively, the realm may retrieve the stored +password from the directory and compare it explicitly with the value +presented by the user. This mode is configured by setting the +userPassword attribute to the name of a directory +attribute in the user's entry that contains the password.

      + +

      Comparison mode has some disadvantages. First, the +connectionName and +connectionPassword attributes must be configured to +allow the realm to read users' passwords in the directory. For +security reasons this is generally undesirable; indeed many directory +implementations will not allow even the directory manager to read +these passwords. In addition, the realm must handle password digests +itself, including variations in the algorithms used and ways of +representing password hashes in the directory. However, the realm may +sometimes need access to the stored password, for example to support +HTTP Digest Access Authentication (RFC 2069). (Note that HTTP digest +authentication is different from the storage of password digests in +the repository for user information as discussed above). +

      +
    • +
    + +
    Assigning roles to the user
    + +

    The directory realm supports two approaches to the representation +of roles in the directory:

    + +
      +
    • +

      Roles as explicit directory entries

      + +

      Roles may be represented by explicit directory entries. A role +entry is usually an LDAP group entry with one attribute +containing the name of the role and another whose values are the +distinguished names or usernames of the users in that role. The +following attributes configure a directory search to +find the names of roles associated with the authenticated user:

      + +
        +
      • roleBase - the base entry for the role search. + If not specified, the search base is the top-level directory + context.
      • + +
      • roleSubtree - the search + scope. Set to true if you wish to search the entire + subtree rooted at the roleBase entry. The default + value of false requests a single-level search + including the top level only.
      • + +
      • roleSearch - the LDAP search filter for + selecting role entries. It optionally includes pattern + replacements "{0}" for the distinguished name and/or "{1}" for the + username and/or "{2}" for an attribute from user's directory entry, + of the authenticated user. Use userRoleAttribute to + specify the name of the attribute that provides the value for "{2}".
      • + +
      • roleName - the attribute in a role entry + containing the name of that role.
      • + +
      • roleNested - enable nested roles. Set to + true if you want to nest roles in roles. If configured, then + every newly found roleName and distinguished + Name will be recursively tried for a new role search. + The default value is false.
      • + +
      + +
    • +
    + +
      +
    • +

      Roles as an attribute of the user entry

      + +

      Role names may also be held as the values of an attribute in the +user's directory entry. Use userRoleName to specify +the name of this attribute.

      + +
    • +
    +

    A combination of both approaches to role representation may be used.

    + +
    Quick Start
    + +

    To set up Tomcat to use JNDIRealm, you will need to follow these steps:

    +
      +
    1. Make sure your directory server is configured with a schema that matches + the requirements listed above.
    2. +
    3. If required, configure a username and password for use by Tomcat, that has + read only access to the information described above. (Tomcat will + never attempt to modify this information.)
    4. +
    5. Set up a <Realm> element, as described below, in your + $CATALINA_BASE/conf/server.xml file.
    6. +
    7. Restart Tomcat if it is already running.
    8. +
    + +
    Realm Element Attributes
    + +

    To configure JNDIRealm, you will create a <Realm> +element and nest it in your $CATALINA_BASE/conf/server.xml file, +as described above. The attributes for the +JNDIRealm are defined in the Realm configuration +documentation.

    + +
    Example
    + +

    Creation of the appropriate schema in your directory server is beyond the +scope of this document, because it is unique to each directory server +implementation. In the examples below, we will assume that you are using a +distribution of the OpenLDAP directory server (version 2.0.11 or later), which +can be downloaded from +https://www.openldap.org. Assume that +your slapd.conf file contains the following settings +(among others):

    +
    database ldbm
    +suffix dc="mycompany",dc="com"
    +rootdn "cn=Manager,dc=mycompany,dc=com"
    +rootpw secret
    + +

    We will assume for connectionURL that the directory +server runs on the same machine as Tomcat. See +http://docs.oracle.com/javase/7/docs/technotes/guides/jndi/index.html +for more information about configuring and using the JNDI LDAP +provider.

    + +

    Next, assume that this directory server has been populated with elements +as shown below (in LDIF format):

    + +
    # Define top-level entry
    +dn: dc=mycompany,dc=com
    +objectClass: dcObject
    +dc:mycompany
    +
    +# Define an entry to contain people
    +# searches for users are based on this entry
    +dn: ou=people,dc=mycompany,dc=com
    +objectClass: organizationalUnit
    +ou: people
    +
    +# Define a user entry for Janet Jones
    +dn: uid=jjones,ou=people,dc=mycompany,dc=com
    +objectClass: inetOrgPerson
    +uid: jjones
    +sn: jones
    +cn: janet jones
    +mail: j.jones@mycompany.com
    +userPassword: janet
    +
    +# Define a user entry for Fred Bloggs
    +dn: uid=fbloggs,ou=people,dc=mycompany,dc=com
    +objectClass: inetOrgPerson
    +uid: fbloggs
    +sn: bloggs
    +cn: fred bloggs
    +mail: f.bloggs@mycompany.com
    +userPassword: fred
    +
    +# Define an entry to contain LDAP groups
    +# searches for roles are based on this entry
    +dn: ou=groups,dc=mycompany,dc=com
    +objectClass: organizationalUnit
    +ou: groups
    +
    +# Define an entry for the "tomcat" role
    +dn: cn=tomcat,ou=groups,dc=mycompany,dc=com
    +objectClass: groupOfUniqueNames
    +cn: tomcat
    +uniqueMember: uid=jjones,ou=people,dc=mycompany,dc=com
    +uniqueMember: uid=fbloggs,ou=people,dc=mycompany,dc=com
    +
    +# Define an entry for the "role1" role
    +dn: cn=role1,ou=groups,dc=mycompany,dc=com
    +objectClass: groupOfUniqueNames
    +cn: role1
    +uniqueMember: uid=fbloggs,ou=people,dc=mycompany,dc=com
    + +

    An example Realm element for the OpenLDAP directory +server configured as described above might look like this, assuming +that users use their uid (e.g. jjones) to login to the +application and that an anonymous connection is sufficient to search +the directory and retrieve role information:

    + +
    <Realm   className="org.apache.catalina.realm.JNDIRealm"
    +     connectionURL="ldap://localhost:389"
    +       userPattern="uid={0},ou=people,dc=mycompany,dc=com"
    +          roleBase="ou=groups,dc=mycompany,dc=com"
    +          roleName="cn"
    +        roleSearch="(uniqueMember={0})"
    +/>
    + +

    With this configuration, the realm will determine the user's +distinguished name by substituting the username into the +userPattern, authenticate by binding to the directory +with this DN and the password received from the user, and search the +directory to find the user's roles.

    + +

    Now suppose that users are expected to enter their email address +rather than their userid when logging in. In this case the realm must +search the directory for the user's entry. (A search is also necessary +when user entries are held in multiple subtrees corresponding perhaps +to different organizational units or company locations).

    + +

    Further, suppose that in addition to the group entries you want to +use an attribute of the user's entry to hold roles. Now the entry for +Janet Jones might read as follows:

    + +
    dn: uid=jjones,ou=people,dc=mycompany,dc=com
    +objectClass: inetOrgPerson
    +uid: jjones
    +sn: jones
    +cn: janet jones
    +mail: j.jones@mycompany.com
    +memberOf: role2
    +memberOf: role3
    +userPassword: janet
    + +

    This realm configuration would satisfy the new requirements:

    + +
    <Realm   className="org.apache.catalina.realm.JNDIRealm"
    +     connectionURL="ldap://localhost:389"
    +          userBase="ou=people,dc=mycompany,dc=com"
    +        userSearch="(mail={0})"
    +      userRoleName="memberOf"
    +          roleBase="ou=groups,dc=mycompany,dc=com"
    +          roleName="cn"
    +        roleSearch="(uniqueMember={0})"
    +/>
    + +

    Now when Janet Jones logs in as "j.jones@mycompany.com", the realm +searches the directory for a unique entry with that value as its mail +attribute and attempts to bind to the directory as +uid=jjones,ou=people,dc=mycompany,dc=com with the given +password. If authentication succeeds, she is assigned three roles: +"role2" and "role3", the values of the "memberOf" attribute in her +directory entry, and "tomcat", the value of the "cn" attribute in the +only group entry of which she is a member.

    + +

    Finally, to authenticate the user by retrieving +the password from the directory and making a local comparison in the +realm, you might use a realm configuration like this:

    + +
    <Realm   className="org.apache.catalina.realm.JNDIRealm"
    +    connectionName="cn=Manager,dc=mycompany,dc=com"
    +connectionPassword="secret"
    +     connectionURL="ldap://localhost:389"
    +      userPassword="userPassword"
    +       userPattern="uid={0},ou=people,dc=mycompany,dc=com"
    +          roleBase="ou=groups,dc=mycompany,dc=com"
    +          roleName="cn"
    +        roleSearch="(uniqueMember={0})"
    +/>
    + +

    However, as discussed above, the default bind mode for +authentication is usually to be preferred.

    + +
    Additional Notes
    + +

    JNDIRealm operates according to the following rules:

    +
      +
    • When a user attempts to access a protected resource for the first time, + Tomcat will call the authenticate() method of this + Realm. Thus, any changes you have made to the directory + (new users, changed passwords or roles, etc.) will be immediately + reflected.
    • +
    • Once a user has been authenticated, the user (and his or her associated + roles) are cached within Tomcat for the duration of the user's login. + (For FORM-based authentication, that means until the session times out or + is invalidated; for BASIC authentication, that means until the user + closes their browser). The cached user is not saved and + restored across sessions serialisations. Any changes to the directory + information for an already authenticated user will not be + reflected until the next time that user logs on again.
    • +
    • Administering the information in the directory server + is the responsibility of your own applications. Tomcat does not + provide any built-in capabilities to maintain users and roles.
    • +
    + +
    + + +

    UserDatabaseRealm

    + +
    Introduction
    + +

    UserDatabaseRealm is an implementation of the Tomcat +Realm interface that uses a JNDI resource to store user +information. By default, the JNDI resource is backed by an XML file. It is not +designed for large-scale production use. At startup time, the UserDatabaseRealm +loads information about all users, and their corresponding roles, from an XML +document (by default, this document is loaded from +$CATALINA_BASE/conf/tomcat-users.xml). The users, their passwords +and their roles may all be editing dynamically, typically via JMX. Changes may +be saved and will be reflected in the XML file.

    + +
    Realm Element Attributes
    + +

    To configure UserDatabaseRealm, you will create a <Realm> +element and nest it in your $CATALINA_BASE/conf/server.xml file, +as described above. The attributes for the +UserDatabaseRealm are defined in the Realm +configuration documentation.

    + +
    User File Format
    + +

    The users file uses the same format as the +MemoryRealm.

    + +
    Example
    + +

    The default installation of Tomcat is configured with a UserDatabaseRealm +nested inside the <Engine> element, so that it applies +to all virtual hosts and web applications. The default contents of the +conf/tomcat-users.xml file is:

    +
    <tomcat-users>
    +  <user username="tomcat" password="tomcat" roles="tomcat" />
    +  <user username="role1"  password="tomcat" roles="role1"  />
    +  <user username="both"   password="tomcat" roles="tomcat,role1" />
    +</tomcat-users>
    + +
    Additional Notes
    + +

    UserDatabaseRealm operates according to the following rules:

    +
      +
    • When Tomcat first starts up, it loads all defined users and their + associated information from the users file. Changes made to the data in + this file will not be recognized until Tomcat is + restarted. Changes may be made via the UserDatabase resource. Tomcat + provides MBeans that may be accessed via JMX for this purpose.
    • +
    • When a user attempts to access a protected resource for the first time, + Tomcat will call the authenticate() method of this + Realm.
    • +
    • Once a user has been authenticated, the user (and his or her associated + roles) are cached within Tomcat for the duration of the user's login. + (For FORM-based authentication, that means until the session times out or + is invalidated; for BASIC authentication, that means until the user + closes their browser). The cached user is not saved and + restored across sessions serialisations.
    • +
    + + +
    + + +

    MemoryRealm

    + +
    Introduction
    + +

    MemoryRealm is a simple demonstration implementation of the +Tomcat Realm interface. It is not designed for production use. +At startup time, MemoryRealm loads information about all users, and their +corresponding roles, from an XML document (by default, this document is loaded +from $CATALINA_BASE/conf/tomcat-users.xml). Changes to the data +in this file are not recognized until Tomcat is restarted.

    + +
    Realm Element Attributes
    + +

    To configure MemoryRealm, you will create a <Realm> +element and nest it in your $CATALINA_BASE/conf/server.xml file, +as described above. The attributes for the +MemoryRealm are defined in the Realm +configuration documentation.

    + +
    User File Format
    + +

    The users file (by default, conf/tomcat-users.xml must be an +XML document, with a root element <tomcat-users>. Nested +inside the root element will be a <user> element for each +valid user, consisting of the following attributes:

    +
      +
    • name - Username this user must log on with.
    • +
    • password - Password this user must log on with (in + clear text if the digest attribute was not set on the + <Realm> element, or digested appropriately as + described here otherwise).
    • +
    • roles - Comma-delimited list of the role names + associated with this user.
    • +
    + +
    Additional Notes
    + +

    MemoryRealm operates according to the following rules:

    +
      +
    • When Tomcat first starts up, it loads all defined users and their + associated information from the users file. Changes to the data in + this file will not be recognized until Tomcat is + restarted.
    • +
    • When a user attempts to access a protected resource for the first time, + Tomcat will call the authenticate() method of this + Realm.
    • +
    • Once a user has been authenticated, the user (and his or her associated + roles) are cached within Tomcat for the duration of the user's login. + (For FORM-based authentication, that means until the session times out or + is invalidated; for BASIC authentication, that means until the user + closes their browser). The cached user is not saved and + restored across sessions serialisations.
    • +
    • Administering the information in the users file is the responsibility + of your application. Tomcat does not + provide any built-in capabilities to maintain users and roles.
    • +
    + + +
    + + +

    JAASRealm

    + +
    Introduction
    + +

    JAASRealm is an implementation of the Tomcat +Realm interface that authenticates users through the Java +Authentication & Authorization Service (JAAS) framework which is now +provided as part of the standard Java SE API.

    +

    Using JAASRealm gives the developer the ability to combine +practically any conceivable security realm with Tomcat's CMA.

    +

    JAASRealm is prototype for Tomcat of the JAAS-based +J2EE authentication framework for J2EE v1.4, based on the JCP Specification +Request 196 to enhance container-managed security and promote +'pluggable' authentication mechanisms whose implementations would be +container-independent. +

    +

    Based on the JAAS login module and principal (see javax.security.auth.spi.LoginModule +and javax.security.Principal), you can develop your own +security mechanism or wrap another third-party mechanism for +integration with the CMA as implemented by Tomcat. +

    + +
    Quick Start
    +

    To set up Tomcat to use JAASRealm with your own JAAS login module, + you will need to follow these steps:

    +
      +
    1. Write your own LoginModule, User and Role classes based +on JAAS (see + +the JAAS Authentication Tutorial and + +the JAAS Login Module Developer's Guide) to be managed by the JAAS Login +Context (javax.security.auth.login.LoginContext) +When developing your LoginModule, note that JAASRealm's built-in CallbackHandler +only recognizes the NameCallback and PasswordCallback at present. +
    2. +
    3. Although not specified in JAAS, you should create +separate classes to distinguish between users and roles, extending javax.security.Principal, +so that Tomcat can tell which Principals returned from your login +module are users and which are roles (see org.apache.catalina.realm.JAASRealm). +Regardless, the first Principal returned is always treated as the user Principal. +
    4. +
    5. Place the compiled classes on Tomcat's classpath +
    6. +
    7. Set up a login.config file for Java (see +JAAS LoginConfig file) and tell Tomcat where to find it by specifying +its location to the JVM, for instance by setting the environment +variable: JAVA_OPTS=$JAVA_OPTS -Djava.security.auth.login.config==$CATALINA_BASE/conf/jaas.config
    8. + +
    9. Configure your security-constraints in your web.xml for +the resources you want to protect
    10. +
    11. Configure the JAASRealm module in your server.xml
    12. +
    13. Restart Tomcat if it is already running.
    14. +
    +
    Realm Element Attributes
    +

    To configure JAASRealm as for step 6 above, you create +a <Realm> element and nest it in your +$CATALINA_BASE/conf/server.xml +file within your <Engine> node. The attributes for the +JAASRealm are defined in the Realm +configuration documentation.

    + +
    Example
    + +

    Here is an example of how your server.xml snippet should look.

    + +
    <Realm className="org.apache.catalina.realm.JAASRealm"
    +                appName="MyFooRealm"
    +    userClassNames="org.foobar.realm.FooUser"
    +     roleClassNames="org.foobar.realm.FooRole"/>
    + +

    It is the responsibility of your login module to create and save User and +Role objects representing Principals for the user +(javax.security.auth.Subject). If your login module doesn't +create a user object but also doesn't throw a login exception, then the +Tomcat CMA will break and you will be left at the +http://localhost:8080/myapp/j_security_check URI or at some other +unspecified location.

    + +

    The flexibility of the JAAS approach is two-fold:

    +
      +
    • you can carry out whatever processing you require behind +the scenes in your own login module.
    • +
    • you can plug in a completely different LoginModule by changing the configuration +and restarting the server, without any code changes to your application.
    • +
    + +
    Additional Notes
    +
      +
    • When a user attempts to access a protected resource for + the first time, Tomcat will call the authenticate() + method of this Realm. Thus, any changes you have made in + the security mechanism directly (new users, changed passwords or + roles, etc.) will be immediately reflected.
    • +
    • Once a user has been authenticated, the user (and his or + her associated roles) are cached within Tomcat for the duration of + the user's login. For FORM-based authentication, that means until + the session times out or is invalidated; for BASIC authentication, + that means until the user closes their browser. Any changes to the + security information for an already authenticated user will not + be reflected until the next time that user logs on again.
    • +
    • As with other Realm implementations, digested passwords + are supported if the <Realm> element in server.xml + contains a digest attribute; JAASRealm's CallbackHandler + will digest the password prior to passing it back to the LoginModule
    • +
    + +
    + + +

    CombinedRealm

    + +
    Introduction
    + +

    CombinedRealm is an implementation of the Tomcat + Realm interface that authenticates users through one or more + sub-Realms.

    + +

    Using CombinedRealm gives the developer the ability to combine multiple + Realms of the same or different types. This can be used to authenticate + against different sources, provide fall back in case one Realm fails or for + any other purpose that requires multiple Realms.

    + +

    Sub-realms are defined by nesting Realm elements inside the + Realm element that defines the CombinedRealm. Authentication + will be attempted against each Realm in the order they are + listed. Authentication against any Realm will be sufficient to authenticate + the user.

    + +
    Realm Element Attributes
    +

    To configure a CombinedRealm, you create a <Realm> + element and nest it in your $CATALINA_BASE/conf/server.xml + file within your <Engine> or <Host>. + You can also nest inside a <Context> node in a + context.xml file.

    + +
    Example
    + +

    Here is an example of how your server.xml snippet should look to use a +UserDatabase Realm and a DataSource Realm.

    + +
    <Realm className="org.apache.catalina.realm.CombinedRealm" >
    +   <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
    +             resourceName="UserDatabase"/>
    +   <Realm className="org.apache.catalina.realm.DataSourceRealm"
    +             dataSourceName="jdbc/authority"
    +             userTable="users" userNameCol="user_name" userCredCol="user_pass"
    +             userRoleTable="user_roles" roleNameCol="role_name"/>
    +</Realm>
    + +
    + +

    LockOutRealm

    + +
    Introduction
    + +

    LockOutRealm is an implementation of the Tomcat + Realm interface that extends the CombinedRealm to provide lock + out functionality to provide a user lock out mechanism if there are too many + failed authentication attempts in a given period of time.

    + +

    To ensure correct operation, there is a reasonable degree of + synchronisation in this Realm.

    + +

    This Realm does not require modification to the underlying Realms or the + associated user storage mechanisms. It achieves this by recording all failed + logins, including those for users that do not exist. To prevent a DOS by + deliberating making requests with invalid users (and hence causing this + cache to grow) the size of the list of users that have failed authentication + is limited.

    + +

    Sub-realms are defined by nesting Realm elements inside the + Realm element that defines the LockOutRealm. Authentication + will be attempted against each Realm in the order they are + listed. Authentication against any Realm will be sufficient to authenticate + the user.

    + +
    Realm Element Attributes
    +

    To configure a LockOutRealm, you create a <Realm> + element and nest it in your $CATALINA_BASE/conf/server.xml + file within your <Engine> or <Host>. + You can also nest inside a <Context> node in a + context.xml file. The attributes for the + LockOutRealm are defined in the Realm + configuration documentation.

    + +
    Example
    + +

    Here is an example of how your server.xml snippet should look to add lock out +functionality to a UserDatabase Realm.

    + +
    <Realm className="org.apache.catalina.realm.LockOutRealm" >
    +   <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
    +             resourceName="UserDatabase"/>
    +</Realm>
    + +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/rewrite.html b/tomcat/docs/rewrite.html new file mode 100644 index 0000000..12343ea --- /dev/null +++ b/tomcat/docs/rewrite.html @@ -0,0 +1,727 @@ + +Apache Tomcat 8 (8.5.43) - The rewrite Valve

    The rewrite Valve

    Introduction

    + +

    The rewrite valve implements URL rewrite functionality in a way that is + very similar to mod_rewrite from Apache HTTP Server.

    + +

    Configuration

    + +

    The rewrite valve is configured as a valve using the org.apache.catalina.valves.rewrite.RewriteValve + class name.

    + +

    The rewrite valve can be configured as a valve added in a Host. + See virtual-server documentation for + informations how to configure it. It will use a rewrite.config file + containing the rewrite directives, it must be placed in the Host configuration + folder. +

    + +

    It can also be in the context.xml of a webapp. + The valve will then use a rewrite.config file containing the + rewrite directives, it must be placed in the WEB-INF folder of the web application +

    + +

    Directives

    + +

    The rewrite.config file contains a list of directives which closely + resemble the directives used by mod_rewrite, in particular the central + RewriteRule and RewriteCond directives. Lines that start with a + # character are treated as comments and will be ignored.

    + +

    Note: This section is a modified version of the mod_rewrite documentation, + which is Copyright 1995-2006 The Apache Software Foundation, and licensed under the + under the Apache License, Version 2.0.

    + +

    RewriteCond

    + +

    Syntax: RewriteCond TestString CondPattern

    + +

    The RewriteCond directive defines a rule condition. One or more RewriteCond + can precede a RewriteRule directive. The following rule is then only used if both + the current state of the URI matches its pattern, and if these conditions are met.

    + +

    TestString is a string which can contain the + following expanded constructs in addition to plain text:

    + +
      +
    • + RewriteRule backreferences: These are + backreferences of the form $N + (0 <= N <= 9), which provide access to the grouped + parts (in parentheses) of the pattern, from the + RewriteRule which is subject to the current + set of RewriteCond conditions.. +
    • +
    • + RewriteCond backreferences: These are + backreferences of the form %N + (1 <= N <= 9), which provide access to the grouped + parts (again, in parentheses) of the pattern, from the last matched + RewriteCond in the current set + of conditions. +
    • +
    • + RewriteMap expansions: These are + expansions of the form ${mapname:key|default}. + See the documentation for + RewriteMap for more details. +
    • +
    • + Server-Variables: These are variables of + the form + %{ NAME_OF_VARIABLE + } + where NAME_OF_VARIABLE can be a string taken + from the following list: + +
        +
      • +

        HTTP headers:

        +

        + HTTP_USER_AGENT
        + HTTP_REFERER
        + HTTP_COOKIE
        + HTTP_FORWARDED
        + HTTP_HOST
        + HTTP_PROXY_CONNECTION
        + HTTP_ACCEPT
        +

        +
      • +
      • +

        connection & request:

        +

        + REMOTE_ADDR
        + REMOTE_HOST
        + REMOTE_PORT
        + REMOTE_USER
        + REMOTE_IDENT
        + REQUEST_METHOD
        + SCRIPT_FILENAME
        + REQUEST_PATH
        + CONTEXT_PATH
        + SERVLET_PATH
        + PATH_INFO
        + QUERY_STRING
        + AUTH_TYPE
        +

        +
      • +
      • +

        server internals:

        +

        + DOCUMENT_ROOT
        + SERVER_NAME
        + SERVER_ADDR
        + SERVER_PORT
        + SERVER_PROTOCOL
        + SERVER_SOFTWARE
        +

        +
      • +
      • +

        date and time:

        +

        + TIME_YEAR
        + TIME_MON
        + TIME_DAY
        + TIME_HOUR
        + TIME_MIN
        + TIME_SEC
        + TIME_WDAY
        + TIME
        +

        +
      • +
      • +

        specials:

        +

        + THE_REQUEST
        + REQUEST_URI
        + REQUEST_FILENAME
        + HTTPS
        +

        +
      • +
      + +

      These variables all + correspond to the similarly named HTTP + MIME-headers and Servlet API methods. + Most are documented elsewhere in the Manual or in + the CGI specification. Those that are special to + the rewrite valve include those below.

      + +
      + +
      REQUEST_PATH
      + +
      Corresponds to the full path that is used for mapping.
      + +
      CONTEXT_PATH
      + +
      Corresponds to the path of the mapped context.
      + +
      SERVLET_PATH
      + +
      Corresponds to the servlet path.
      + +
      THE_REQUEST
      + +
      The full HTTP request line sent by the + browser to the server (e.g., "GET + /index.html HTTP/1.1"). This does not + include any additional headers sent by the + browser.
      + +
      REQUEST_URI
      + +
      The resource requested in the HTTP request + line. (In the example above, this would be + "/index.html".)
      + +
      REQUEST_FILENAME
      + +
      The full local file system path to the file or + script matching the request.
      + +
      HTTPS
      + +
      Will contain the text "on" if the connection is + using SSL/TLS, or "off" otherwise.
      + +
      + +
    • +
    + +

    Other things you should be aware of:

    + +
      +
    1. The variables SCRIPT_FILENAME and REQUEST_FILENAME + contain the same value - the value of the + filename field of the internal + request_rec structure of the Apache server. + The first name is the commonly known CGI variable name + while the second is the appropriate counterpart of + REQUEST_URI (which contains the value of the + uri field of request_rec).
    2. + +
    3. + %{ENV:variable}, where variable can be + any Java system property, is also available.
    4. + +
    5. + %{SSL:variable}, where variable is the + name of an SSL environment + variable, are not implemented yet. Example: + %{SSL:SSL_CIPHER_USEKEYSIZE} may expand to + 128.
    6. + +
    7. + %{HTTP:header}, where header can be + any HTTP MIME-header name, can always be used to obtain the + value of a header sent in the HTTP request. + Example: %{HTTP:Proxy-Connection} is + the value of the HTTP header + ``Proxy-Connection:''.
    8. + +
    + +

    CondPattern is the condition pattern, + a regular expression which is applied to the + current instance of the TestString. + TestString is first evaluated, before being matched against + CondPattern.

    + +

    Remember: CondPattern is a + perl compatible regular expression with some + additions:

    + +
      +
    1. You can prefix the pattern string with a + '!' character (exclamation mark) to specify a + non-matching pattern.
    2. + +
    3. + There are some special variants of CondPatterns. + Instead of real regular expression strings you can also + use one of the following: + +
        +
      • '<CondPattern' (lexicographically + precedes)
        + Treats the CondPattern as a plain string and + compares it lexicographically to TestString. True if + TestString lexicographically precedes + CondPattern.
      • + +
      • '>CondPattern' (lexicographically + follows)
        + Treats the CondPattern as a plain string and + compares it lexicographically to TestString. True if + TestString lexicographically follows + CondPattern.
      • + +
      • '=CondPattern' (lexicographically + equal)
        + Treats the CondPattern as a plain string and + compares it lexicographically to TestString. True if + TestString is lexicographically equal to + CondPattern (the two strings are exactly + equal, character for character). If CondPattern + is "" (two quotation marks) this + compares TestString to the empty string.
      • + +
      • '-d' (is + directory)
        + Treats the TestString as a pathname and tests + whether or not it exists, and is a directory.
      • + +
      • '-f' (is regular + file)
        + Treats the TestString as a pathname and tests + whether or not it exists, and is a regular file.
      • + +
      • '-s' (is regular file, with + size)
        + Treats the TestString as a pathname and tests + whether or not it exists, and is a regular file with size greater + than zero.
      • + +
      + +Note: + All of these tests can + also be prefixed by an exclamation mark ('!') to + negate their meaning. + +
    4. + +
    5. You can also set special flags for + CondPattern by appending + [flags] + as the third argument to the RewriteCond + directive, where flags is a comma-separated list of any of the + following flags: + +
        +
      • 'nocase|NC' + (no case)
        + This makes the test case-insensitive - differences + between 'A-Z' and 'a-z' are ignored, both in the + expanded TestString and the CondPattern. + This flag is effective only for comparisons between + TestString and CondPattern. It has no + effect on file system and subrequest checks.
      • + +
      • + 'ornext|OR' + (or next condition)
        + Use this to combine rule conditions with a local OR + instead of the implicit AND. Typical example: + +
        RewriteCond %{REMOTE_HOST}  ^host1.*  [OR]
        +RewriteCond %{REMOTE_HOST}  ^host2.*  [OR]
        +RewriteCond %{REMOTE_HOST}  ^host3.*
        +RewriteRule ...some special stuff for any of these hosts...
        + + Without this flag you would have to write the condition/rule + pair three times. +
      • +
      +
    6. +
    + +

    Example:

    + +

    To rewrite the Homepage of a site according to the + ``User-Agent:'' header of the request, you can + use the following:

    + +
    RewriteCond  %{HTTP_USER_AGENT}  ^Mozilla.*
    +RewriteRule  ^/$                 /homepage.max.html  [L]
    +
    +RewriteCond  %{HTTP_USER_AGENT}  ^Lynx.*
    +RewriteRule  ^/$                 /homepage.min.html  [L]
    +
    +RewriteRule  ^/$                 /homepage.std.html  [L]
    + +

    Explanation: If you use a browser which identifies itself + as 'Mozilla' (including Netscape Navigator, Mozilla etc), then you + get the max homepage (which could include frames, or other special + features). + If you use the Lynx browser (which is terminal-based), then + you get the min homepage (which could be a version designed for + easy, text-only browsing). + If neither of these conditions apply (you use any other browser, + or your browser identifies itself as something non-standard), you get + the std (standard) homepage.

    + +
    + +

    RewriteMap

    + +

    Syntax: RewriteMap name rewriteMapClassName optionalParameters

    + +

    The maps are implemented using an interface that users must implement. Its class + name is org.apache.catalina.valves.rewrite.RewriteMap, and its code is:

    + +
    package org.apache.catalina.valves.rewrite;
    +
    +public interface RewriteMap {
    +    public String setParameters(String params);
    +    public String lookup(String key);
    +}
    + +
    + +

    RewriteRule

    + +

    Syntax: RewriteRule Pattern Substitution

    + +

    The RewriteRule directive is the real + rewriting workhorse. The directive can occur more than once, + with each instance defining a single rewrite rule. The + order in which these rules are defined is important - this is the order + in which they will be applied at run-time.

    + +

    Pattern is a perl compatible regular + expression, which is applied to the current URL. + ``Current'' means the value of the URL when this rule is + applied. This may not be the originally requested URL, + which may already have matched a previous rule, and have been + altered.

    + +

    Security warning: Due to the way Java's + regex matching is done, poorly formed regex patterns are vulnerable + to "catastrophic backtracking", also known as "regular expression + denial of service" or ReDoS. Therefore, extra caution should be used + for RewriteRule patterns. In general it is difficult to automatically + detect such vulnerable regex, and so a good defense is to read a bit + on the subject of catastrophic backtracking. A good reference is the + + OWASP ReDoS guide.

    + +

    Some hints on the syntax of regular + expressions:

    + + +
    +Text:
    +  .           Any single character
    +  [chars]     Character class: Any character of the class ``chars''
    +  [^chars]    Character class: Not a character of the class ``chars''
    +  text1|text2 Alternative: text1 or text2
    +
    +Quantifiers:
    +  ?           0 or 1 occurrences of the preceding text
    +  *           0 or N occurrences of the preceding text (N > 0)
    +  +           1 or N occurrences of the preceding text (N > 1)
    +
    +Grouping:
    +  (text)      Grouping of text
    +              (used either to set the borders of an alternative as above, or
    +              to make backreferences, where the Nth group can
    +              be referred to on the RHS of a RewriteRule as $N)
    +
    +Anchors:
    +  ^           Start-of-line anchor
    +  $           End-of-line anchor
    +
    +Escaping:
    +  \char       escape the given char
    +              (for instance, to specify the chars ".[]()" etc.)
    +
    + +

    For more information about regular expressions, have a look at the + perl regular expression manpage ("perldoc + perlre"). If you are interested in more detailed + information about regular expressions and their variants + (POSIX regex etc.) the following book is dedicated to this topic:

    + +

    + Mastering Regular Expressions, 2nd Edition
    + Jeffrey E.F. Friedl
    + O'Reilly & Associates, Inc. 2002
    + ISBN 978-0-596-00289-3
    +

    + +

    In the rules, the NOT character + ('!') is also available as a possible pattern + prefix. This enables you to negate a pattern; to say, for instance: + ``if the current URL does NOT match this + pattern''. This can be used for exceptional cases, where + it is easier to match the negative pattern, or as a last + default rule.

    + +

    +Note: When using the NOT character to negate a pattern, you cannot include +grouped wildcard parts in that pattern. This is because, when the +pattern does NOT match (i.e., the negation matches), there are no +contents for the groups. Thus, if negated patterns are used, you +cannot use $N in the substitution string! +

    + +

    The substitution of a + rewrite rule is the string which is substituted for (or + replaces) the original URL which Pattern + matched. In addition to plain text, it can include

    + +
      +
    1. back-references ($N) to the RewriteRule + pattern
    2. + +
    3. back-references (%N) to the last matched + RewriteCond pattern
    4. + +
    5. server-variables as in rule condition test-strings + (%{VARNAME})
    6. + +
    7. mapping-function calls + (${mapname:key|default})
    8. +
    +

    Back-references are identifiers of the form + $N + (N=0..9), which will be replaced + by the contents of the Nth group of the + matched Pattern. The server-variables are the same + as for the TestString of a RewriteCond + directive. The mapping-functions come from the + RewriteMap directive and are explained there. + These three types of variables are expanded in the order above.

    + +

    As already mentioned, all rewrite rules are + applied to the Substitution (in the order in which + they are defined + in the config file). The URL is completely + replaced by the Substitution and the + rewriting process continues until all rules have been applied, + or it is explicitly terminated by a + L flag.

    + +

    The special characters $ and % can + be quoted by prepending them with a backslash character + \.

    + +

    There is a special substitution string named + '-' which means: NO + substitution! This is useful in providing + rewriting rules which only match + URLs but do not substitute anything for them. It is commonly used + in conjunction with the C (chain) flag, in order + to apply more than one pattern before substitution occurs.

    + +

    Unlike newer mod_rewrite versions, the Tomcat rewrite valve does + not automatically support absolute URLs (the specific redirect flag + must be used to be able to specify an absolute URLs, see below) + or direct file serving.

    + +

    Additionally you can set special flags for Substitution by + appending [flags] + as the third argument to the RewriteRule + directive. Flags is a comma-separated list of any of the + following flags:

    + +
      +
    • 'chain|C' + (chained with next rule)
      + This flag chains the current rule with the next rule + (which itself can be chained with the following rule, + and so on). This has the following effect: if a rule + matches, then processing continues as usual - + the flag has no effect. If the rule does + not match, then all following chained + rules are skipped. For instance, it can be used to remove the + ``.www'' part, inside a per-directory rule set, + when you let an external redirect happen (where the + ``.www'' part should not occur!).
    • + +
    • + 'cookie|CO=NAME:VAL:domain[:lifetime[:path]]' + (set cookie)
      + This sets a cookie in the client's browser. The cookie's name + is specified by NAME and the value is + VAL. The domain field is the domain of the + cookie, such as '.apache.org', the optional lifetime + is the lifetime of the cookie in minutes, and the optional + path is the path of the cookie
    • + +
    • + 'env|E=VAR:VAL' + (set environment variable)
      + This forces a request attribute named VAR to + be set to the value VAL, where VAL can + contain regexp backreferences ($N and + %N) which will be expanded. You can use this + flag more than once, to set more than one variable.
    • + +
    • 'forbidden|F' (force URL + to be forbidden)
      + This forces the current URL to be forbidden - it immediately + sends back a HTTP response of 403 (FORBIDDEN). + Use this flag in conjunction with + appropriate RewriteConds to conditionally block some + URLs.
    • + +
    • 'gone|G' (force URL to be + gone)
      + This forces the current URL to be gone - it + immediately sends back a HTTP response of 410 (GONE). Use + this flag to mark pages which no longer exist as gone.
    • + +
    • + 'host|H=Host' + (apply rewriting to host)
      + Rather that rewrite the URL, the virtual host will be + rewritten.
    • + +
    • 'last|L' + (last rule)
      + Stop the rewriting process here and don't apply any more + rewrite rules. This corresponds to the Perl + last command or the break command + in C. Use this flag to prevent the currently + rewritten URL from being rewritten further by following + rules. For example, use it to rewrite the root-path URL + ('/') to a real one, e.g., + '/e/www/'.
    • + +
    • 'next|N' + (next round)
      + Re-run the rewriting process (starting again with the + first rewriting rule). This time, the URL to match is no longer + the original URL, but rather the URL returned by the last rewriting rule. + This corresponds to the Perl next command or + the continue command in C. Use + this flag to restart the rewriting process - + to immediately go to the top of the loop.
      + Be careful not to create an infinite + loop!
    • + +
    • 'nocase|NC' + (no case)
      + This makes the Pattern case-insensitive, + ignoring difference between 'A-Z' and + 'a-z' when Pattern is matched against the current + URL.
    • + +
    • + 'noescape|NE' + (no URI escaping of + output)
      + This flag prevents the rewrite valve from applying the usual URI + escaping rules to the result of a rewrite. Ordinarily, + special characters (such as '%', '$', ';', and so on) + will be escaped into their hexcode equivalents ('%25', + '%24', and '%3B', respectively); this flag prevents this + from happening. This allows percent symbols to appear in + the output, as in +
      RewriteRule /foo/(.*) /bar?arg=P1\%3d$1 [R,NE]
      + which would turn '/foo/zed' into a safe + request for '/bar?arg=P1=zed'. +
    • + + + +
    • 'qsappend|QSA' + (query string + append)
      + This flag forces the rewrite engine to append a query + string part of the substitution string to the existing string, + instead of replacing it. Use this when you want to add more + data to the query string via a rewrite rule.
    • + +
    • 'redirect|R + [=code]' (force + redirect)
      + Prefix Substitution with + http://thishost[:thisport]/ (which makes the + new URL a URI) to force a external redirection. If no + code is given, a HTTP response of 302 (FOUND, previously MOVED + TEMPORARILY) will be returned. If you want to use other response + codes in the range 300-399, simply specify the appropriate number + or use one of the following symbolic names: + temp (default), permanent, + seeother. Use this for rules to + canonicalize the URL and return it to the client - to + translate ``/~'' into + ``/u/'', or to always append a slash to + /u/user, etc.
      + Note: When you use this flag, make + sure that the substitution field is a valid URL! Otherwise, + you will be redirecting to an invalid location. Remember + that this flag on its own will only prepend + http://thishost[:thisport]/ to the URL, and rewriting + will continue. Usually, you will want to stop rewriting at this point, + and redirect immediately. To stop rewriting, you should add + the 'L' flag. +
    • + +
    • 'skip|S=num' + (skip next rule(s))
      + This flag forces the rewriting engine to skip the next + num rules in sequence, if the current rule + matches. Use this to make pseudo if-then-else constructs: + The last rule of the then-clause becomes + skip=N, where N is the number of rules in the + else-clause. (This is not the same as the + 'chain|C' flag!)
    • + +
    • + 'type|T=MIME-type' + (force MIME type)
      + Force the MIME-type of the target file to be + MIME-type. This can be used to + set up the content-type based on some conditions. + For example, the following snippet allows .php files to + be displayed by mod_php if they are called with + the .phps extension: +
      RewriteRule ^(.+\.php)s$ $1 [T=application/x-httpd-php-source]
      +
    • +
    + +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/security-howto.html b/tomcat/docs/security-howto.html new file mode 100644 index 0000000..20e34a0 --- /dev/null +++ b/tomcat/docs/security-howto.html @@ -0,0 +1,541 @@ + +Apache Tomcat 8 (8.5.43) - Security Considerations

    Security Considerations

    Table of Contents

    Introduction

    +

    Tomcat is configured to be reasonably secure for most use cases by + default. Some environments may require more, or less, secure configurations. + This page is to provide a single point of reference for configuration + options that may impact security and to offer some commentary on the + expected impact of changing those options. The intention is to provide a + list of configuration options that should be considered when assessing the + security of a Tomcat installation.

    + +

    Note: Reading this page is not a substitute for reading + and understanding the detailed configuration documentation. Fuller + descriptions of these attributes may be found in the relevant documentation + pages.

    +

    Non-Tomcat settings

    +

    Tomcat configuration should not be the only line of defense. The other + components in the system (operating system, network, database, etc.) should + also be secured.

    +

    Tomcat should not be run under the root user. Create a dedicated user for + the Tomcat process and provide that user with the minimum necessary + permissions for the operating system. For example, it should not be possible + to log on remotely using the Tomcat user.

    +

    File permissions should also be suitably restricted. In the + .tar.gz distribution, files and directories are not world + readable and the group does not have write access. On Unix like operating + systems, Tomcat runs with a default umask of 0027 to maintain + these permissions for files created while Tomcat is running (e.g. log files, + expanded WARs, etc.).

    +

    Taking the Tomcat instances at the ASF as an example (where + auto-deployment is disabled and web applications are deployed as exploded + directories), the standard configuration is to have all Tomcat files owned + by root with group Tomcat and whilst owner has read/write privileges, group + only has read and world has no permissions. The exceptions are the logs, + temp and work directory that are owned by the Tomcat user rather than root. + This means that even if an attacker compromises the Tomcat process, they + can't change the Tomcat configuration, deploy new web applications or + modify existing web applications. The Tomcat process runs with a umask of + 007 to maintain these permissions.

    +

    At the network level, consider using a firewall to limit both incoming + and outgoing connections to only those connections you expect to be + present.

    + +

    JMX

    +

    The security of the JMX connection is dependent on the implementation + provided by the JRE and therefore falls outside the control of Tomcat.

    + +

    Typically, access control is very limited (either read-only to + everything or read-write to everything). Tomcat exposes a large amount + of internal information and control via JMX to aid debugging, monitoring + and management. Given the limited access control available, JMX access + should be treated as equivalent to local root/admin access and restricted + accordingly.

    + +

    The JMX access control provided by most (all?) JRE vendors does not + log failed authentication attempts, nor does it provide an account + lock-out feature after repeated failed authentications. This makes a + brute force attack easy to mount and difficult to detect.

    + +

    Given all of the above, care should be taken to ensure that, if used, + the JMX interface is appropriately secured. Options you may wish to + consider to secure the JMX interface include:

    + +
      +
    • configuring a strong password for all JMX users;
    • +
    • binding the JMX listener only to an internal network;
    • +
    • limiting network access to the JMX port to trusted clients; and
    • +
    • providing an application specific health page for use by external + monitoring systems.
    • +
    +
    + +

    Default web applications

    + +

    General

    +

    Tomcat ships with a number of web applications that are enabled by + default. Vulnerabilities have been discovered in these applications in the + past. Applications that are not required should be removed so the system + will not be at risk if another vulnerability is discovered.

    +
    + +

    ROOT

    +

    The ROOT web application presents a very low security risk but it does + include the version of Tomcat that is being used. The ROOT web application + should normally be removed from a publicly accessible Tomcat instance, not + for security reasons, but so that a more appropriate default page is shown + to users.

    +
    + +

    Documentation

    +

    The documentation web application presents a very low security risk but + it does identify the version of Tomcat that is being used. It should + normally be removed from a publicly accessible Tomcat instance.

    +
    + +

    Examples

    +

    The examples web application should always be removed from any security + sensitive installation. While the examples web application does not + contain any known vulnerabilities, it is known to contain features + (particularly the cookie examples that display the contents of all + received and allow new cookies to be set) that may be used by an attacker + in conjunction with a vulnerability in another application deployed on the + Tomcat instance to obtain additional information that would otherwise be + unavailable.

    +
    + +

    Manager

    +

    The Manager application allows the remote deployment of web + applications and is frequently targeted by attackers due to the widespread + use of weak passwords and publicly accessible Tomcat instances with the + Manager application enabled. The Manager application is not accessible by + default as no users are configured with the necessary access. If the + Manager application is enabled then guidance in the section + Securing Management Applications section should be + followed.

    +
    + +

    Host Manager

    +

    The Host Manager application allows the creation and management of + virtual hosts - including the enabling of the Manager application for a + virtual host. The Host Manager application is not accessible by default + as no users are configured with the necessary access. If the Host Manager + application is enabled then guidance in the section Securing + Management Applications section should be followed.

    +
    + +

    Securing Management Applications

    +

    When deploying a web application that provides management functions for + the Tomcat instance, the following guidelines should be followed:

    +
      +
    • Ensure that any users permitted to access the management application + have strong passwords.
    • +
    • Do not remove the use of the LockOutRealm + which prevents brute force attacks against user passwords.
    • +
    • Configure the RemoteAddrValve + in the context.xml file for the + management application which limits access to localhost by default. + If remote access is required, limit it to specific IP addresses using + this valve.
    • +
    +
    +

    Security manager

    +

    Enabling the security manager causes web applications to be run in a + sandbox, significantly limiting a web application's ability to perform + malicious actions such as calling System.exit(), establishing network + connections or accessing the file system outside of the web application's + root and temporary directories. However, it should be noted that there are + some malicious actions, such as triggering high CPU consumption via an + infinite loop, that the security manager cannot prevent.

    + +

    Enabling the security manager is usually done to limit the potential + impact, should an attacker find a way to compromise a trusted web + application . A security manager may also be used to reduce the risks of + running untrusted web applications (e.g. in hosting environments) but it + should be noted that the security manager only reduces the risks of + running untrusted web applications, it does not eliminate them. If running + multiple untrusted web applications, it is recommended that each web + application is deployed to a separate Tomcat instance (and ideally separate + hosts) to reduce the ability of a malicious web application impacting the + availability of other applications.

    + +

    Tomcat is tested with the security manager enabled; but the majority of + Tomcat users do not run with a security manager, so Tomcat is not as well + user-tested in this configuration. There have been, and continue to be, + bugs reported that are triggered by running under a security manager.

    + +

    The restrictions imposed by a security manager are likely to break most + applications if the security manager is enabled. The security manager should + not be used without extensive testing. Ideally, the use of a security + manager should be introduced at the start of the development cycle as it can + be time-consuming to track down and fix issues caused by enabling a security + manager for a mature application.

    + +

    Enabling the security manager changes the defaults for the following + settings:

    +
      +
    • The default value for the deployXML attribute of the + Host element is changed to false.
    • +
    +

    server.xml

    +

    General

    +

    The default server.xml contains a large number of comments, including + some example component definitions that are commented out. Removing these + comments makes it considerably easier to read and comprehend + server.xml.

    +

    If a component type is not listed, then there are no settings for that + type that directly impact security.

    +
    + +

    Server

    +

    Setting the port attribute to -1 disables + the shutdown port.

    +

    If the shutdown port is not disabled, a strong password should be + configured for shutdown.

    +
    + +

    Listeners

    +

    The APR Lifecycle Listener is not stable if compiled on Solaris using + gcc. If using the APR/native connector on Solaris, compile it with the + Sun Studio compiler.

    +

    The JNI Library Loading Listener may be used to load native code. It should + only be used to load trusted libraries.

    +

    The Security Lifecycle Listener should be enabled and configured as appropriate. +

    +
    + +

    Connectors

    +

    By default, an HTTP and an AJP connector are configured. Connectors + that will not be used should be removed from server.xml.

    + +

    The address attribute may be used to control which IP + address the connector listens on for connections. By default, the + connector listens on all configured IP addresses.

    + +

    The allowTrace attribute may be used to enable TRACE + requests which can be useful for debugging. Due to the way some browsers + handle the response from a TRACE request (which exposes the browser to an + XSS attack), support for TRACE requests is disabled by default.

    + +

    The maxPostSize attribute controls the maximum size + of a POST request that will be parsed for parameters. The parameters are + cached for the duration of the request so this is limited to 2MB by + default to reduce exposure to a DOS attack.

    + +

    The maxSavePostSize attribute controls the saving of + POST requests during FORM and CLIENT-CERT authentication. The parameters + are cached for the duration of the authentication (which may be many + minutes) so this is limited to 4KB by default to reduce exposure to a DOS + attack.

    + +

    The maxParameterCount attribute controls the + maximum number of parameter and value pairs (GET plus POST) that can + be parsed and stored in the request. Excessive parameters are ignored. + If you want to reject such requests, configure a + FailedRequestFilter.

    + +

    The xpoweredBy attribute controls whether or not the + X-Powered-By HTTP header is sent with each request. If sent, the value of + the header contains the Servlet and JSP specification versions, the full + Tomcat version (e.g. Apache Tomcat/8.5), the name of + the JVM vendor and + the version of the JVM. This header is disabled by default. This header + can provide useful information to both legitimate clients and attackers. +

    + +

    The server attribute controls the value of the Server + HTTP header. The default value of this header for Tomcat 4.1.x to + 8.5.x is Apache-Coyote/1.1. This header can provide + limited information to both legitimate clients and attackers.

    + +

    The SSLEnabled, scheme and + secure attributes may all be independently set. These are + normally used when Tomcat is located behind a reverse proxy and the proxy + is connecting to Tomcat via HTTP or HTTPS. They allow Tomcat to see the + SSL attributes of the connections between the client and the proxy rather + than the proxy and Tomcat. For example, the client may connect to the + proxy over HTTPS but the proxy connects to Tomcat using HTTP. If it is + necessary for Tomcat to be able to distinguish between secure and + non-secure connections received by a proxy, the proxy must use separate + connectors to pass secure and non-secure requests to Tomcat. If the + proxy uses AJP then the SSL attributes of the client connection are + passed via the AJP protocol and separate connectors are not needed.

    + +

    The tomcatAuthentication and + tomcatAuthorization attributes are used with the + AJP connectors to determine if Tomcat should handle all authentication and + authorisation or if authentication should be delegated to the reverse + proxy (the authenticated user name is passed to Tomcat as part of the AJP + protocol) with the option for Tomcat to still perform authorization.

    + +

    The requiredSecret attribute in AJP connectors + configures shared secret between Tomcat and reverse proxy in front of + Tomcat. It is used to prevent unauthorized connections over AJP protocol.

    +
    + +

    Host

    +

    The host element controls deployment. Automatic deployment allows for + simpler management but also makes it easier for an attacker to deploy a + malicious application. Automatic deployment is controlled by the + autoDeploy and deployOnStartup + attributes. If both are false, only Contexts defined in + server.xml will be deployed and any changes will require a Tomcat restart. +

    + +

    In a hosted environment where web applications may not be trusted, set + the deployXML attribute to false to ignore + any context.xml packaged with the web application that may try to assign + increased privileges to the web application. Note that if the security + manager is enabled that the deployXML attribute will + default to false.

    +
    + +

    Context

    +

    This applies to Context + elements in all places where they can be defined: + server.xml file, + default context.xml file, + per-host context.xml.default file, + web application context file in per-host configuration directory + or inside the web application.

    + +

    The crossContext attribute controls if a context is + allowed to access the resources of another context. It is + false by default and should only be changed for trusted web + applications.

    + +

    The privileged attribute controls if a context is + allowed to use container provided servlets like the Manager servlet. It is + false by default and should only be changed for trusted web + applications.

    + +

    The allowLinking attribute of a nested + Resources element controls if a context + is allowed to use linked files. If enabled and the context is undeployed, + the links will be followed when deleting the context resources. Changing + this setting from the default of false on case insensitive + operating systems (this includes Windows) will disable a number of + security measures and allow, among other things, direct access to the + WEB-INF directory.

    + +

    The sessionCookiePathUsesTrailingSlash can be used to + work around a bug in a number of browsers (Internet Explorer, Safari and + Edge) to prevent session cookies being exposed across applications when + applications share a common path prefix. However, enabling this option + can create problems for applications with Servlets mapped to + /*. It should also be noted the RFC6265 section 8.5 makes it + clear that different paths should not be considered sufficient to isolate + cookies from other applications.

    +
    + +

    Valves

    +

    It is strongly recommended that an AccessLogValve is configured. The + default Tomcat configuration includes an AccessLogValve. These are + normally configured per host but may also be configured per engine or per + context as required.

    + +

    Any administrative application should be protected by a + RemoteAddrValve (this Valve is also available as a Filter). + The allow attribute should be used to limit access to a + set of known trusted hosts.

    + +

    The default ErrorReportValve includes the Tomcat version number in the + response sent to clients. To avoid this, custom error handling can be + configured within each web application. Alternatively, you can explicitly + configure an ErrorReportValve and set its + showServerInfo attribute to false. + Alternatively, the version number can be changed by creating the file + CATALINA_BASE/lib/org/apache/catalina/util/ServerInfo.properties with + content as follows:

    +
    server.info=Apache Tomcat/8.5.x
    +

    Modify the values as required. Note that this will also change the version + number reported in some of the management tools and may make it harder to + determine the real version installed. The CATALINA_HOME/bin/version.bat|sh + script will still report the correct version number.

    + +

    The default ErrorReportValve can display stack traces and/or JSP + source code to clients when an error occurs. To avoid this, custom error + handling can be configured within each web application. Alternatively, you + can explicitly configure an ErrorReportValve + and set its showReport attribute to false.

    + +

    The RewriteValve uses regular expressions and poorly formed regex + patterns may be vulnerable to "catastrophic backtracking" or "ReDoS". See + Rewrite docs for more details.

    +
    + +

    Realms

    +

    The MemoryRealm is not intended for production use as any changes to + tomcat-users.xml require a restart of Tomcat to take effect.

    + +

    The JDBCRealm is not recommended for production use as it is single + threaded for all authentication and authorization options. Use the + DataSourceRealm instead.

    + +

    The UserDatabaseRealm is not intended for large-scale installations. It + is intended for small-scale, relatively static environments.

    + +

    The JAASRealm is not widely used and therefore the code is not as + mature as the other realms. Additional testing is recommended before using + this realm.

    + +

    By default, the realms do not implement any form of account lock-out. + This means that brute force attacks can be successful. To prevent a brute + force attack, the chosen realm should be wrapped in a LockOutRealm.

    +
    + +

    Manager

    +

    The manager component is used to generate session IDs.

    + +

    The class used to generate random session IDs may be changed with + the randomClass attribute.

    + +

    The length of the session ID may be changed with the + sessionIdLength attribute.

    +
    + +

    Cluster

    +

    The cluster implementation is written on the basis that a secure, + trusted network is used for all of the cluster related network traffic. It + is not safe to run a cluster on a insecure, untrusted network.

    + +

    If you are operating on an untrusted network or would prefer to + exercise an over-abundance of caution, you can use the + EncryptInterceptor + to encrypt traffic between nodes.

    +
    +

    System Properties

    +

    Setting org.apache.catalina.connector.RECYCLE_FACADES + system property to true will cause a new facade object to be + created for each request. This reduces the chances of a bug in an + application exposing data from one request to another.

    + +

    The + org.apache.catalina.connector.CoyoteAdapter.ALLOW_BACKSLASH and + org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH + system properties allow non-standard parsing of the request URI. Using + these options when behind a reverse proxy may enable an attacker to bypass + any security constraints enforced by the proxy.

    + +

    The + org.apache.catalina.connector.Response.ENFORCE_ENCODING_IN_GET_WRITER + system property has security implications if disabled. Many user + agents, in breach of RFC2616, try to guess the character encoding of text + media types when the specification-mandated default of ISO-8859-1 should be + used. Some browsers will interpret as UTF-7 a response containing characters + that are safe for ISO-8859-1 but trigger an XSS vulnerability if interpreted + as UTF-7.

    +

    web.xml

    +

    This applies to the default conf/web.xml file and + WEB-INF/web.xml files in web applications if they define + the components mentioned here.

    + +

    The DefaultServlet is configured + with readonly set to + true. Changing this to false allows clients to + delete or modify static resources on the server and to upload new + resources. This should not normally be changed without requiring + authentication.

    + +

    The DefaultServlet is configured with listings set to + false. This isn't because allowing directory listings is + considered unsafe but because generating listings of directories with + thousands of files can consume significant CPU leading to a DOS attack. +

    + +

    The DefaultServlet is configured with showServerInfo + set to true. When the directory listings is enabled the Tomcat + version number is included in the response sent to clients. To avoid this, + you can explicitly configure a DefaultServlet and set its + showServerInfo attribute to false. + Alternatively, the version number can be changed by creating the file + CATALINA_BASE/lib/org/apache/catalina/util/ServerInfo.properties with + content as follows:

    +
    server.info=Apache Tomcat/8.5.x
    +

    Modify the values as required. Note that this will also change the version + number reported in some of the management tools and may make it harder to + determine the real version installed. The CATALINA_HOME/bin/version.bat|sh + script will still report the correct version number. +

    + +

    The CGI Servlet is disabled by default. If enabled, the debug + initialisation parameter should not be set to 10 or higher on a + production system because the debug page is not secure.

    + +

    When using the CGI Servlet on Windows with + enableCmdLineArguments enabled, review the setting of + cmdLineArgumentsDecoded carefully and ensure that it is + appropriate for your environment. The default value is secure. Insecure + configurations may expose the server to remote code execution. Further + information on the potential risks and mitigations may be found by + following the links in the CGI How To.

    + +

    FailedRequestFilter + can be configured and used to reject requests that had errors during + request parameter parsing. Without the filter the default behaviour is + to ignore invalid or excessive parameters.

    + +

    HttpHeaderSecurityFilter can be + used to add headers to responses to improve security. If clients access + Tomcat directly, then you probably want to enable this filter and all the + headers it sets unless your application is already setting them. If Tomcat + is accessed via a reverse proxy, then the configuration of this filter needs + to be co-ordinated with any headers that the reverse proxy sets.

    +

    General

    +

    BASIC and FORM authentication pass user names and passwords in clear + text. Web applications using these authentication mechanisms with clients + connecting over untrusted networks should use SSL.

    + +

    The session cookie for a session with an authenticated user are nearly + as useful as the user's password to an attacker and in nearly all + circumstances should be afforded the same level of protection as the + password itself. This usually means authenticating over SSL and continuing + to use SSL until the session ends.

    +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/security-manager-howto.html b/tomcat/docs/security-manager-howto.html new file mode 100644 index 0000000..9007927 --- /dev/null +++ b/tomcat/docs/security-manager-howto.html @@ -0,0 +1,517 @@ + +Apache Tomcat 8 (8.5.43) - Security Manager How-To

    Security Manager How-To

    Table of Contents

    Background

    + +

    The Java SecurityManager is what allows a web browser + to run an applet in its own sandbox to prevent untrusted code from + accessing files on the local file system, connecting to a host other + than the one the applet was loaded from, and so on. In the same way + the SecurityManager protects you from an untrusted applet running in + your browser, use of a SecurityManager while running Tomcat can protect + your server from trojan servlets, JSPs, JSP beans, and tag libraries. + Or even inadvertent mistakes.

    + +

    Imagine if someone who is authorized to publish JSPs on your site + inadvertently included the following in their JSP:

    +
    <% System.exit(1); %>
    + +

    Every time this JSP was executed by Tomcat, Tomcat would exit. + Using the Java SecurityManager is just one more line of defense a + system administrator can use to keep the server secure and reliable.

    + +

    WARNING - A security audit + have been conducted using the Tomcat codebase. Most of the critical + package have been protected and a new security package protection mechanism + has been implemented. Still, make sure that you are satisfied with your SecurityManager + configuration before allowing untrusted users to publish web applications, + JSPs, servlets, beans, or tag libraries. However, running with a + SecurityManager is definitely better than running without one.

    + +

    Permissions

    + +

    Permission classes are used to define what Permissions a class loaded + by Tomcat will have. There are a number of Permission classes that are + a standard part of the JDK, and you can create your own Permission class + for use in your own web applications. Both techniques are used in + Tomcat.

    + + +

    Standard Permissions

    + +

    This is just a short summary of the standard system SecurityManager + Permission classes applicable to Tomcat. See + + http://docs.oracle.com/javase/7/docs/technotes/guides/security/ + for more information.

    + +
      +
    • java.util.PropertyPermission - Controls read/write + access to JVM properties such as java.home.
    • +
    • java.lang.RuntimePermission - Controls use of + some System/Runtime functions like exit() and + exec(). Also control the package access/definition.
    • +
    • java.io.FilePermission - Controls read/write/execute + access to files and directories.
    • +
    • java.net.SocketPermission - Controls use of + network sockets.
    • +
    • java.net.NetPermission - Controls use of + multicast network connections.
    • +
    • java.lang.reflect.ReflectPermission - Controls + use of reflection to do class introspection.
    • +
    • java.security.SecurityPermission - Controls access + to Security methods.
    • +
    • java.security.AllPermission - Allows access to all + permissions, just as if you were running Tomcat without a + SecurityManager.
    • +
    + +
    + +

    Configuring Tomcat With A SecurityManager

    + +

    Policy File Format

    + +

    The security policies implemented by the Java SecurityManager are + configured in the $CATALINA_BASE/conf/catalina.policy file. + This file completely replaces the java.policy file present + in your JDK system directories. The catalina.policy file + can be edited by hand, or you can use the + policytool + application that comes with Java 1.2 or later.

    + +

    Entries in the catalina.policy file use the standard + java.policy file format, as follows:

    +
    // Example policy file entry
    +
    +grant [signedBy <signer>,] [codeBase <code source>] {
    +  permission  <class>  [<name> [, <action list>]];
    +};
    + +

    The signedBy and codeBase entries are + optional when granting permissions. Comment lines begin with "//" and + end at the end of the current line. The codeBase is in the + form of a URL, and for a file URL can use the ${java.home} + and ${catalina.home} properties (which are expanded out to + the directory paths defined for them by the JAVA_HOME, + CATALINA_HOME and CATALINA_BASE environment + variables).

    + +

    The Default Policy File

    + +

    The default $CATALINA_BASE/conf/catalina.policy file + looks like this:

    + + +
    // 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.
    +
    +// ============================================================================
    +// catalina.policy - Security Policy Permissions for Tomcat
    +//
    +// This file contains a default set of security policies to be enforced (by the
    +// JVM) when Catalina is executed with the "-security" option.  In addition
    +// to the permissions granted here, the following additional permissions are
    +// granted to each web application:
    +//
    +// * Read access to the web application's document root directory
    +// * Read, write and delete access to the web application's working directory
    +// ============================================================================
    +
    +
    +// ========== SYSTEM CODE PERMISSIONS =========================================
    +
    +
    +// These permissions apply to javac
    +grant codeBase "file:${java.home}/lib/-" {
    +        permission java.security.AllPermission;
    +};
    +
    +// These permissions apply to all shared system extensions
    +grant codeBase "file:${java.home}/jre/lib/ext/-" {
    +        permission java.security.AllPermission;
    +};
    +
    +// These permissions apply to javac when ${java.home] points at $JAVA_HOME/jre
    +grant codeBase "file:${java.home}/../lib/-" {
    +        permission java.security.AllPermission;
    +};
    +
    +// These permissions apply to all shared system extensions when
    +// ${java.home} points at $JAVA_HOME/jre
    +grant codeBase "file:${java.home}/lib/ext/-" {
    +        permission java.security.AllPermission;
    +};
    +
    +
    +// ========== CATALINA CODE PERMISSIONS =======================================
    +
    +
    +// These permissions apply to the daemon code
    +grant codeBase "file:${catalina.home}/bin/commons-daemon.jar" {
    +        permission java.security.AllPermission;
    +};
    +
    +// These permissions apply to the logging API
    +// Note: If tomcat-juli.jar is in ${catalina.base} and not in ${catalina.home},
    +// update this section accordingly.
    +//  grant codeBase "file:${catalina.base}/bin/tomcat-juli.jar" {..}
    +grant codeBase "file:${catalina.home}/bin/tomcat-juli.jar" {
    +        permission java.io.FilePermission
    +         "${java.home}${file.separator}lib${file.separator}logging.properties", "read";
    +
    +        permission java.io.FilePermission
    +         "${catalina.base}${file.separator}conf${file.separator}logging.properties", "read";
    +        permission java.io.FilePermission
    +         "${catalina.base}${file.separator}logs", "read, write";
    +        permission java.io.FilePermission
    +         "${catalina.base}${file.separator}logs${file.separator}*", "read, write, delete";
    +
    +        permission java.lang.RuntimePermission "shutdownHooks";
    +        permission java.lang.RuntimePermission "getClassLoader";
    +        permission java.lang.RuntimePermission "setContextClassLoader";
    +
    +        permission java.lang.management.ManagementPermission "monitor";
    +
    +        permission java.util.logging.LoggingPermission "control";
    +
    +        permission java.util.PropertyPermission "java.util.logging.config.class", "read";
    +        permission java.util.PropertyPermission "java.util.logging.config.file", "read";
    +        permission java.util.PropertyPermission "org.apache.juli.AsyncLoggerPollInterval", "read";
    +        permission java.util.PropertyPermission "org.apache.juli.AsyncMaxRecordCount", "read";
    +        permission java.util.PropertyPermission "org.apache.juli.AsyncOverflowDropType", "read";
    +        permission java.util.PropertyPermission "org.apache.juli.ClassLoaderLogManager.debug", "read";
    +        permission java.util.PropertyPermission "catalina.base", "read";
    +
    +        // Note: To enable per context logging configuration, permit read access to
    +        // the appropriate file. Be sure that the logging configuration is
    +        // secure before enabling such access.
    +        // E.g. for the examples web application (uncomment and unwrap
    +        // the following to be on a single line):
    +        // permission java.io.FilePermission "${catalina.base}${file.separator}
    +        //  webapps${file.separator}examples${file.separator}WEB-INF
    +        //  ${file.separator}classes${file.separator}logging.properties", "read";
    +};
    +
    +// These permissions apply to the server startup code
    +grant codeBase "file:${catalina.home}/bin/bootstrap.jar" {
    +        permission java.security.AllPermission;
    +};
    +
    +// These permissions apply to the servlet API classes
    +// and those that are shared across all class loaders
    +// located in the "lib" directory
    +grant codeBase "file:${catalina.home}/lib/-" {
    +        permission java.security.AllPermission;
    +};
    +
    +
    +// If using a per instance lib directory, i.e. ${catalina.base}/lib,
    +// then the following permission will need to be uncommented
    +// grant codeBase "file:${catalina.base}/lib/-" {
    +//         permission java.security.AllPermission;
    +// };
    +
    +
    +// ========== WEB APPLICATION PERMISSIONS =====================================
    +
    +
    +// These permissions are granted by default to all web applications
    +// In addition, a web application will be given a read FilePermission
    +// for all files and directories in its document root.
    +grant {
    +    // Required for JNDI lookup of named JDBC DataSource's and
    +    // javamail named MimePart DataSource used to send mail
    +    permission java.util.PropertyPermission "java.home", "read";
    +    permission java.util.PropertyPermission "java.naming.*", "read";
    +    permission java.util.PropertyPermission "javax.sql.*", "read";
    +
    +    // OS Specific properties to allow read access
    +    permission java.util.PropertyPermission "os.name", "read";
    +    permission java.util.PropertyPermission "os.version", "read";
    +    permission java.util.PropertyPermission "os.arch", "read";
    +    permission java.util.PropertyPermission "file.separator", "read";
    +    permission java.util.PropertyPermission "path.separator", "read";
    +    permission java.util.PropertyPermission "line.separator", "read";
    +
    +    // JVM properties to allow read access
    +    permission java.util.PropertyPermission "java.version", "read";
    +    permission java.util.PropertyPermission "java.vendor", "read";
    +    permission java.util.PropertyPermission "java.vendor.url", "read";
    +    permission java.util.PropertyPermission "java.class.version", "read";
    +    permission java.util.PropertyPermission "java.specification.version", "read";
    +    permission java.util.PropertyPermission "java.specification.vendor", "read";
    +    permission java.util.PropertyPermission "java.specification.name", "read";
    +
    +    permission java.util.PropertyPermission "java.vm.specification.version", "read";
    +    permission java.util.PropertyPermission "java.vm.specification.vendor", "read";
    +    permission java.util.PropertyPermission "java.vm.specification.name", "read";
    +    permission java.util.PropertyPermission "java.vm.version", "read";
    +    permission java.util.PropertyPermission "java.vm.vendor", "read";
    +    permission java.util.PropertyPermission "java.vm.name", "read";
    +
    +    // Required for OpenJMX
    +    permission java.lang.RuntimePermission "getAttribute";
    +
    +    // Allow read of JAXP compliant XML parser debug
    +    permission java.util.PropertyPermission "jaxp.debug", "read";
    +
    +    // All JSPs need to be able to read this package
    +    permission java.lang.RuntimePermission "accessClassInPackage.org.apache.tomcat";
    +
    +    // Precompiled JSPs need access to these packages.
    +    permission java.lang.RuntimePermission "accessClassInPackage.org.apache.jasper.el";
    +    permission java.lang.RuntimePermission "accessClassInPackage.org.apache.jasper.runtime";
    +    permission java.lang.RuntimePermission
    +     "accessClassInPackage.org.apache.jasper.runtime.*";
    +
    +    // The cookie code needs these.
    +    permission java.util.PropertyPermission
    +     "org.apache.catalina.STRICT_SERVLET_COMPLIANCE", "read";
    +    permission java.util.PropertyPermission
    +     "org.apache.tomcat.util.http.ServerCookie.STRICT_NAMING", "read";
    +    permission java.util.PropertyPermission
    +     "org.apache.tomcat.util.http.ServerCookie.FWD_SLASH_IS_SEPARATOR", "read";
    +
    +    // Applications using WebSocket need to be able to access these packages
    +    permission java.lang.RuntimePermission "accessClassInPackage.org.apache.tomcat.websocket";
    +    permission java.lang.RuntimePermission "accessClassInPackage.org.apache.tomcat.websocket.server";
    +
    +    // Applications need to access these packages to use the Servlet 4.0 Preview
    +    permission java.lang.RuntimePermission "accessClassInPackage.org.apache.catalina.servlet4preview";
    +    permission java.lang.RuntimePermission "accessClassInPackage.org.apache.catalina.servlet4preview.http";
    +};
    +
    +
    +// The Manager application needs access to the following packages to support the
    +// session display functionality. It also requires the custom Tomcat
    +// DeployXmlPermission to enable the use of META-INF/context.xml
    +// These settings support the following configurations:
    +// - default CATALINA_HOME == CATALINA_BASE
    +// - CATALINA_HOME != CATALINA_BASE, per instance Manager in CATALINA_BASE
    +// - CATALINA_HOME != CATALINA_BASE, shared Manager in CATALINA_HOME
    +grant codeBase "file:${catalina.base}/webapps/manager/-" {
    +    permission java.lang.RuntimePermission "accessClassInPackage.org.apache.catalina";
    +    permission java.lang.RuntimePermission "accessClassInPackage.org.apache.catalina.ha.session";
    +    permission java.lang.RuntimePermission "accessClassInPackage.org.apache.catalina.manager";
    +    permission java.lang.RuntimePermission "accessClassInPackage.org.apache.catalina.manager.util";
    +    permission java.lang.RuntimePermission "accessClassInPackage.org.apache.catalina.util";
    +    permission org.apache.catalina.security.DeployXmlPermission "manager";
    +};
    +grant codeBase "file:${catalina.home}/webapps/manager/-" {
    +    permission java.lang.RuntimePermission "accessClassInPackage.org.apache.catalina";
    +    permission java.lang.RuntimePermission "accessClassInPackage.org.apache.catalina.ha.session";
    +    permission java.lang.RuntimePermission "accessClassInPackage.org.apache.catalina.manager";
    +    permission java.lang.RuntimePermission "accessClassInPackage.org.apache.catalina.manager.util";
    +    permission java.lang.RuntimePermission "accessClassInPackage.org.apache.catalina.util";
    +    permission org.apache.catalina.security.DeployXmlPermission "manager";
    +};
    +
    +// The Host Manager application needs the custom Tomcat DeployXmlPermission to
    +// enable the use of META-INF/context.xml
    +// These settings support the following configurations:
    +// - default CATALINA_HOME == CATALINA_BASE
    +// - CATALINA_HOME != CATALINA_BASE, per instance Host Manager in CATALINA_BASE
    +// - CATALINA_HOME != CATALINA_BASE, shared Host Manager in CATALINA_HOME
    +grant codeBase "file:${catalina.base}/webapps/host-manager/-" {
    +    permission org.apache.catalina.security.DeployXmlPermission "host-manager";
    +};
    +grant codeBase "file:${catalina.home}/webapps/host-manager/-" {
    +    permission org.apache.catalina.security.DeployXmlPermission "host-manager";
    +};
    +
    +
    +// You can assign additional permissions to particular web applications by
    +// adding additional "grant" entries here, based on the code base for that
    +// application, /WEB-INF/classes/, or /WEB-INF/lib/ jar files.
    +//
    +// Different permissions can be granted to JSP pages, classes loaded from
    +// the /WEB-INF/classes/ directory, all jar files in the /WEB-INF/lib/
    +// directory, or even to individual jar files in the /WEB-INF/lib/ directory.
    +//
    +// For instance, assume that the standard "examples" application
    +// included a JDBC driver that needed to establish a network connection to the
    +// corresponding database and used the scrape taglib to get the weather from
    +// the NOAA web server.  You might create a "grant" entries like this:
    +//
    +// The permissions granted to the context root directory apply to JSP pages.
    +// grant codeBase "file:${catalina.base}/webapps/examples/-" {
    +//      permission java.net.SocketPermission "dbhost.mycompany.com:5432", "connect";
    +//      permission java.net.SocketPermission "*.noaa.gov:80", "connect";
    +// };
    +//
    +// The permissions granted to the context WEB-INF/classes directory
    +// grant codeBase "file:${catalina.base}/webapps/examples/WEB-INF/classes/-" {
    +// };
    +//
    +// The permission granted to your JDBC driver
    +// grant codeBase "jar:file:${catalina.base}/webapps/examples/WEB-INF/lib/driver.jar!/-" {
    +//      permission java.net.SocketPermission "dbhost.mycompany.com:5432", "connect";
    +// };
    +// The permission granted to the scrape taglib
    +// grant codeBase "jar:file:${catalina.base}/webapps/examples/WEB-INF/lib/scrape.jar!/-" {
    +//      permission java.net.SocketPermission "*.noaa.gov:80", "connect";
    +// };
    +
    +// To grant permissions for web applications using packed WAR files, use the
    +// Tomcat specific WAR url scheme.
    +//
    +// The permissions granted to the entire web application
    +// grant codeBase "war:file:${catalina.base}/webapps/examples.war*/-" {
    +// };
    +//
    +// The permissions granted to a specific JAR
    +// grant codeBase "war:file:${catalina.base}/webapps/examples.war*/WEB-INF/lib/foo.jar" {
    +// };
    + +

    Starting Tomcat With A SecurityManager

    + +

    Once you have configured the catalina.policy file for use + with a SecurityManager, Tomcat can be started with a SecurityManager in + place by using the "-security" option:

    +
    $CATALINA_HOME/bin/catalina.sh start -security    (Unix)
    +%CATALINA_HOME%\bin\catalina start -security      (Windows)
    + +

    Permissions for packed WAR files

    + +

    When using packed WAR files, it is necessary to use Tomcat's custom war + URL protocol to assign permissions to web application code.

    + +

    To assign permissions to the entire web application the entry in the + policy file would look like this:

    + +
    // Example policy file entry
    +grant codeBase "war:file:${catalina.base}/webapps/examples.war*/-" {
    +    ...
    +};
    +
    + +

    To assign permissions to a single JAR within the web application the + entry in the policy file would look like this:

    + +
    // Example policy file entry
    +grant codeBase "war:file:${catalina.base}/webapps/examples.war*/WEB-INF/lib/foo.jar" {
    +    ...
    +};
    +
    + +
    + +

    Configuring Package Protection in Tomcat

    +

    Starting with Tomcat 5, it is now possible to configure which Tomcat + internal package are protected against package definition and access. See + + http://www.oracle.com/technetwork/java/seccodeguide-139067.html + for more information.

    + + +

    WARNING: Be aware that removing the default package protection + could possibly open a security hole

    + +

    The Default Properties File

    + +

    The default $CATALINA_BASE/conf/catalina.properties file + looks like this:

    +
    #
    +# List of comma-separated packages that start with or equal this string
    +# will cause a security exception to be thrown when
    +# passed to checkPackageAccess unless the
    +# corresponding RuntimePermission ("accessClassInPackage."+package) has
    +# been granted.
    +package.access=sun.,org.apache.catalina.,org.apache.coyote.,org.apache.tomcat.,
    +org.apache.jasper.
    +#
    +# List of comma-separated packages that start with or equal this string
    +# will cause a security exception to be thrown when
    +# passed to checkPackageDefinition unless the
    +# corresponding RuntimePermission ("defineClassInPackage."+package) has
    +# been granted.
    +#
    +# by default, no packages are restricted for definition, and none of
    +# the class loaders supplied with the JDK call checkPackageDefinition.
    +#
    +package.definition=sun.,java.,org.apache.catalina.,org.apache.coyote.,
    +org.apache.tomcat.,org.apache.jasper.
    +

    Once you have configured the catalina.properties file for use + with a SecurityManager, remember to re-start Tomcat.

    +

    Troubleshooting

    + +

    If your web application attempts to execute an operation that is + prohibited by lack of a required Permission, it will throw an + AccessControLException or a SecurityException + when the SecurityManager detects the violation. Debugging the permission + that is missing can be challenging, and one option is to turn on debug + output of all security decisions that are made during execution. This + is done by setting a system property before starting Tomcat. The easiest + way to do this is via the CATALINA_OPTS environment variable. + Execute this command:

    +
    export CATALINA_OPTS=-Djava.security.debug=all    (Unix)
    +set CATALINA_OPTS=-Djava.security.debug=all       (Windows)
    + +

    before starting Tomcat.

    + +

    WARNING - This will generate many megabytes + of output! However, it can help you track down problems by searching + for the word "FAILED" and determining which permission was being checked + for. See the Java security documentation for more options that you can + specify here as well.

    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/servletapi/index.html b/tomcat/docs/servletapi/index.html new file mode 100644 index 0000000..e1c5695 --- /dev/null +++ b/tomcat/docs/servletapi/index.html @@ -0,0 +1,34 @@ + + + + + + API docs + + + + +The Servlet Javadoc is not installed by default. Download and install +the "fulldocs" package to get it. + +You can also access the javadoc online in the Tomcat + +documentation bundle. + + + diff --git a/tomcat/docs/setup.html b/tomcat/docs/setup.html new file mode 100644 index 0000000..929d9df --- /dev/null +++ b/tomcat/docs/setup.html @@ -0,0 +1,202 @@ + +Apache Tomcat 8 (8.5.43) - Tomcat Setup

    Tomcat Setup

    Table of Contents

    Introduction

    +

    + There are several ways to set up Tomcat for running on different + platforms. The main documentation for this is a file called + RUNNING.txt. We encourage you to refer to that + file if the information below does not answer some of your questions. +

    +

    Windows

    + +

    + Installing Tomcat on Windows can be done easily using the Windows + installer. Its interface and functionality is similar to other wizard + based installers, with only a few items of interest. +

    + + +
      +
    • Installation as a service: Tomcat will be + installed as a Windows service no matter what setting is selected. + Using the checkbox on the component page sets the service as "auto" + startup, so that Tomcat is automatically started when Windows + starts. For optimal security, the service should be run as a + separate user, with reduced permissions (see the Windows Services + administration tool and its documentation).
    • +
    • Java location: The installer will provide a default + JRE to use to run the service. The installer uses the registry to + determine the base path of a Java 7 or later JRE, including the JRE + installed as part of the full JDK. When running on a 64-bit + operating system, the installer will first look for a 64-bit JRE and + only look for a 32-bit JRE if a 64-bit JRE is not found. It is not + mandatory to use the default JRE detected by the installer. Any + installed Java 7 or later JRE (32-bit or 64-bit) may be used.
    • +
    • Tray icon: When Tomcat is run as a service, there + will not be any tray icon present when Tomcat is running. Note that + when choosing to run Tomcat at the end of installation, the tray + icon will be used even if Tomcat was installed as a service.
    • +
    • Defaults: The defaults used by the installer may be + overridden by use of the /C=<config file> command + line argument. The configuration file uses the format + name=value with each pair on a separate line. The names + of the available configuration options are: +
        +
      • JavaHome
      • +
      • TomcatPortShutdown
      • +
      • TomcatPortHttp
      • +
      • TomcatPortAjp
      • +
      • TomcatMenuEntriesEnable
      • +
      • TomcatShortcutAllUsers
      • +
      • TomcatServiceDefaultName
      • +
      • TomcatServiceName
      • +
      • TomcatServiceFileName
      • +
      • TomcatServiceManagerFileName
      • +
      • TomcatAdminEnable
      • +
      • TomcatAdminUsername
      • +
      • TomcatAdminPassword
      • +
      • TomcatAdminRoles
      • +
      + By using /C=... along with /S and + /D= it is possible to perform fully configured + unattended installs of Apache Tomcat. +
    • +
    • Refer to the + Windows Service How-To + for information on how to manage Tomcat as a Windows service. +
    • +
    + + +

    The installer will create shortcuts allowing starting and configuring + Tomcat. It is important to note that the Tomcat administration web + application can only be used when Tomcat is running.

    + +

    Unix daemon

    + +

    Tomcat can be run as a daemon using the jsvc tool from the + commons-daemon project. Source tarballs for jsvc are included with the + Tomcat binaries, and need to be compiled. Building jsvc requires + a C ANSI compiler (such as GCC), GNU Autoconf, and a JDK.

    + +

    Before running the script, the JAVA_HOME environment + variable should be set to the base path of the JDK. Alternately, when + calling the ./configure script, the path of the JDK may + be specified using the --with-java parameter, such as + ./configure --with-java=/usr/java.

    + +

    Using the following commands should result in a compiled jsvc binary, + located in the $CATALINA_HOME/bin folder. This assumes + that GNU TAR is used, and that CATALINA_HOME is an + environment variable pointing to the base path of the Tomcat + installation.

    + +

    Please note that you should use the GNU make (gmake) instead of + the native BSD make on FreeBSD systems.

    + +
    cd $CATALINA_HOME/bin
    +tar xvfz commons-daemon-native.tar.gz
    +cd commons-daemon-1.1.x-native-src/unix
    +./configure
    +make
    +cp jsvc ../..
    +cd ../..
    + +

    Tomcat can then be run as a daemon using the following commands.

    + +
    CATALINA_BASE=$CATALINA_HOME
    +cd $CATALINA_HOME
    +./bin/jsvc \
    +    -classpath $CATALINA_HOME/bin/bootstrap.jar:$CATALINA_HOME/bin/tomcat-juli.jar \
    +    -outfile $CATALINA_BASE/logs/catalina.out \
    +    -errfile $CATALINA_BASE/logs/catalina.err \
    +    -Dcatalina.home=$CATALINA_HOME \
    +    -Dcatalina.base=$CATALINA_BASE \
    +    -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager \
    +    -Djava.util.logging.config.file=$CATALINA_BASE/conf/logging.properties \
    +    org.apache.catalina.startup.Bootstrap
    + +

    When running on Java 9 you will need to additionally specify the + following when starting jsvc to avoid warnings on shutdown.

    +
    ...
    +--add-opens=java.base/java.lang=ALL-UNNAMED \
    +--add-opens=java.base/java.io=ALL-UNNAMED \
    +--add-opens=java.rmi/sun.rmi.transport=ALL-UNNAMED \
    +...
    +
    + +

    You may also need to specify -jvm server if the JVM defaults + to using a server VM rather than a client VM. This has been observed on + OSX.

    + +

    jsvc has other useful parameters, such as -user which + causes it to switch to another user after the daemon initialization is + complete. This allows, for example, running Tomcat as a non privileged + user while still being able to use privileged ports. Note that if you + use this option and start Tomcat as root, you'll need to disable the + org.apache.catalina.security.SecurityListener check that + prevents Tomcat starting when running as root.

    + +

    jsvc --help will return the full jsvc usage + information. In particular, the -debug option is useful + to debug issues running jsvc.

    + +

    The file $CATALINA_HOME/bin/daemon.sh can be used as a + template for starting Tomcat automatically at boot time from + /etc/init.d with jsvc.

    + +

    Note that the Commons-Daemon JAR file must be on your runtime classpath + to run Tomcat in this manner. The Commons-Daemon JAR file is in the + Class-Path entry of the bootstrap.jar manifest, but if you get a + ClassNotFoundException or a NoClassDefFoundError for a Commons-Daemon + class, add the Commons-Daemon JAR to the -cp argument when launching + jsvc.

    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/ssi-howto.html b/tomcat/docs/ssi-howto.html new file mode 100644 index 0000000..77af900 --- /dev/null +++ b/tomcat/docs/ssi-howto.html @@ -0,0 +1,440 @@ + +Apache Tomcat 8 (8.5.43) - SSI How To

    SSI How To

    Table of Contents

    Introduction

    + +

    SSI (Server Side Includes) are directives that are placed in HTML pages, +and evaluated on the server while the pages are being served. They let you +add dynamically generated content to an existing HTML page, without having +to serve the entire page via a CGI program, or other dynamic technology. +

    + +

    Within Tomcat SSI support can be added when using Tomcat as your +HTTP server and you require SSI support. Typically this is done +during development when you don't want to run a web server like Apache.

    + +

    Tomcat SSI support implements the same SSI directives as Apache. See the + +Apache Introduction to SSI for information on using SSI directives.

    + +

    SSI support is available as a servlet and as a filter. You should use one +or the other to provide SSI support but not both.

    + +

    Servlet based SSI support is implemented using the class +org.apache.catalina.ssi.SSIServlet. Traditionally, this servlet +is mapped to the URL pattern "*.shtml".

    + +

    Filter based SSI support is implemented using the class +org.apache.catalina.ssi.SSIFilter. Traditionally, this filter +is mapped to the URL pattern "*.shtml", though it can be mapped to "*" as +it will selectively enable/disable SSI processing based on mime types. The +contentType init param allows you to apply SSI processing to JSP pages, +javascript, or any other content you wish.

    +

    By default SSI support is disabled in Tomcat.

    +

    Installation

    + +

    CAUTION - SSI directives can be used to execute programs +external to the Tomcat JVM. If you are using the Java SecurityManager this +will bypass your security policy configuration in catalina.policy. +

    + +

    To use the SSI servlet, remove the XML comments from around the SSI servlet +and servlet-mapping configuration in +$CATALINA_BASE/conf/web.xml.

    + +

    To use the SSI filter, remove the XML comments from around the SSI filter +and filter-mapping configuration in +$CATALINA_BASE/conf/web.xml.

    + +

    Only Contexts which are marked as privileged may use SSI features (see the +privileged property of the Context element).

    + +

    Servlet Configuration

    + +

    There are several servlet init parameters which can be used to +configure the behaviour of the SSI servlet.

    +
      +
    • buffered - Should output from this servlet be buffered? +(0=false, 1=true) Default 0 (false).
    • +
    • debug - Debugging detail level for messages logged +by this servlet. Default 0.
    • +
    • expires - The number of seconds before a page with SSI +directives will expire. Default behaviour is for all SSI directives to be +evaluated for every request.
    • +
    • isVirtualWebappRelative - Should "virtual" SSI directive +paths be interpreted as relative to the context root, instead of the server +root? Default false.
    • +
    • inputEncoding - The encoding to be assumed for SSI +resources if one cannot be determined from the resource itself. Default is +the default platform encoding.
    • +
    • outputEncoding - The encoding to be used for the result +of the SSI processing. Default is UTF-8.
    • +
    • allowExec - Is the exec command enabled? Default is +false.
    • +
    + + +

    Filter Configuration

    + +

    There are several filter init parameters which can be used to +configure the behaviour of the SSI filter.

    +
      +
    • contentType - A regex pattern that must be matched before +SSI processing is applied. When crafting your own pattern, don't forget that a +mime content type may be followed by an optional character set in the form +"mime/type; charset=set" that you must take into account. Default is +"text/x-server-parsed-html(;.*)?".
    • +
    • debug - Debugging detail level for messages logged +by this servlet. Default 0.
    • +
    • expires - The number of seconds before a page with SSI +directives will expire. Default behaviour is for all SSI directives to be +evaluated for every request.
    • +
    • isVirtualWebappRelative - Should "virtual" SSI directive +paths be interpreted as relative to the context root, instead of the server +root? Default false.
    • +
    • allowExec - Is the exec command enabled? Default is +false.
    • +
    + + +

    Directives

    +

    Server Side Includes are invoked by embedding SSI directives in an HTML document + whose type will be processed by the SSI servlet. The directives take the form of an HTML + comment. The directive is replaced by the results of interpreting it before sending the + page to the client. The general form of a directive is:

    +

    <!--#directive [parm=value] -->

    +

    The directives are:

    +
      +
    • +config - <!--#config errmsg="Error occured" sizefmt="abbrev" +timefmt="%B %Y" --> +Used to set SSI error message, the format of dates and file sizes processed by SSI.
      +All are optional but at least one must be used. The available options are as follows: +
      +errmsg - error message used for SSI errors
      +sizefmt - format used for sizes in the fsize directive
      +timefmt - format used for timestamps in the flastmod directive
      +
    • +
    • +echo - <!--#echo var="VARIABLE_NAME" encoding="entity" --> +will be replaced by the value of the variable. +
      +The optional encoding parameter specifies the type of encoding to use. +Valid values are entity (default), url or none. +NOTE: Using an encoding other than entity can lead to security issues. +
    • +
    • +exec - <!--#exec cmd="file-name" --> +Used to run commands on the host system. +
    • +
    • +exec - <!--#exec cgi="file-name" --> +This acts the same as the include virtual directive, and doesn't actually execute any commands. +
    • +
    • +include - <!--#include file="file-name" --> +inserts the contents. The path is interpreted relative to the document where this directive +is being used, and IS NOT a "virtual" path relative to either the context root or the server root. +
    • +
    • +include - <!--#include virtual="file-name" --> +inserts the contents. The path is interpreted as a "virtual" path which is +relative to either the context root or the server root (depending on the isVirtualWebappRelative +parameter). +
    • +
    • +flastmod - <!--#flastmod file="filename.shtml" --> +Returns the time that a file was last modified. The path is interpreted relative to the document where this directive +is being used, and IS NOT a "virtual" path relative to either the context root or the server root. +
    • +
    • +flastmod - <!--#flastmod virtual="filename.shtml" --> +Returns the time that a file was last modified. The path is interpreted as a "virtual" path which is +relative to either the context root or the server root (depending on the isVirtualWebappRelative +parameter). +
    • +
    • +fsize - <!--#fsize file="filename.shtml" --> +Returns the size of a file. The path is interpreted relative to the document where this directive +is being used, and IS NOT a "virtual" path relative to either the context root or the server root. +
    • +
    • +fsize - <!--#fsize virtual="filename.shtml" --> +Returns the size of a file. The path is interpreted as a "virtual" path which is +relative to either the context root or the server root (depending on the isVirtualWebappRelative +parameter). +
    • +
    • +printenv - <!--#printenv --> +Returns the list of all the defined variables. +
    • +
    • +set - <!--#set var="foo" value="Bar" --> +is used to assign a value to a user-defined variable. +
    • +
    • +if elif endif else - Used to create conditional sections. For example: +
      <!--#config timefmt="%A" -->
      +<!--#if expr="$DATE_LOCAL = /Monday/" -->
      +<p>Meeting at 10:00 on Mondays</p>
      +<!--#elif expr="$DATE_LOCAL = /Friday/" -->
      +<p>Turn in your time card</p>
      +<!--#else -->
      +<p>Yoga class at noon.</p>
      +<!--#endif -->
      +
    • +
    +

    +See the + +Apache Introduction to SSI for more information on using SSI directives.

    +

    Variables

    +

    +SSI variables are implemented via request attributes on the javax.servlet.ServletRequest object +and are not limited to the SSI servlet. Variables starting with the names +"java.", "javax.", "sun" or "org.apache.catalina.ssi.SSIMediator." are reserved +and cannot be used. +

    +

    The SSI servlet currently implements the following variables: +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Variable NameDescription
    AUTH_TYPE + The type of authentication used for this user: BASIC, FORM, etc.
    CONTENT_LENGTH + The length of the data (in bytes or the number of + characters) passed from a form.
    CONTENT_TYPE + The MIME type of the query data, such as "text/html".
    DATE_GMT +Current date and time in GMT
    DATE_LOCAL +Current date and time in the local time zone
    DOCUMENT_NAME +The current file
    DOCUMENT_URI +Virtual path to the file
    GATEWAY_INTERFACE + The revision of the Common Gateway Interface that the + server uses if enabled: "CGI/1.1".
    HTTP_ACCEPT + A list of the MIME types that the client can accept.
    HTTP_ACCEPT_ENCODING + A list of the compression types that the client can accept.
    HTTP_ACCEPT_LANGUAGE + A list of the languages that the client can accept.
    HTTP_CONNECTION + The way that the connection from the client is being managed: + "Close" or "Keep-Alive".
    HTTP_HOST + The web site that the client requested.
    HTTP_REFERER + The URL of the document that the client linked from.
    HTTP_USER_AGENT + The browser the client is using to issue the request.
    LAST_MODIFIED +Last modification date and time for current file
    PATH_INFO + Extra path information passed to a servlet.
    PATH_TRANSLATED + The translated version of the path given by the + variable PATH_INFO.
    QUERY_STRING +The query string that follows the "?" in the URL. +
    QUERY_STRING_UNESCAPED +Undecoded query string with all shell metacharacters escaped +with "\"
    REMOTE_ADDR + The remote IP address of the user making the request.
    REMOTE_HOST + The remote hostname of the user making the request.
    REMOTE_PORT + The port number at remote IP address of the user making the request.
    REMOTE_USER + The authenticated name of the user.
    REQUEST_METHOD + The method with which the information request was + issued: "GET", "POST" etc.
    REQUEST_URI + The web page originally requested by the client.
    SCRIPT_FILENAME + The location of the current web page on the server.
    SCRIPT_NAME + The name of the web page.
    SERVER_ADDR + The server's IP address.
    SERVER_NAME + The server's hostname or IP address.
    SERVER_PORT + The port on which the server received the request.
    SERVER_PROTOCOL + The protocol used by the server. E.g. "HTTP/1.1".
    SERVER_SOFTWARE + The name and version of the server software that is + answering the client request.
    UNIQUE_ID + A token used to identify the current session if one + has been established.
    +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/ssl-howto.html b/tomcat/docs/ssl-howto.html new file mode 100644 index 0000000..5c016b0 --- /dev/null +++ b/tomcat/docs/ssl-howto.html @@ -0,0 +1,687 @@ + +Apache Tomcat 8 (8.5.43) - SSL/TLS Configuration How-To

    SSL/TLS Configuration How-To

    Table of Contents

    Quick Start

    + +

    The description below uses the variable name $CATALINA_BASE to refer the + base directory against which most relative paths are resolved. If you have + not configured Tomcat for multiple instances by setting a CATALINA_BASE + directory, then $CATALINA_BASE will be set to the value of $CATALINA_HOME, + the directory into which you have installed Tomcat.

    + +

    To install and configure SSL/TLS support on Tomcat, you need to follow +these simple steps. For more information, read the rest of this How-To.

    +
      +
    1. Create a keystore file to store the server's private key and +self-signed certificate by executing the following command:

      +

      Windows:

      +
      "%JAVA_HOME%\bin\keytool" -genkey -alias tomcat -keyalg RSA
      +

      Unix:

      +
      $JAVA_HOME/bin/keytool -genkey -alias tomcat -keyalg RSA
      + +

      and specify a password value of "changeit".

    2. +
    3. Uncomment the "SSL HTTP/1.1 Connector" entry in + $CATALINA_BASE/conf/server.xml and modify as described in + the Configuration section below.

    4. + +
    + + +

    Introduction to SSL/TLS

    + +

    Transport Layer Security (TLS) and its predecessor, Secure Sockets Layer +(SSL), are technologies which allow web browsers and web servers to communicate +over a secured connection. This means that the data being sent is encrypted by +one side, transmitted, then decrypted by the other side before processing. +This is a two-way process, meaning that both the server AND the browser encrypt +all traffic before sending out data.

    + +

    Another important aspect of the SSL/TLS protocol is Authentication. This means +that during your initial attempt to communicate with a web server over a secure +connection, that server will present your web browser with a set of +credentials, in the form of a "Certificate", as proof the site is who and what +it claims to be. In certain cases, the server may also request a Certificate +from your web browser, asking for proof that you are who you claim +to be. This is known as "Client Authentication," although in practice this is +used more for business-to-business (B2B) transactions than with individual +users. Most SSL-enabled web servers do not request Client Authentication.

    + +

    SSL/TLS and Tomcat

    + +

    It is important to note that configuring Tomcat to take advantage of +secure sockets is usually only necessary when running it as a stand-alone +web server. Details can be found in the +Security Considerations Document. +When running Tomcat primarily as a Servlet/JSP container behind +another web server, such as Apache or Microsoft IIS, it is usually necessary +to configure the primary web server to handle the SSL connections from users. +Typically, this server will negotiate all SSL-related functionality, then +pass on any requests destined for the Tomcat container only after decrypting +those requests. Likewise, Tomcat will return cleartext responses, that will +be encrypted before being returned to the user's browser. In this environment, +Tomcat knows that communications between the primary web server and the +client are taking place over a secure connection (because your application +needs to be able to ask about this), but it does not participate in the +encryption or decryption itself.

    + +

    Certificates

    + +

    In order to implement SSL, a web server must have an associated Certificate +for each external interface (IP address) that accepts secure connections. +The theory behind this design is that a server should provide some kind of +reasonable assurance that its owner is who you think it is, particularly +before receiving any sensitive information. While a broader explanation of +Certificates is beyond the scope of this document, think of a Certificate as a +"digital passport" for an Internet address. It states which organisation the +site is associated with, along with some basic contact information about the +site owner or administrator.

    + +

    This certificate is cryptographically signed by its owner, and is +therefore extremely difficult for anyone else to forge. For the certificate to +work in the visitors browsers without warnings, it needs to be signed by a +trusted third party. These are called Certificate Authorities (CAs). To +obtain a signed certificate, you need to choose a CA and follow the instructions +your chosen CA provides to obtain your certificate. A range of CAs is available +including some that offer certificates at no cost.

    + +

    Java provides a relatively simple command-line tool, called +keytool, which can easily create a "self-signed" Certificate. +Self-signed Certificates are simply user generated Certificates which have not +been signed by a well-known CA and are, therefore, not really guaranteed to be +authentic at all. While self-signed certificates can be useful for some testing +scenarios, they are not suitable for any form of production use.

    + +

    General Tips on Running SSL

    + +

    When securing a website with SSL it's important to make sure that all assets +that the site uses are served over SSL, so that an attacker can't bypass +the security by injecting malicious content in a javascript file or similar. To +further enhance the security of your website, you should evaluate to use the +HSTS header. It allows you to communicate to the browser that your site should +always be accessed over https.

    + +

    Using name-based virtual hosts on a secured connection requires careful +configuration of the names specified in a single certificate or Tomcat 8.5 +onwards where Server Name Indication (SNI) support is available. SNI allows +multiple certificates with different names to be associated with a single TLS +connector.

    + +

    Configuration

    + +

    Prepare the Certificate Keystore

    + +

    Tomcat currently operates only on JKS, PKCS11 or +PKCS12 format keystores. The JKS format +is Java's standard "Java KeyStore" format, and is the format created by the +keytool command-line utility. This tool is included in the JDK. +The PKCS12 format is an internet standard, and can be manipulated +via (among other things) OpenSSL and Microsoft's Key-Manager. +

    + +

    Each entry in a keystore is identified by an alias string. Whilst many +keystore implementations treat aliases in a case insensitive manner, case +sensitive implementations are available. The PKCS11 specification, +for example, requires that aliases are case sensitive. To avoid issues related +to the case sensitivity of aliases, it is not recommended to use aliases that +differ only in case. +

    + +

    To import an existing certificate into a JKS keystore, please read the +documentation (in your JDK documentation package) about keytool. +Note that OpenSSL often adds readable comments before the key, but +keytool does not support that. So if your certificate has +comments before the key data, remove them before importing the certificate with +keytool. +

    +

    To import an existing certificate signed by your own CA into a PKCS12 +keystore using OpenSSL you would execute a command like:

    +
    openssl pkcs12 -export -in mycert.crt -inkey mykey.key
    +                       -out mycert.p12 -name tomcat -CAfile myCA.crt
    +                       -caname root -chain
    +

    For more advanced cases, consult the +OpenSSL documentation.

    + +

    To create a new JKS keystore from scratch, containing a single +self-signed Certificate, execute the following from a terminal command line:

    +

    Windows:

    +
    "%JAVA_HOME%\bin\keytool" -genkey -alias tomcat -keyalg RSA
    +

    Unix:

    +
    $JAVA_HOME/bin/keytool -genkey -alias tomcat -keyalg RSA
    + +

    (The RSA algorithm should be preferred as a secure algorithm, and this +also ensures general compatibility with other servers and components.)

    + +

    This command will create a new file, in the home directory of the user +under which you run it, named ".keystore". To specify a +different location or filename, add the -keystore parameter, +followed by the complete pathname to your keystore file, +to the keytool command shown above. You will also need to +reflect this new location in the server.xml configuration file, +as described later. For example:

    +

    Windows:

    +
    "%JAVA_HOME%\bin\keytool" -genkey -alias tomcat -keyalg RSA
    +  -keystore \path\to\my\keystore
    +

    Unix:

    +
    $JAVA_HOME/bin/keytool -genkey -alias tomcat -keyalg RSA
    +  -keystore /path/to/my/keystore
    + +

    After executing this command, you will first be prompted for the keystore +password. The default password used by Tomcat is "changeit" +(all lower case), although you can specify a custom password if you like. +You will also need to specify the custom password in the +server.xml configuration file, as described later.

    + +

    Next, you will be prompted for general information about this Certificate, +such as company, contact name, and so on. This information will be displayed +to users who attempt to access a secure page in your application, so make +sure that the information provided here matches what they will expect.

    + +

    Finally, you will be prompted for the key password, which is the +password specifically for this Certificate (as opposed to any other +Certificates stored in the same keystore file). The keytool prompt +will tell you that pressing the ENTER key automatically uses the same password +for the key as the keystore. You are free to use the same password or to select +a custom one. If you select a different password to the keystore password, you +will also need to specify the custom password in the server.xml +configuration file.

    + +

    If everything was successful, you now have a keystore file with a +Certificate that can be used by your server.

    + +
    + +

    Edit the Tomcat Configuration File

    +

    +Tomcat can use three different implementations of SSL: +

    +
      +
    • JSSE implementation provided as part of the Java runtime
    • +
    • JSSE implementation that uses OpenSSL
    • +
    • APR implementation, which uses the OpenSSL engine by default
    • +
    +

    +The exact configuration details depend on which implementation is being used. +If you configured Connector by specifying generic +protocol="HTTP/1.1" then the implementation used by Tomcat is +chosen automatically. If the installation uses APR +- i.e. you have installed the Tomcat native library - +then it will use the JSSE OpenSSL implementation, otherwise it will use the Java +JSSE implementation. +

    + +

    +Auto-selection of implementation can be avoided if needed. It is done by specifying a classname +in the protocol attribute of the Connector.

    + +

    To define a Java (JSSE) connector, regardless of whether the APR library is +loaded or not, use one of the following:

    +
    <!-- Define a HTTP/1.1 Connector on port 8443, JSSE NIO implementation -->
    +<Connector protocol="org.apache.coyote.http11.Http11NioProtocol"
    +           sslImplementationName="org.apache.tomcat.util.net.jsse.JSSEImplementation"
    +           port="8443" .../>
    +
    +<!-- Define a HTTP/1.1 Connector on port 8443, JSSE NIO2 implementation -->
    +<Connector protocol="org.apache.coyote.http11.Http11Nio2Protocol"
    +           sslImplementationName="org.apache.tomcat.util.net.jsse.JSSEImplementation"
    +           port="8443" .../>
    + +

    The OpenSSL JSSE implementation can also be configured explicitly if needed. If the APR library +is installed (as for using the APR connector), using the sslImplementationName attribute +allows enabling it. When using the OpenSSL JSSE implementation, the configuration can use +either the JSSE attributes or +the OpenSSL attributes (as used for the APR connector), but must not mix attributes from +both types in the same SSLHostConfig or Connector element.

    +
    <!-- Define a HTTP/1.1 Connector on port 8443, JSSE NIO implementation and OpenSSL -->
    +<Connector protocol="org.apache.coyote.http11.Http11NioProtocol" port="8443"
    +           sslImplementationName="org.apache.tomcat.util.net.openssl.OpenSSLImplementation"
    +           .../>
    + +

    Alternatively, to specify an APR connector (the APR library must be available) use:

    +
    <!-- Define a HTTP/1.1 Connector on port 8443, APR implementation -->
    +<Connector protocol="org.apache.coyote.http11.Http11AprProtocol"
    +           port="8443" .../>
    + +

    If you are using APR or JSSE OpenSSL, you have the option of configuring an alternative engine to OpenSSL.

    +
    <Listener className="org.apache.catalina.core.AprLifecycleListener"
    +          SSLEngine="someengine" SSLRandomSeed="somedevice" />
    +

    The default value is

    +
    <Listener className="org.apache.catalina.core.AprLifecycleListener"
    +          SSLEngine="on" SSLRandomSeed="builtin" />
    +

    Also the useAprConnector attribute may be used to have Tomcat default to +using the APR connector rather than the NIO connector:

    +
    <Listener className="org.apache.catalina.core.AprLifecycleListener"
    +          useAprConnector="true" SSLEngine="on" SSLRandomSeed="builtin" />
    +

    +So to enable OpenSSL, make sure the SSLEngine attribute is set to something other than off. +The default value is on and if you specify another value, +it has to be a valid OpenSSL engine name. +

    + +

    +SSLRandomSeed allows to specify a source of entropy. Productive system needs a reliable source of entropy +but entropy may need a lot of time to be collected therefore test systems could use no blocking entropy +sources like "/dev/urandom" that will allow quicker starts of Tomcat. +

    + +

    The final step is to configure the Connector in the +$CATALINA_BASE/conf/server.xml file, where +$CATALINA_BASE represents the base directory for the +Tomcat instance. An example <Connector> element +for an SSL connector is included in the default server.xml +file installed with Tomcat. To configure an SSL connector that uses JSSE, you +will need to remove the comments and edit it so it looks something like +this:

    +
    <!-- Define a SSL Coyote HTTP/1.1 Connector on port 8443 -->
    +<Connector
    +           protocol="org.apache.coyote.http11.Http11NioProtocol"
    +           port="8443" maxThreads="200"
    +           scheme="https" secure="true" SSLEnabled="true"
    +           keystoreFile="${user.home}/.keystore" keystorePass="changeit"
    +           clientAuth="false" sslProtocol="TLS"/>
    +

    + Note: If tomcat-native is installed, the configuration will use JSSE with + an OpenSSL implementation, which supports either this configuration or the APR + configuration example given below.

    +

    + The APR connector uses different attributes for many SSL settings, + particularly keys and certificates. An example of an APR configuration is:

    +
    <!-- Define a SSL Coyote HTTP/1.1 Connector on port 8443 -->
    +<Connector
    +           protocol="org.apache.coyote.http11.Http11AprProtocol"
    +           port="8443" maxThreads="200"
    +           scheme="https" secure="true" SSLEnabled="true"
    +           SSLCertificateFile="/usr/local/ssl/server.crt"
    +           SSLCertificateKeyFile="/usr/local/ssl/server.pem"
    +           SSLVerifyClient="optional" SSLProtocol="TLSv1+TLSv1.1+TLSv1.2"/>
    + + +

    The configuration options and information on which attributes +are mandatory, are documented in the SSL Support section of the +HTTP connector configuration +reference. Make sure that you use the correct attributes for the connector you +are using. The NIO and NIO2 connectors use JSSE unless the JSSE OpenSSL implementation is +installed (in which case it supports either the JSSE or OpenSSL configuration styles), +whereas the APR/native connector uses APR.

    + +

    The port attribute is the TCP/IP +port number on which Tomcat will listen for secure connections. You can +change this to any port number you wish (such as to the default port for +https communications, which is 443). However, special setup +(outside the scope of this document) is necessary to run Tomcat on port +numbers lower than 1024 on many operating systems.

    + +

    If you change the port number here, you should also change the + value specified for the redirectPort attribute on the + non-SSL connector. This allows Tomcat to automatically redirect + users who attempt to access a page with a security constraint specifying + that SSL is required, as required by the Servlet Specification.

    + +

    After completing these configuration changes, you must restart Tomcat as +you normally do, and you should be in business. You should be able to access +any web application supported by Tomcat via SSL. For example, try:

    +
    https://localhost:8443/
    +

    and you should see the usual Tomcat splash page (unless you have modified +the ROOT web application). If this does not work, the following section +contains some troubleshooting tips.

    + +
    + +

    Installing a Certificate from a Certificate Authority

    +

    To obtain and install a Certificate from a Certificate Authority (like verisign.com, thawte.com +or trustcenter.de), read the previous section and then follow these instructions:

    + +

    Create a local Certificate Signing Request (CSR)

    +

    In order to obtain a Certificate from the Certificate Authority of your choice +you have to create a so called Certificate Signing Request (CSR). That CSR will be used +by the Certificate Authority to create a Certificate that will identify your website +as "secure". To create a CSR follow these steps:

    +
      +
    • Create a local self-signed Certificate (as described in the previous section): +
      keytool -genkey -alias tomcat -keyalg RSA
      +    -keystore <your_keystore_filename>
      + Note: In some cases you will have to enter the domain of your website (i.e. www.myside.org) + in the field "first- and lastname" in order to create a working Certificate. +
    • +
    • The CSR is then created with: +
      keytool -certreq -keyalg RSA -alias tomcat -file certreq.csr
      +    -keystore <your_keystore_filename>
      +
    • +
    +

    Now you have a file called certreq.csr that you can submit to the Certificate Authority (look at the +documentation of the Certificate Authority website on how to do this). In return you get a Certificate.

    +
    + +

    Importing the Certificate

    +

    Now that you have your Certificate you can import it into you local keystore. +First of all you have to import a so called Chain Certificate or Root Certificate into your keystore. +After that you can proceed with importing your Certificate.

    + +
      +
    • Download a Chain Certificate from the Certificate Authority you obtained the Certificate from.
      + For Verisign.com commercial certificates go to: + http://www.verisign.com/support/install/intermediate.html
      + For Verisign.com trial certificates go to: + http://www.verisign.com/support/verisign-intermediate-ca/Trial_Secure_Server_Root/index.html
      + For Trustcenter.de go to: + http://www.trustcenter.de/certservices/cacerts/en/en.htm#server
      + For Thawte.com go to: + http://www.thawte.com/certs/trustmap.html
      +
    • +
    • Import the Chain Certificate into your keystore +
      keytool -import -alias root -keystore <your_keystore_filename>
      +    -trustcacerts -file <filename_of_the_chain_certificate>
      +
    • +
    • And finally import your new Certificate +
      keytool -import -alias tomcat -keystore <your_keystore_filename>
      +    -file <your_certificate_filename>
      +
    • +
    +
    +

    Using OCSP Certificates

    +

    To use Online Certificate Status Protocol (OCSP) with Apache Tomcat, ensure + you have downloaded, installed, and configured the + + Tomcat Native Connector. +Furthermore, if you use the Windows platform, ensure you download the +ocsp-enabled connector.

    +

    To use OCSP, you require the following:

    + +
      +
    • OCSP-enabled certificates
    • +
    • Tomcat with SSL APR connector
    • +
    • Configured OCSP responder
    • +
    + +

    Generating OCSP-Enabled Certificates

    +

    Apache Tomcat requires the OCSP-enabled certificate to have the OCSP + responder location encoded in the certificate. The basic OCSP-related + certificate authority settings in the openssl.cnf file could look + as follows:

    + +
    
    +#... omitted for brevity
    +
    +[x509]
    +x509_extensions = v3_issued
    +
    +[v3_issued]
    +subjectKeyIdentifier=hash
    +authorityKeyIdentifier=keyid,issuer
    +# The address of your responder
    +authorityInfoAccess = OCSP;URI:http://127.0.0.1:8088
    +keyUsage = critical,digitalSignature,nonRepudiation,keyEncipherment,dataEncipherment,keyAgreement,keyCertSign,cRLSign,encipherOnly,decipherOnly
    +basicConstraints=critical,CA:FALSE
    +nsComment="Testing OCSP Certificate"
    +
    +#... omitted for brevity
    +
    + +

    The settings above encode the OCSP responder address + 127.0.0.1:8088 into the certificate. Note that for the following + steps, you must have openssl.cnf and other configuration of + your CA ready. To generate an OCSP-enabled certificate:

    + +
      +
    • + Create a private key: +
      openssl genrsa -aes256 -out ocsp-cert.key 4096
      +
    • +
    • + Create a signing request (CSR): +
      openssl req -config openssl.cnf -new -sha256 \
      +  -key ocsp-cert.key -out ocsp-cert.csr
    • +
    • + Sign the CSR: +
      openssl ca -openssl.cnf -extensions ocsp -days 375 -notext \
      +  -md sha256 -in ocsp-cert.csr -out ocsp-cert.crt
      +
    • +
    • + You may verify the certificate: +
      openssl x509 -noout -text -in ocsp-cert.crt
      +
    • +
    +
    + +

    Configuring OCSP Connector

    + +

    To configure the OCSP connector, first verify that you are loading the Tomcat + APR library. Check the + Apache Portable Runtime (APR) based Native library for Tomcat +for more information about installation of APR. A basic OCSP-enabled connector + definition in the server.xml file looks as follows:

    +
    
    +<Connector
    +    port="8443"
    +    protocol="org.apache.coyote.http11.Http11AprProtocol"
    +    secure="true"
    +    scheme="https"
    +    SSLEnabled="true"
    +  <SSLHostConfig
    +      caCertificateFile="/path/to/ca.pem"
    +      certificateVerification="require"
    +      certificateVerificationDepth="10" >
    +    <Certificate
    +        certificateFile="/path/to/ocsp-cert.crt"
    +        certificateKeyFile="/path/to/ocsp-cert.key" />
    +  </SSLHostConfig>
    +
    +
    + +

    Starting OCSP Responder

    +

    Apache Tomcat will query an OCSP responder server to get the certificate + status. When testing, an easy way to create an OCSP responder is by executing + the following: +

    openssl ocsp -port 127.0.0.1:8088 \
    +    -text -sha256 -index index.txt \
    +    -CA ca-chain.cert.pem -rkey ocsp-cert.key \
    +    -rsigner ocsp-cert.crt

    + +

    Do note that when using OCSP, the responder encoded in the connector + certificate must be running. For further information, see + + OCSP documentation + . +

    + +
    + +

    Troubleshooting

    + +

    Here is a list of common problems that you may encounter when setting up +SSL communications, and what to do about them.

    + +
      + +
    • When Tomcat starts up, I get an exception like + "java.io.FileNotFoundException: {some-directory}/{some-file} not found". + +

      A likely explanation is that Tomcat cannot find the keystore file + where it is looking. By default, Tomcat expects the keystore file to + be named .keystore in the user home directory under which + Tomcat is running (which may or may not be the same as yours :-). If + the keystore file is anywhere else, you will need to add a + keystoreFile attribute to the <Connector> + element in the Tomcat + configuration file.

      +
    • + +
    • When Tomcat starts up, I get an exception like + "java.io.FileNotFoundException: Keystore was tampered with, or + password was incorrect". + +

      Assuming that someone has not actually tampered with + your keystore file, the most likely cause is that Tomcat is using + a different password than the one you used when you created the + keystore file. To fix this, you can either go back and + recreate the keystore + file, or you can add or update the keystorePass + attribute on the <Connector> element in the + Tomcat configuration + file. REMINDER - Passwords are case sensitive!

      +
    • + +
    • When Tomcat starts up, I get an exception like + "java.net.SocketException: SSL handshake error javax.net.ssl.SSLException: No + available certificate or key corresponds to the SSL cipher suites which are + enabled." + +

      A likely explanation is that Tomcat cannot find the alias for the server + key within the specified keystore. Check that the correct + keystoreFile and keyAlias are specified in the + <Connector> element in the + Tomcat configuration file. + REMINDER - keyAlias values may be case + sensitive!

      +
    • + +
    • My Java-based client aborts handshakes with exceptions such as + "java.lang.RuntimeException: Could not generate DH keypair" and + "java.security.InvalidAlgorithmParameterException: Prime size must be multiple + of 64, and can only range from 512 to 1024 (inclusive)" + +

      If you are using the APR/native connector or the JSSE OpenSSL implementation, + it will determine the strength of ephemeral DH keys from the key size of + your RSA certificate. For example a 2048 bit RSA key will result in + using a 2048 bit prime for the DH keys. Unfortunately Java 6 only supports + 768 bit and Java 7 only supports 1024 bit. So if your certificate has a + stronger key, old Java clients might produce such handshake failures. + As a mitigation you can either try to force them to use another cipher by + configuring an appropriate SSLCipherSuite and activate + SSLHonorCipherOrder, or embed weak DH params in your + certificate file. The latter approach is not recommended because it weakens + the SSL security (logjam attack).

      +
    • + +
    + +

    If you are still having problems, a good source of information is the +TOMCAT-USER mailing list. You can find pointers to archives +of previous messages on this list, as well as subscription and unsubscription +information, at +https://tomcat.apache.org/lists.html.

    + +

    Using the SSL for session tracking in your application

    +

    This is a new feature in the Servlet 3.0 specification. Because it uses the + SSL session ID associated with the physical client-server connection there + are some limitations. They are:

    +
      +
    • Tomcat must have a connector with the attribute + isSecure set to true.
    • +
    • If SSL connections are managed by a proxy or a hardware accelerator + they must populate the SSL request headers (see the + SSLValve) so that + the SSL session ID is visible to Tomcat.
    • +
    • If Tomcat terminates the SSL connection, it will not be possible to use + session replication as the SSL session IDs will be different on each + node.
    • +
    + +

    + To enable SSL session tracking you need to use a context listener to set the + tracking mode for the context to be just SSL (if any other tracking mode is + enabled, it will be used in preference). It might look something like:

    +
    package org.apache.tomcat.example;
    +
    +import java.util.EnumSet;
    +
    +import javax.servlet.ServletContext;
    +import javax.servlet.ServletContextEvent;
    +import javax.servlet.ServletContextListener;
    +import javax.servlet.SessionTrackingMode;
    +
    +public class SessionTrackingModeListener implements ServletContextListener {
    +
    +    @Override
    +    public void contextDestroyed(ServletContextEvent event) {
    +        // Do nothing
    +    }
    +
    +    @Override
    +    public void contextInitialized(ServletContextEvent event) {
    +        ServletContext context = event.getServletContext();
    +        EnumSet<SessionTrackingMode> modes =
    +            EnumSet.of(SessionTrackingMode.SSL);
    +
    +        context.setSessionTrackingModes(modes);
    +    }
    +
    +}
    + +

    Note: SSL session tracking is implemented for the NIO and NIO2 connectors. + It is not yet implemented for the APR connector.

    + +

    Miscellaneous Tips and Bits

    + +

    To access the SSL session ID from the request, use:

    + +
    String sslID = (String)request.getAttribute("javax.servlet.request.ssl_session_id");
    +

    +For additional discussion on this area, please see +Bugzilla. +

    + +

    To terminate an SSL session, use:

    +
    // Standard HTTP session invalidation
    +session.invalidate();
    +
    +// Invalidate the SSL Session
    +org.apache.tomcat.util.net.SSLSessionManager mgr =
    +    (org.apache.tomcat.util.net.SSLSessionManager)
    +    request.getAttribute("javax.servlet.request.ssl_session_mgr");
    +mgr.invalidateSession();
    +
    +// Close the connection since the SSL session will be active until the connection
    +// is closed
    +response.setHeader("Connection", "close");
    +

    + Note that this code is Tomcat specific due to the use of the + SSLSessionManager class. This is currently only available for the NIO and + NIO2 connectors, not the APR/native connector. +

    +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/tribes/developers.html b/tomcat/docs/tribes/developers.html new file mode 100644 index 0000000..f4fbd54 --- /dev/null +++ b/tomcat/docs/tribes/developers.html @@ -0,0 +1,50 @@ + +Apache Tribes - The Tomcat Cluster Communication Module (8.5.43) - Apache Tribes - Developers

    Apache Tribes - Developers

    Developers

    +

    TODO

    +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/tribes/faq.html b/tomcat/docs/tribes/faq.html new file mode 100644 index 0000000..b3e628e --- /dev/null +++ b/tomcat/docs/tribes/faq.html @@ -0,0 +1,50 @@ + +Apache Tribes - The Tomcat Cluster Communication Module (8.5.43) - Apache Tribes - Frequently Asked Questions

    Apache Tribes - Frequently Asked Questions

    Frequently Asked Questions

    +

    TODO

    +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/tribes/interceptors.html b/tomcat/docs/tribes/interceptors.html new file mode 100644 index 0000000..12638d1 --- /dev/null +++ b/tomcat/docs/tribes/interceptors.html @@ -0,0 +1,50 @@ + +Apache Tribes - The Tomcat Cluster Communication Module (8.5.43) - Apache Tribes - Interceptors

    Apache Tribes - Interceptors

    Interceptors

    +

    TODO

    +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/tribes/introduction.html b/tomcat/docs/tribes/introduction.html new file mode 100644 index 0000000..07981eb --- /dev/null +++ b/tomcat/docs/tribes/introduction.html @@ -0,0 +1,274 @@ + +Apache Tribes - The Tomcat Cluster Communication Module (8.5.43) - Apache Tribes - Introduction

    Apache Tribes - Introduction

    Table of Contents

    Quick Start

    + +

    Apache Tribes is a group or peer-to-peer communication framework that enables you to easily connect + your remote objects to communicate with each other. +

    +
      +
    • Import: org.apache.catalina.tribes.Channel
    • +
    • Import: org.apache.catalina.tribes.Member
    • +
    • Import: org.apache.catalina.tribes.MembershipListener
    • +
    • Import: org.apache.catalina.tribes.ChannelListener
    • +
    • Import: org.apache.catalina.tribes.group.GroupChannel
    • +
    • Create a class that implements: org.apache.catalina.tribes.ChannelListener
    • +
    • Create a class that implements: org.apache.catalina.tribes.MembershipListener
    • +
    • Simple class to demonstrate how to send a message: +
      //create a channel
      +Channel myChannel = new GroupChannel();
      +
      +//create my listeners
      +ChannelListener msgListener = new MyMessageListener();
      +MembershipListener mbrListener = new MyMemberListener();
      +
      +//attach the listeners to the channel
      +myChannel.addMembershipListener(mbrListener);
      +myChannel.addChannelListener(msgListener);
      +
      +//start the channel
      +myChannel.start(Channel.DEFAULT);
      +
      +//create a message to be sent, message must implement java.io.Serializable
      +//for performance reasons you probably want them to implement java.io.Externalizable
      +Serializable myMsg = new MyMessage();
      +
      +//retrieve my current members
      +Member[] group = myChannel.getMembers();
      +
      +//send the message
      +myChannel.send(group,myMsg,Channel.SEND_OPTIONS_DEFAULT);
      +
    • +
    +

    + Simple yeah? There is a lot more to Tribes than we have shown, hopefully the docs will be able + to explain more to you. Remember, that we are always interested in suggestions, improvements, bug fixes + and anything that you think would help this project. +

    +

    What is Tribes

    +

    + Tribes is a messaging framework with group communication abilities. Tribes allows you to send and receive + messages over a network, it also allows for dynamic discovery of other nodes in the network.
    + And that is the short story, it really is as simple as that. What makes Tribes useful and unique will be + described in the section below.
    +

    +

    + The Tribes module was started early 2006 and a small part of the code base comes from the clustering module + that has been existing since 2003 or 2004. + The current cluster implementation has several short comings and many workarounds were created due + to the complexity in group communication. Long story short, what should have been two modules a long time + ago, will be now. Tribes takes out the complexity of messaging from the replication module and becomes + a fully independent and highly flexible group communication module.
    +

    +

    + In Tomcat the old modules/cluster has now become modules/groupcom(Tribes) and + modules/ha (replication). This will allow development to proceed and let the developers + focus on the issues they are actually working on rather than getting boggled down in details of a module + they are not interested in. The understanding is that both communication and replication are complex enough, + and when trying to develop them in the same module, well you know, it becomes a cluster :)
    +

    +

    + Tribes allows for guaranteed messaging, and can be customized in many ways. Why is this important?
    + Well, you as a developer want to know that the messages you are sending are reaching their destination. + More than that, if a message doesn't reach its destination, the application on top of Tribes will be notified + that the message was never sent, and what node it failed. +

    + +

    Why another messaging framework

    +

    + I am a big fan of reusing code and would never dream of developing something if someone else has already + done it and it was available to me and the community I try to serve.
    + When I did my research to improve the clustering module I was constantly faced with a few obstacles:
    + 1. The framework wasn't flexible enough
    + 2. The framework was licensed in a way that neither I nor the community could use it
    + 3. Several features that I needed were missing
    + 4. Messaging was guaranteed, but no feedback was reported to me
    + 5. The semantics of my message delivery had to be configured before runtime
    + And the list continues... +

    +

    + So I came up with Tribes, to address these issues and other issues that came along. + When designing Tribes I wanted to make sure I didn't lose any of the flexibility and + delivery semantics that the existing frameworks already delivered. The goal was to create a framework + that could do everything that the others already did, but to provide more flexibility for the application + developer. In the next section will give you the high level overview of what features tribes offers or will offer. +

    +

    Feature Overview

    +

    + To give you an idea of the feature set I will list it out here. + Some of the features are not yet completed, if that is the case they are marked accordingly. +

    +

    + Pluggable modules
    + Tribes is built using interfaces. Any of the modules or components that are part of Tribes can be swapped out + to customize your own Tribes implementation. +

    +

    + Guaranteed Messaging
    + In the default implementation of Tribes uses TCP or UDP for messaging. TCP already has guaranteed message delivery + and flow control built in. I believe that the performance of Java TCP, will outperform an implementation of + Java/UDP/flow-control/message guarantee since the logic happens further down the stack. UDP messaging has been added in for + sending messages over UDP instead of TCP when desired. The same guarantee scenarios as described below are still available + over UDP, however, when a UDP message is lost, it's considered failed.
    + Tribes supports both non-blocking and blocking IO operations. The recommended setting is to use non blocking + as it promotes better parallelism when sending and receiving messages. The blocking implementation is available + for those platforms where NIO is still a trouble child. +

    +

    + Different Guarantee Levels
    + There are three different levels of delivery guarantee when a message is sent. +

    +
      +
    1. IO Based send guarantee. - fastest, least reliable
      + This means that Tribes considers the message transfer to be successful + if the message was sent to the socket send buffer and accepted.
      + On blocking IO, this would be socket.getOutputStream().write(msg)
      + On non blocking IO, this would be socketChannel.write(), and the buffer byte buffer gets emptied + followed by a socketChannel.read() to ensure the channel still open. + The read() has been added since write() will succeed if the connection has been "closed" + when using NIO. +
    2. +
    3. ACK based. - recommended, guaranteed delivery
      + When the message has been received on a remote node, an ACK is sent back to the sender, + indicating that the message was received successfully. +
    4. +
    5. SYNC_ACK based. - guaranteed delivery, guaranteed processed, slowest
      + When the message has been received on a remote node, the node will process + the message and if the message was processed successfully, an ACK is sent back to the sender + indicating that the message was received and processed successfully. + If the message was received, but processing it failed, an ACK_FAIL will be sent back + to the sender. This is a unique feature that adds an incredible amount value to the application + developer. Most frameworks here will tell you that the message was delivered, and the application + developer has to build in logic on whether the message was actually processed properly by the application + on the remote node. If configured, Tribes will throw an exception when it receives an ACK_FAIL + and associate that exception with the member that didn't process the message. +
    6. +
    +

    + You can of course write even more sophisticated guarantee levels, and some of them will be mentioned later on + in the documentation. One mentionable level would be a 2-Phase-Commit, where the remote applications don't receive + the message until all nodes have received the message. Sort of like a all-or-nothing protocol. +

    +

    + Per Message Delivery Attributes
    + Perhaps the feature that makes Tribes stand out from the crowd of group communication frameworks. + Tribes enables you to send to decide what delivery semantics a message transfer should have on a per + message basis. Meaning, that your messages are not delivered based on some static configuration + that remains fixed after the message framework has been started.
    + To give you an example of how powerful this feature is, I'll try to illustrate it with a simple example. + Imagine you need to send 10 different messages, you could send them the following way: +

    +
    Message_1 - asynchronous and fast, no guarantee required, fire and forget
    +Message_2 - all-or-nothing, either all receivers get it, or none.
    +Message_3 - encrypted and SYNC_ACK based
    +Message_4 - asynchronous, SYNC_ACK and call back when the message is processed on the remote nodes
    +Message_5 - totally ordered, this message should be received in the same order on all nodes that have been
    +            send totally ordered
    +Message_6 - asynchronous and totally ordered
    +Message_7 - RPC message, send a message, wait for all remote nodes to reply before returning
    +Message_8 - RPC message, wait for the first reply
    +Message_9 - RPC message, asynchronous, don't wait for a reply, collect them via a callback
    +Message_10- sent to a member that is not part of this group
    +

    + As you can imagine by now, these are just examples. The number of different semantics you can apply on a + per-message-basis is almost limitless. Tribes allows you to set up to 28 different on a message + and then configure Tribes to what flag results in what action on the message.
    + Imagine a shared transactional cache, probably >90% are reads, and the dirty reads should be completely + unordered and delivered as fast as possible. But transactional writes on the other hand, have to + be ordered so that no cache gets corrupted. With tribes you would send the write messages totally ordered, + while the read messages you simple fire to achieve highest throughput.
    + There are probably better examples on how this powerful feature can be used, so use your imagination and + your experience to think of how this could benefit you in your application. +

    +

    + Interceptor based message processing
    + Tribes uses a customizable interceptor stack to process messages that are sent and received.
    + So what, all frameworks have this!
    + Yes, but in Tribes interceptors can react to a message based on the per-message-attributes + that are sent runtime. Meaning, that if you add a encryption interceptor that encrypts message + you can decide if this interceptor will encrypt all messages, or only certain messages that are decided + by the applications running on top of Tribes.
    + This is how Tribes is able to send some messages totally ordered and others fire and forget style + like the example above.
    + The number of interceptors that are available will keep growing, and we would appreciate any contributions + that you might have. +

    +

    + Threadless Interceptor stack + The interceptor don't require any separate threads to perform their message manipulation.
    + Messages that are sent will piggy back on the thread that is sending them all the way through transmission. + The exception is the MessageDispatchInterceptor that will queue up the message + and send it on a separate thread for asynchronous message delivery. + Messages received are controlled by a thread pool in the receiver component.
    + The channel object can send a heartbeat() through the interceptor stack to allow + for timeouts, cleanup and other events.
    + The MessageDispatchInterceptor is the only interceptor that is configured by default. +

    +

    + Parallel Delivery
    + Tribes support parallel delivery of messages. Meaning that node_A could send three messages to node_B in + parallel. This feature becomes useful when sending messages with different delivery semantics. + Otherwise if Message_1 was sent totally ordered, Message_2 would have to wait for that message to complete.
    + Through NIO, Tribes is also able to send a message to several receivers at the same time on the same thread. +

    +

    + Silent Member Messaging
    + With Tribes you are able to send messages to members that are not in your group. + So by default, you can already send messages over a wide area network, even though the dynamic discover + module today is limited to local area networks by using multicast for dynamic node discovery. + Of course, the membership component will be expanded to support WAN memberships in the future. + But this is very useful, when you want to hide members from the rest of the group and only communicate with them +

    +

    Where can I get Tribes

    +

    + Tribes ships as a module with Tomcat, and is released as part of the Apache Tomcat release. +

    + + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/tribes/membership.html b/tomcat/docs/tribes/membership.html new file mode 100644 index 0000000..cd0c687 --- /dev/null +++ b/tomcat/docs/tribes/membership.html @@ -0,0 +1,50 @@ + +Apache Tribes - The Tomcat Cluster Communication Module (8.5.43) - Apache Tribes - Membership

    Apache Tribes - Membership

    Membership

    +

    TODO

    +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/tribes/setup.html b/tomcat/docs/tribes/setup.html new file mode 100644 index 0000000..893c772 --- /dev/null +++ b/tomcat/docs/tribes/setup.html @@ -0,0 +1,50 @@ + +Apache Tribes - The Tomcat Cluster Communication Module (8.5.43) - Apache Tribes - Configuration

    Apache Tribes - Configuration

    Configuration Overview

    +

    TODO

    +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/tribes/status.html b/tomcat/docs/tribes/status.html new file mode 100644 index 0000000..f8d1487 --- /dev/null +++ b/tomcat/docs/tribes/status.html @@ -0,0 +1,50 @@ + +Apache Tribes - The Tomcat Cluster Communication Module (8.5.43) - Apache Tribes - Status

    Apache Tribes - Status

    Status

    +

    TODO

    +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/tribes/transport.html b/tomcat/docs/tribes/transport.html new file mode 100644 index 0000000..48af71b --- /dev/null +++ b/tomcat/docs/tribes/transport.html @@ -0,0 +1,50 @@ + +Apache Tribes - The Tomcat Cluster Communication Module (8.5.43) - Apache Tribes - Transport

    Apache Tribes - Transport

    Transport

    +

    TODO

    +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/virtual-hosting-howto.html b/tomcat/docs/virtual-hosting-howto.html new file mode 100644 index 0000000..79af008 --- /dev/null +++ b/tomcat/docs/virtual-hosting-howto.html @@ -0,0 +1,152 @@ + +Apache Tomcat 8 (8.5.43) - Virtual Hosting and Tomcat

    Virtual Hosting and Tomcat

    Table of Contents

    Assumptions

    +

    + For the sake of this how-to, assume you have a development host with two + host names, ren and stimpy. Let's also assume + one instance of Tomcat running, so $CATALINA_HOME refers to + wherever it's installed, perhaps /usr/local/tomcat. +

    +

    + Also, this how-to uses Unix-style path separators and commands; if you're + on Windows modify accordingly. +

    +

    server.xml

    +

    + At the simplest, edit the Engine portion + of your server.xml file to look like this: +

    +
    <Engine name="Catalina" defaultHost="ren">
    +    <Host name="ren"    appBase="renapps"/>
    +    <Host name="stimpy" appBase="stimpyapps"/>
    +</Engine>
    +

    + Note that the directory structures under the appBase for each host should + not overlap each other. +

    +

    + Consult the configuration documentation for other attributes of the + Engine and + Host elements. +

    +

    Webapps Directory

    +

    + Create directories for each of the virtual hosts: +

    +
    mkdir $CATALINA_HOME/renapps
    +mkdir $CATALINA_HOME/stimpyapps
    +

    Configuring Your Contexts

    +

    General

    +

    Contexts are normally located underneath the appBase directory. For + example, to deploy the foobar context as a war file in + the ren host, use + $CATALINA_HOME/renapps/foobar.war. Note that the + default or ROOT context for ren would be deployed as + $CATALINA_HOME/renapps/ROOT.war (WAR) or + $CATALINA_HOME/renapps/ROOT (directory). +

    +

    NOTE: The docBase for a context should never be + the same as the appBase for a host. +

    +
    +

    context.xml - approach #1

    +

    + Within your Context, create a META-INF directory and then + place your Context definition in it in a file named + context.xml. i.e. + $CATALINA_HOME/renapps/ROOT/META-INF/context.xml + This makes deployment easier, particularly if you're distributing a WAR + file. +

    +
    +

    context.xml - approach #2

    +

    + Create a structure under $CATALINA_HOME/conf/Catalina + corresponding to your virtual hosts, e.g.: +

    +
    mkdir $CATALINA_HOME/conf/Catalina/ren
    +mkdir $CATALINA_HOME/conf/Catalina/stimpy
    +

    + Note that the ending directory name "Catalina" represents the + name attribute of the + Engine element as shown above. +

    +

    + Now, for your default webapps, add: +

    +
    $CATALINA_HOME/conf/Catalina/ren/ROOT.xml
    +$CATALINA_HOME/conf/Catalina/stimpy/ROOT.xml
    +

    + If you want to use the Tomcat manager webapp for each host, you'll also + need to add it here: +

    +
    cd $CATALINA_HOME/conf/Catalina
    +cp localhost/manager.xml ren/
    +cp localhost/manager.xml stimpy/
    +
    +

    Defaults per host

    +

    + You can override the default values found in conf/context.xml + and conf/web.xml by specifying the new values in files + named context.xml.default and web.xml.default + from the host specific xml directory.

    +

    Following our previous example, you could use + $CATALINA_HOME/conf/Catalina/ren/web.xml.default + to customize the defaults for all webapps that are deployed in the virtual + host named ren. +

    +
    +

    Further Information

    +

    + Consult the configuration documentation for other attributes of the + Context element. +

    +
    +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/web-socket-howto.html b/tomcat/docs/web-socket-howto.html new file mode 100644 index 0000000..ac5585f --- /dev/null +++ b/tomcat/docs/web-socket-howto.html @@ -0,0 +1,144 @@ + +Apache Tomcat 8 (8.5.43) - WebSocket How-To

    WebSocket How-To

    Table of Contents

    Overview

    +

    Tomcat provides support for WebSocket as defined by + RFC 6455.

    +

    Application development

    +

    Tomcat implements the Java WebSocket 1.1 API defined by JSR-356.

    + +

    There are several example applications that demonstrate how the WebSocket API + can be used. You will need to look at both the client side + HTML and the server side + code.

    +

    Tomcat WebSocket specific configuration

    + +

    Tomcat provides a number of Tomcat specific configuration options for + WebSocket. It is anticipated that these will be absorbed into the WebSocket + specification over time.

    + +

    The write timeout used when sending WebSocket messages in blocking mode + defaults to 20000 milliseconds (20 seconds). This may be changed by setting + the property org.apache.tomcat.websocket.BLOCKING_SEND_TIMEOUT + in the user properties collection attached to the WebSocket session. The + value assigned to this property should be a Long and represents + the timeout to use in milliseconds. For an infinite timeout, use + -1.

    + +

    If the application does not define a MessageHandler.Partial for + incoming binary messages, any incoming binary messages must be buffered so + the entire message can be delivered in a single call to the registered + MessageHandler.Whole for binary messages. The default buffer + size for binary messages is 8192 bytes. This may be changed for a web + application by setting the servlet context initialization parameter + org.apache.tomcat.websocket.binaryBufferSize to the desired + value in bytes.

    + +

    If the application does not define a MessageHandler.Partial for + incoming text messages, any incoming text messages must be buffered so the + entire message can be delivered in a single call to the registered + MessageHandler.Whole for text messages. The default buffer size + for text messages is 8192 bytes. This may be changed for a web application by + setting the servlet context initialization parameter + org.apache.tomcat.websocket.textBufferSize to the desired value + in bytes.

    + +

    The Java WebSocket specification 1.0 does not permit programmatic deployment + after the first endpoint has started a WebSocket handshake. By default, + Tomcat continues to permit additional programmatic deployment. This + behavior is controlled by the + org.apache.tomcat.websocket.noAddAfterHandshake servlet context + initialization parameter. The default may be changed by setting the + org.apache.tomcat.websocket.STRICT_SPEC_COMPLIANCE system + property to true but any explicit setting on the servlet context + will always take priority.

    + +

    When using the WebSocket client to connect to server endpoints, the timeout + for IO operations while establishing the connection is controlled by the + userProperties of the provided + javax.websocket.ClientEndpointConfig. The property is + org.apache.tomcat.websocket.IO_TIMEOUT_MS and is the + timeout as a String in milliseconds. The default is 5000 (5 + seconds).

    + +

    When using the WebSocket client to connect to secure server endpoints, the + client SSL configuration is controlled by the userProperties + of the provided javax.websocket.ClientEndpointConfig. The + following user properties are supported:

    +
      +
    • org.apache.tomcat.websocket.SSL_CONTEXT
    • +
    • org.apache.tomcat.websocket.SSL_PROTOCOLS
    • +
    • org.apache.tomcat.websocket.SSL_TRUSTSTORE
    • +
    • org.apache.tomcat.websocket.SSL_TRUSTSTORE_PWD
    • +
    +

    The default truststore password is changeit.

    + +

    If the org.apache.tomcat.websocket.SSL_CONTEXT property is + set then the org.apache.tomcat.websocket.SSL_TRUSTSTORE and + org.apache.tomcat.websocket.SSL_TRUSTSTORE_PWD properties + will be ignored.

    + +

    For secure server end points, host name verification is enabled by default. + To bypass this verification (not recommended), it is necessary to provide a + custom SSLContext via the + org.apache.tomcat.websocket.SSL_CONTEXT user property. The + custom SSLContext must be configured with a custom + TrustManager that extends + javax.net.ssl.X509ExtendedTrustManager. The desired verification + (or lack of verification) can then be controlled by appropriate + implementations of the individual abstract methods.

    + +

    When using the WebSocket client to connect to server endpoints, the number of + HTTP redirects that the client will follow is controlled by the + userProperties of the provided + javax.websocket.ClientEndpointConfig. The property is + org.apache.tomcat.websocket.MAX_REDIRECTIONS. The default value + is 20. Redirection support can be disabled by configuring a value of zero.

    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/websocketapi/index.html b/tomcat/docs/websocketapi/index.html new file mode 100644 index 0000000..517ac7c --- /dev/null +++ b/tomcat/docs/websocketapi/index.html @@ -0,0 +1,34 @@ + + + + + + API docs + + + + +The WebSocket Javadoc is not installed by default. Download and install +the "fulldocs" package to get it. + +You can also access the javadoc online in the Tomcat + +documentation bundle. + + + diff --git a/tomcat/docs/windows-auth-howto.html b/tomcat/docs/windows-auth-howto.html new file mode 100644 index 0000000..63682c3 --- /dev/null +++ b/tomcat/docs/windows-auth-howto.html @@ -0,0 +1,340 @@ + +Apache Tomcat 8 (8.5.43) - Windows Authentication How-To

    Windows Authentication How-To

    Table of Contents

    Overview

    +

    Integrated Windows authentication is most frequently used within intranet +environments since it requires that the server performing the authentication and +the user being authenticated are part of the same domain. For the user to be +authenticated automatically, the client machine used by the user must also be +part of the domain.

    +

    There are several options for implementing integrated Windows authentication +with Apache Tomcat. They are:

    +
      +
    • Built-in Tomcat support.
    • +
    • Use a third party library such as Waffle.
    • +
    • Use a reverse proxy that supports Windows authentication to perform the +authentication step such as IIS or httpd.
    • +
    +

    The configuration of each of these options is discussed in the following +sections.

    +

    Built-in Tomcat support

    +

    Kerberos (the basis for integrated Windows authentication) requires careful +configuration. If the steps in this guide are followed exactly, then a working +configuration will result. It is important that the steps below are followed +exactly. There is very little scope for flexibility in the configuration. From +the testing to date it is known that:

    +
      +
    • The host name used to access the Tomcat server must match the host name in +the SPN exactly else authentication will fail. A checksum error may be reported +in the debug logs in this case.
    • +
    • The client must be of the view that the server is part of the local trusted +intranet.
    • +
    • The SPN must be HTTP/<hostname> and it must be exactly the same in all +the places it is used.
    • +
    • The port number must not be included in the SPN.
    • +
    • No more than one SPN may be mapped to a domain user.
    • +
    • Tomcat must run as the domain account with which the SPN has been associated +or as domain admin. It is NOT recommended to run Tomcat under a +domain admin user.
    • +
    • The domain name (DEV.LOCAL) is not case sensitive when used in +the ktpass command, nor when used in jaas.conf
    • +
    • The domain must be specified when using the ktpass command
    • +
    +

    There are four components to the configuration of the built-in Tomcat +support for Windows authentication. The domain controller, the server hosting +Tomcat, the web application wishing to use Windows authentication and the client +machine. The following sections describe the configuration required for each +component.

    +

    The names of the three machines used in the configuration examples below are +win-dc01.dev.local (the domain controller), win-tc01.dev.local (the Tomcat +instance) and win-pc01.dev.local (client). All are members of the DEV.LOCAL +domain.

    +

    Note: In order to use the passwords in the steps below, the domain password +policy had to be relaxed. This is not recommended for production environments. +

    + +

    Domain Controller

    +

    These steps assume that the server has already been configured to act as a + domain controller. Configuration of a Windows server as a domain controller is + outside the scope of this how-to. The steps to configure the domain controller + to enable Tomcat to support Windows authentication are as follows: +

    +
      +
    • Create a domain user that will be mapped to the service name used by the + Tomcat server. In this how-to, this user is called tc01 and has a + password of tc01pass.
    • +
    • Map the service principal name (SPN) to the user account. SPNs take the + form + <service class>/<host>:<port>/<service name>. + The SPN used in this how-to is HTTP/win-tc01.dev.local. To + map the user to the SPN, run the following: +
      setspn -A HTTP/win-tc01.dev.local tc01
      +
    • +
    • Generate the keytab file that the Tomcat server will use to authenticate + itself to the domain controller. This file contains the Tomcat private key for + the service provider account and should be protected accordingly. To generate + the file, run the following command (all on a single line): +
      ktpass /out c:\tomcat.keytab /mapuser tc01@DEV.LOCAL
      +          /princ HTTP/win-tc01.dev.local@DEV.LOCAL
      +          /pass tc01pass /kvno 0
    • +
    • Create a domain user to be used on the client. In this how-to the domain + user is test with a password of testpass.
    • +
    +

    The above steps have been tested on a domain controller running Windows + Server 2008 R2 64-bit Standard using the Windows Server 2003 functional level + for both the forest and the domain. +

    +
    + +

    Tomcat instance (Windows server)

    +

    These steps assume that Tomcat and a Java 6 JDK/JRE have already been + installed and configured and that Tomcat is running as the tc01@DEV.LOCAL + user. The steps to configure the Tomcat instance for Windows authentication + are as follows: +

    +
      +
    • Copy the tomcat.keytab file created on the domain controller + to $CATALINA_BASE/conf/tomcat.keytab.
    • +
    • Create the kerberos configuration file + $CATALINA_BASE/conf/krb5.ini. The file used in this how-to + contained:
      [libdefaults]
      +default_realm = DEV.LOCAL
      +default_keytab_name = FILE:c:\apache-tomcat-8.5.x\conf\tomcat.keytab
      +default_tkt_enctypes = rc4-hmac,aes256-cts-hmac-sha1-96,aes128-cts-hmac-sha1-96
      +default_tgs_enctypes = rc4-hmac,aes256-cts-hmac-sha1-96,aes128-cts-hmac-sha1-96
      +forwardable=true
      +
      +[realms]
      +DEV.LOCAL = {
      +        kdc = win-dc01.dev.local:88
      +}
      +
      +[domain_realm]
      +dev.local= DEV.LOCAL
      +.dev.local= DEV.LOCAL
      + The location of this file can be changed by setting the + java.security.krb5.conf system property.
    • +
    • Create the JAAS login configuration file + $CATALINA_BASE/conf/jaas.conf. The file used in this how-to + contained:
      com.sun.security.jgss.krb5.initiate {
      +    com.sun.security.auth.module.Krb5LoginModule required
      +    doNotPrompt=true
      +    principal="HTTP/win-tc01.dev.local@DEV.LOCAL"
      +    useKeyTab=true
      +    keyTab="c:/apache-tomcat-8.5.x/conf/tomcat.keytab"
      +    storeKey=true;
      +};
      +
      +com.sun.security.jgss.krb5.accept {
      +    com.sun.security.auth.module.Krb5LoginModule required
      +    doNotPrompt=true
      +    principal="HTTP/win-tc01.dev.local@DEV.LOCAL"
      +    useKeyTab=true
      +    keyTab="c:/apache-tomcat-8.5.x/conf/tomcat.keytab"
      +    storeKey=true;
      +};
      + The location of this file can be changed by setting the + java.security.auth.login.config system property. The LoginModule + used is a JVM specific one so ensure that the LoginModule specified matches + the JVM being used. The name of the login configuration must match the + value used by the authentication + valve.
    • +
    +

    The SPNEGO authenticator will work with any + Realm but if used with the JNDI Realm, by default the JNDI Realm will use + the user's delegated credentials to connect to the Active Directory. +

    +

    The above steps have been tested on a Tomcat server running Windows Server + 2008 R2 64-bit Standard with an Oracle 1.6.0_24 64-bit JDK.

    +
    + +

    Tomcat instance (Linux server)

    +

    This was tested with:

    +
      +
    • Java 1.7.0, update 45, 64-bit
    • +
    • Ubuntu Server 12.04.3 LTS 64-bit
    • +
    • Tomcat 8.0.x (r1546570)
    • +
    +

    It should work with any Tomcat 8 release although it is recommended that + the latest stable release is used.

    +

    The configuration is the same as for Windows but with the following + changes:

    +
      +
    • The Linux server does not have to be part of the Windows domain.
    • +
    • The path to the keytab file in krb5.ini and jaas.conf should be updated + to reflect the path to the keytab file on the Linux server using Linux + style file paths (e.g. /usr/local/tomcat/...).
    • +
    +
    + +

    Web application

    +

    The web application needs to be configured to the use Tomcat specific + authentication method of SPNEGO (rather than BASIC etc.) in + web.xml. As with the other authenticators, behaviour can be customised by + explicitly configuring the + authentication valve and setting attributes on the Valve.

    +
    + +

    Client

    +

    The client must be configured to use Kerberos authentication. For Internet + Explorer this means making sure that the Tomcat instance is in the "Local + intranet" security domain and that it is configured (Tools > Internet + Options > Advanced) with integrated Windows authentication enabled. Note that + this will not work if you use the same machine for the client + and the Tomcat instance as Internet Explorer will use the unsupported NTLM + protocol.

    +
    + + + +

    Third party libraries

    + +

    Waffle

    +

    Full details of this solution can be found through the + Waffle web site. The + key features are:

    +
      +
    • Drop-in solution
    • +
    • Simple configuration (no JAAS or Kerberos keytab configuration required) +
    • +
    • Uses a native library
    • +
    +
    + +

    Spring Security - Kerberos Extension

    +

    Full details of this solution can be found through the + Kerberos extension web site. The key features are:

    +
      +
    • Extension to Spring Security
    • +
    • Requires a Kerberos keytab file to be generated
    • +
    • Pure Java solution
    • +
    +
    + +

    SPNEGO project at SourceForge

    +

    Full details of this solution can be found through the + project + site. The key features are:

    +
      +
    • Uses Kerberos
    • +
    • Pure Java solution
    • +
    +
    + +

    Jespa

    +

    Full details of this solution can be found through the + project web site. The key + features are:

    +
      +
    • Pure Java solution
    • +
    • Advanced Active Directory integration
    • +
    +
    +

    Reverse proxies

    + +

    Microsoft IIS

    +

    There are three steps to configuring IIS to provide Windows authentication. + They are:

    +
      +
    1. Configure IIS as a reverse proxy for Tomcat (see the + + IIS Web Server How-To).
    2. +
    3. Configure IIS to use Windows authentication
    4. +
    5. Configure Tomcat to use the authentication user information from IIS by + setting the tomcatAuthentication attribute on the + AJP connector to false. Alternatively, set the + tomcatAuthorization attribute to true to allow IIS to + authenticate, while Tomcat performs the authorization.
    6. +
    +
    + +

    Apache httpd

    +

    Apache httpd does not support Windows authentication out of the box but + there are a number of third-party modules that can be used. These include:

    +
      +
    1. mod_auth_sspi for use on Windows platforms.
    2. +
    3. mod_auth_ntlm_winbind for non-Windows platforms. Known to + work with httpd 2.0.x on 32-bit platforms. Some users have reported stability + issues with both httpd 2.2.x builds and 64-bit Linux builds.
    4. +
    +

    There are three steps to configuring httpd to provide Windows + authentication. They are:

    +
      +
    1. Configure httpd as a reverse proxy for Tomcat (see the + + Apache httpd Web Server How-To).
    2. +
    3. Configure httpd to use Windows authentication
    4. +
    5. Configure Tomcat to use the authentication user information from httpd by + setting the tomcatAuthentication attribute on the + AJP connector to false.
    6. +
    +
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/docs/windows-service-howto.html b/tomcat/docs/windows-service-howto.html new file mode 100644 index 0000000..bd348b8 --- /dev/null +++ b/tomcat/docs/windows-service-howto.html @@ -0,0 +1,483 @@ + +Apache Tomcat 8 (8.5.43) - Windows Service How-To

    Windows Service How-To

    Table of Contents

    Tomcat service application

    +

    + Tomcat8 is a service application for running Tomcat + 8 as a Windows service. +

    +

    Tomcat monitor application

    +

    + Tomcat8w is a GUI application for monitoring and + configuring Tomcat services. +

    +

    The available command line options are:

    + + + + + + + + + + +
    //ES//Edit service configurationThis is the default operation. It is called if the no option is + provided but the executable is renamed to servicenameW.exe
    //MS//Monitor servicePut the icon in the system tray
    + +

    Command line arguments

    +

    + Each command line directive is in the form of //XX//ServiceName +

    +

    The available command line options are:

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    //TS//Run the service as console applicationThis is the default operation. It is called if the no option is + provided. The ServiceName is the name of the executable without + exe suffix, meaning Tomcat8
    //RS//Run the serviceCalled only from ServiceManager
    //SS//Stop the service
    //US//Update service parameters
    //IS//Install service
    //DS//Delete serviceStops the service if running
    + +

    Command line parameters

    +

    + Each command line parameter is prefixed with --. If the command line + parameter is prefixed with ++ then it's value will be appended to the + existing option. + If the environment variable with the same name as command line parameter but + prefixed with PR_ exists it will take precedence. + For example:

    +
    set PR_CLASSPATH=xx.jar
    + +

    is equivalent to providing

    +
    --Classpath=xx.jar
    +

    as command line parameter.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    ParameterNameDefaultDescription
    --DescriptionService name description (maximum 1024 characters)
    --DisplayNameServiceNameService display name
    --Installprocrun.exe //RS//ServiceNameInstall image
    --StartupmanualService startup mode can be either auto or manual
    --DependsOnList of services that this service depend on. Dependent services + are separated using either # or ; characters
    --EnvironmentList of environment variables that will be provided to the service + in the form key=value. They are separated using either + # or ; characters. If you need to use either the # + or ; character within a value then the entire value must be + enclosed inside single quotes.
    --UserUser account used for running executable. It is used only for + StartMode java or exe and enables running applications + as service under account without LogonAsService privilege.
    --PasswordPassword for user account set by --User parameter
    --JavaHomeJAVA_HOMESet a different JAVA_HOME than defined by JAVA_HOME environment + variable
    --JvmautoUse either auto (i.e. find the JVM from the Windows registry) + or specify the full path to the jvm.dll. + You can use the environment variable expansion here.
    --JvmOptions-XrsList of options in the form of -D or -X that will be + passed to the JVM. The options are separated using either + # or ; characters. If you need to embed either # or + ; characters, put them inside single quotes. (Not used in + exe mode.)
    --JvmOptions9List of options in the form of -D or -X that will be + passed to the JVM when running on Java 9 or later. The options are + separated using either # or ; characters. If you need to + embed either # or ; characters, put them inside single + quotes. (Not used in exe mode.)
    --ClasspathSet the Java classpath. (Not used in exe mode.)
    --JvmMsInitial memory pool size in MB. (Not used in exe mode.)
    --JvmMxMaximum memory pool size in MB. (Not used in exe mode.)
    --JvmSsThread stack size in KB. (Not used in exe mode.)
    --StartModeOne of jvm, Java or exe. The modes are: +
      +
    • jvm - start Java in-process. Depends on jvm.dll, see --Jvm.
    • +
    • Java - same as exe, but automatically uses the default Java + executable, i.e. %JAVA_HOME%\bin\java.exe. Make sure JAVA_HOME is set + correctly, or use --JavaHome to provide the correct location. + If neither is set, procrun will try to find the default JDK (not JRE) + from the Windows registry.
    • +
    • exe - run the image as a separate process
    • +
    +
    --StartImageExecutable that will be run. Only applies to exe mode.
    --StartPathWorking path for the start image executable.
    --StartClassMainClass that contains the startup method. Applies to the jvm and + Java modes. (Not used in exe mode.)
    --StartMethodmainMethod name if differs then main
    --StartParamsList of parameters that will be passed to either StartImage or + StartClass. Parameters are separated using either # or + ; character.
    --StopModeOne of jvm, Java or exe. See --StartMode + for further details.
    --StopImageExecutable that will be run on Stop service signal. Only applies to + exe mode.
    --StopPathWorking path for the stop image executable. Does not apply to jvm + mode.
    --StopClassMainClass that will be used on Stop service signal. Applies to the + jvm and Java modes.
    --StopMethodmainMethod name if differs then main
    --StopParamsList of parameters that will be passed to either StopImage or + StopClass. Parameters are separated using either # or + ; character.
    --StopTimeoutNo TimeoutDefines the timeout in seconds that procrun waits for service to + exit gracefully.
    --LogPath%SystemRoot%\System32\LogFiles\ApacheDefines the path for logging. Creates the directory if necessary.
    --LogPrefixcommons-daemonDefines the service log filename prefix. The log file is created in the + LogPath directory with .YEAR-MONTH-DAY.log suffix
    --LogLevelInfoDefines the logging level and can be either Error, + Info, Warn or Debug. (Case insensitive).
    --StdOutputRedirected stdout filename. + If named auto then file is created inside LogPath with the + name service-stdout.YEAR-MONTH-DAY.log.
    --StdErrorRedirected stderr filename. + If named auto then file is created inside LogPath with the + name service-stderr.YEAR-MONTH-DAY.log.
    --PidFileDefines the file name for storing the running process id. Actual file is + created in the LogPath directory
    + +

    Installing services

    +

    +The safest way to manually install the service is to use the provided +service.bat script. Administrator privileges are required to run this +script. If necessary, you can use the /user switch to specify +a user to use for the installation of the service. +

    +

    +NOTE: On Windows Vista or any later operating system with User +Account Control (UAC) enabled you will be asked for additional privileges +when 'Tomcat8.exe' is launched by the script.
    +If you want to pass additional options to service installer as +PR_* environment variables, you have to either configure them +globally in OS, or launch the program that sets them with elevated privileges +(e.g. right-click on cmd.exe and select "Run as administrator"; on Windows 8 +(or later) or Windows Server 2012 (or later), you can open an elevated command +prompt for the current directory from the Explorer +by clicking on the "File" menu bar). See issue 56143 for details. +

    + +
    Install the service named 'Tomcat8'
    +C:\> service.bat install
    + +

    There is a 2nd optional parameter that lets you specify the name of the +service, as displayed in Windows services.

    + +
    Install the service named 'MyService'
    +C:\> service.bat install MyService
    + +

    +If using tomcat8.exe, you need to use the //IS// parameter.

    + +
    Install the service named 'Tomcat8'
    +C:\> tomcat8 //IS//Tomcat8 --DisplayName="Apache Tomcat 8" ^
    +     --Install="C:\Program Files\Tomcat\bin\tomcat8.exe" --Jvm=auto ^
    +     --StartMode=jvm --StopMode=jvm ^
    +     --StartClass=org.apache.catalina.startup.Bootstrap --StartParams=start ^
    +     --StopClass=org.apache.catalina.startup.Bootstrap --StopParams=stop
    + +

    Updating services

    +

    +To update the service parameters, you need to use the //US// parameter. +

    + +
    Update the service named 'Tomcat8'
    +C:\> tomcat8 //US//Tomcat8 --Description="Apache Tomcat Server - https://tomcat.apache.org/ " ^
    +     --Startup=auto --Classpath=%JAVA_HOME%\lib\tools.jar;%CATALINA_HOME%\bin\bootstrap.jar
    + +

    If you gave the service an optional name, you need to specify it like this: +

    + +
    Update the service named 'MyService'
    +C:\> tomcat8 //US//MyService --Description="Apache Tomcat Server - https://tomcat.apache.org/ " ^
    +     --Startup=auto --Classpath=%JAVA_HOME%\lib\tools.jar;%CATALINA_HOME%\bin\bootstrap.jar
    + +

    Removing services

    +

    +To remove the service, you need to use the //DS// parameter.
    +If the service is running it will be stopped and then deleted.

    + +
    Remove the service named 'Tomcat8'
    +C:\> tomcat8 //DS//Tomcat8
    + +

    If you gave the service an optional name, you need to specify it like this: +

    + +
    Remove the service named 'MyService'
    +C:\> tomcat8 //DS//MyService
    + +

    Debugging services

    +

    +To run the service in console mode, you need to use the //TS// parameter. +The service shutdown can be initiated by pressing CTRL+C or +CTRL+BREAK. +If you rename the tomcat8.exe to testservice.exe then you can just execute the +testservice.exe and this command mode will be executed by default.

    + +
    Run the service named 'Tomcat8' in console mode
    +C:\> tomcat8 //TS//Tomcat8 [additional arguments]
    +Or simply execute:
    +C:\> tomcat8
    + +

    Multiple Instances

    +

    +Tomcat supports installation of multiple instances. You can have a single +installation of Tomcat with multiple instances running on different IP/port +combinations, or multiple Tomcat versions, each running one or more instances on +different IP/ports.

    +

    +Each instance folder will need the following structure: +

    +
      +
    • conf
    • +
    • logs
    • +
    • temp
    • +
    • webapps
    • +
    • work
    • +
    +

    +At a minimum, conf should contain a copy of the following files from +CATALINA_HOME\conf\. Any files not copied and edited, will be picked up by +default from CATALINA_HOME\conf, i.e. CATALINA_BASE\conf files override defaults +from CATALINA_HOME\conf.

    +
      +
    • server.xml
    • +
    • web.xml
    • +
    +

    +You must edit CATALINA_BASE\conf\server.xml to specify a unique IP/port for the +instance to listen on. Find the line that contains +<Connector port="8080" ... and add an address attribute and/or +update the port number so as to specify a unique IP/port combination.

    +

    +To install an instance, first set the CATALINA_HOME environment variable to the +name of the Tomcat installation directory. Then create a second environment +variable CATALINA_BASE and point this to the instance folder. Then run +"service.bat install" command specifying a service name.

    + +
    set CATALINA_HOME=c:\tomcat_8
    +set CATALINA_BASE=c:\tomcat_8\instances\instance1
    +service.bat install instance1
    + +

    +To modify the service settings, you can run tomcat8w //ES//instance1. +

    +

    +For additional instances, create additional instance folder, update the +CATALINA_BASE environment variable, and run the "service.bat install" again.

    + +
    set CATALINA_BASE=c:\tomcat_8\instances\instance2
    +service.bat install instance2
    + +

    + Comments +

    Notice: This comments section collects your suggestions + on improving documentation for Apache Tomcat.

    + If you have trouble and need help, read + Find Help page + and ask your question on the tomcat-users + mailing list. + Do not ask such questions here. This is not a Q&A section.

    + The Apache Comments System is explained here. + Comments may be removed by our moderators if they are either + implemented or considered invalid/off-topic. +

    \ No newline at end of file diff --git a/tomcat/examples/WEB-INF/classes/CookieExample.class b/tomcat/examples/WEB-INF/classes/CookieExample.class new file mode 100644 index 0000000..01a6da9 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/CookieExample.class differ diff --git a/tomcat/examples/WEB-INF/classes/CookieExample.java b/tomcat/examples/WEB-INF/classes/CookieExample.java new file mode 100644 index 0000000..c62463b --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/CookieExample.java @@ -0,0 +1,142 @@ +/* +* 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. +*/ + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.ResourceBundle; + +import javax.servlet.ServletException; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import util.CookieFilter; +import util.HTMLFilter; + +/** + * Example servlet showing request headers + * + * @author James Duncan Davidson + */ + +public class CookieExample extends HttpServlet { + + private static final long serialVersionUID = 1L; + + private static final ResourceBundle RB = ResourceBundle.getBundle("LocalStrings"); + + @Override + public void doGet(HttpServletRequest request, + HttpServletResponse response) + throws IOException, ServletException + { + + String cookieName = request.getParameter("cookiename"); + String cookieValue = request.getParameter("cookievalue"); + Cookie aCookie = null; + if (cookieName != null && cookieValue != null) { + aCookie = new Cookie(cookieName, cookieValue); + aCookie.setPath(request.getContextPath() + "/"); + response.addCookie(aCookie); + } + + response.setContentType("text/html"); + response.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + out.println(""); + out.println(""); + out.println(""); + + String title = RB.getString("cookies.title"); + out.println("" + title + ""); + out.println(""); + out.println(""); + + // relative links + + // XXX + // making these absolute till we work out the + // addition of a PathInfo issue + + out.println(""); + out.println("\"view"); + out.println(""); + out.println("\"return\""); + + out.println("

    " + title + "

    "); + + Cookie[] cookies = request.getCookies(); + if ((cookies != null) && (cookies.length > 0)) { + HttpSession session = request.getSession(false); + String sessionId = null; + if (session != null) { + sessionId = session.getId(); + } + out.println(RB.getString("cookies.cookies") + "
    "); + for (int i = 0; i < cookies.length; i++) { + Cookie cookie = cookies[i]; + String cName = cookie.getName(); + String cValue = cookie.getValue(); + out.print("Cookie Name: " + HTMLFilter.filter(cName) + "
    "); + out.println(" Cookie Value: " + + HTMLFilter.filter(CookieFilter.filter(cName, cValue, sessionId)) + + "

    "); + } + } else { + out.println(RB.getString("cookies.no-cookies")); + } + + if (aCookie != null) { + out.println("

    "); + out.println(RB.getString("cookies.set") + "
    "); + out.print(RB.getString("cookies.name") + " " + + HTMLFilter.filter(cookieName) + "
    "); + out.print(RB.getString("cookies.value") + " " + + HTMLFilter.filter(cookieValue)); + } + + out.println("

    "); + out.println(RB.getString("cookies.make-cookie") + "
    "); + out.print("

    "); + out.print(RB.getString("cookies.name") + " "); + out.println("
    "); + out.print(RB.getString("cookies.value") + " "); + out.println("
    "); + out.println("
    "); + + + out.println(""); + out.println(""); + } + + @Override + public void doPost(HttpServletRequest request, + HttpServletResponse response) + throws IOException, ServletException + { + doGet(request, response); + } + +} + + diff --git a/tomcat/examples/WEB-INF/classes/HelloWorldExample.class b/tomcat/examples/WEB-INF/classes/HelloWorldExample.class new file mode 100644 index 0000000..4b83e7c Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/HelloWorldExample.class differ diff --git a/tomcat/examples/WEB-INF/classes/HelloWorldExample.java b/tomcat/examples/WEB-INF/classes/HelloWorldExample.java new file mode 100644 index 0000000..4a75a4d --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/HelloWorldExample.java @@ -0,0 +1,79 @@ +/* +* 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. +*/ +import java.io.IOException; +import java.io.PrintWriter; +import java.util.ResourceBundle; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * The simplest possible servlet. + * + * @author James Duncan Davidson + */ + +public class HelloWorldExample extends HttpServlet { + + private static final long serialVersionUID = 1L; + + @Override + public void doGet(HttpServletRequest request, + HttpServletResponse response) + throws IOException, ServletException + { + ResourceBundle rb = + ResourceBundle.getBundle("LocalStrings",request.getLocale()); + response.setContentType("text/html"); + response.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + + out.println(""); + out.println(""); + out.println(""); + + String title = rb.getString("helloworld.title"); + + out.println("" + title + ""); + out.println(""); + out.println(""); + + // note that all links are created to be relative. this + // ensures that we can move the web application that this + // servlet belongs to a different place in the url + // tree and not have any harmful side effects. + + // XXX + // making these absolute till we work out the + // addition of a PathInfo issue + + out.println(""); + out.println("\"view"); + out.println(""); + out.println("\"return\""); + out.println("

    " + title + "

    "); + out.println(""); + out.println(""); + } +} + + + diff --git a/tomcat/examples/WEB-INF/classes/LocalStrings.properties b/tomcat/examples/WEB-INF/classes/LocalStrings.properties new file mode 100644 index 0000000..2791a66 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/LocalStrings.properties @@ -0,0 +1,48 @@ +# 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. + +cookies.cookies=Your browser is sending the following cookies: +cookies.make-cookie=Create a cookie to send to your browser +cookies.name=Name: +cookies.no-cookies=Your browser isn't sending any cookies +cookies.set=You just sent the following cookie to your browser: +cookies.title=Cookies Example +cookies.value=Value: + +helloworld.title=Hello World! + +requestheader.title=Request Header Example + +requestinfo.label.method=Method: +requestinfo.label.pathinfo=Path Info: +requestinfo.label.protocol=Protocol: +requestinfo.label.remoteaddr=Remote Address: +requestinfo.label.requesturi=Request URI: +requestinfo.title=Request Information Example + +requestparams.firstname=First Name: +requestparams.lastname=Last Name: +requestparams.no-params=No Parameters, Please enter some +requestparams.params-in-req=Parameters in this request: +requestparams.title=Request Parameters Example + +sessions.adddata=Add data to your session +sessions.created=Created: +sessions.data=The following data is in your session: +sessions.dataname=Name of Session Attribute: +sessions.datavalue=Value of Session Attribute: +sessions.id=Session ID: +sessions.lastaccessed=Last Accessed: +sessions.title=Sessions Example diff --git a/tomcat/examples/WEB-INF/classes/LocalStrings_es.properties b/tomcat/examples/WEB-INF/classes/LocalStrings_es.properties new file mode 100644 index 0000000..0cbe29b --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/LocalStrings_es.properties @@ -0,0 +1,48 @@ +# 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. + +cookies.cookies=Tu navegador est\u00e1 enviando los siguientes cookies: +cookies.make-cookie=Crea un cookie para enviarlo a tu navegador +cookies.name=Nombre: +cookies.no-cookies=Tu navegador no est\u00e1 enviando cookies +cookies.set=Acabas de enviar a tu navegador estos cookies: +cookies.title=Ejemplo de Cookies +cookies.value=Valor: + +helloworld.title=Hola Mundo! + +requestheader.title=Ejemplo de Cabecera de Requerimiento: + +requestinfo.label.method=M\u00e9todo: +requestinfo.label.pathinfo=Info de Ruta: +requestinfo.label.protocol=Protocolo: +requestinfo.label.remoteaddr=Direccion Remota: +requestinfo.label.requesturi=URI de Requerimiento: +requestinfo.title=Ejemplo de Informacion de Requerimiento: + +requestparams.firstname=Nombre: +requestparams.lastname=Apellidos: +requestparams.no-params=No hay p\u00e1rametro. Por favor, usa alguno +requestparams.params-in-req=Par\u00e1metros en este Request: +requestparams.title=Ejemplo de solicitud con par\u00e1metros: + +sessions.adddata=A\u00f1ade datos a tu sesi\u00f3n: +sessions.created=Creado: +sessions.data=Lo siguientes datos est\u00e1n en tu sesi\u00f3n: +sessions.dataname=Nombre del atributo de sesi\u00f3n: +sessions.datavalue=Valor del atributo de sesi\u00f3n: +sessions.id=ID de Sesi\u00f3n: +sessions.lastaccessed=Ultimo Acceso: +sessions.title=Ejemplo de Sesiones diff --git a/tomcat/examples/WEB-INF/classes/LocalStrings_fr.properties b/tomcat/examples/WEB-INF/classes/LocalStrings_fr.properties new file mode 100644 index 0000000..729884c --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/LocalStrings_fr.properties @@ -0,0 +1,48 @@ +# 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. + +cookies.cookies=Votre navigateur retourne les cookies suivant: +cookies.make-cookie=Cr\u00e9ation d'un cookie \u00e0 retourner \u00e0 votre navigateur +cookies.name=Nom: +cookies.no-cookies=Votre navigateur ne retourne aucun cookie +cookies.set=Vous venez d'envoyer le cookie suivant \u00e0 votre navigateur: +cookies.title=Exemple d'utilisation de Cookies +cookies.value=Valeur: + +helloworld.title=Salut le Monde! + +requestheader.title=Exemple d'information sur les ent\u00eates de requ\u00eate + +requestinfo.label.method=M\u00e9thode: +requestinfo.label.pathinfo=Info de chemin: +requestinfo.label.protocol=Protocole: +requestinfo.label.remoteaddr=Adresse distante: +requestinfo.label.requesturi=URI de requ\u00eate: +requestinfo.title=Exemple d'information sur la requ\u00eate + +requestparams.firstname=Pr\u00e9nom: +requestparams.lastname=Nom: +requestparams.no-params=Pas de param\u00eatre, merci d'en saisir quelques-uns +requestparams.params-in-req=Param\u00eatres dans la requ\u00eate: +requestparams.title=Exemple de requ\u00eate avec param\u00e8tres + +sessions.adddata=Ajouter des donn\u00e9es \u00e0 votre session +sessions.created=Cr\u00e9e le: +sessions.data=Les donn\u00e9es existantes dans votre session: +sessions.dataname=Nom de l'Attribut de Session: +sessions.datavalue=Valeur de l'Attribut de Session: +sessions.id=ID de Session: +sessions.lastaccessed=Dernier acc\u00e8s: +sessions.title=Exemple de Sessions diff --git a/tomcat/examples/WEB-INF/classes/LocalStrings_pt.properties b/tomcat/examples/WEB-INF/classes/LocalStrings_pt.properties new file mode 100644 index 0000000..b432741 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/LocalStrings_pt.properties @@ -0,0 +1,48 @@ +# 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. + +cookies.cookies=O se browser esta a enviar os seguintes cookies: +cookies.make-cookie=Crie um cookie para enviar para o seu browser +cookies.name=Nome: +cookies.no-cookies=O seu browser nao esta a enviar nenhuns cookies +cookies.set=Acabou de enviar o seguinte cookie para o seu browser: +cookies.title=CExamplo de Cookies +cookies.value=Valor: + +helloworld.title=Ola Mundo! + +requestheader.title=Exemplo da Cebeceira do Pedido + +requestinfo.label.method=Metodo: +requestinfo.label.pathinfo=Informacao do Caminho: +requestinfo.label.protocol=Protocolo: +requestinfo.label.remoteaddr=Endereco Remoto: +requestinfo.label.requesturi=URI do Pedido: +requestinfo.title=Exemplo da Informacao do Pedido + +requestparams.firstname=Primeiro Nome: +requestparams.lastname=Apelido: +requestparams.no-params=Sem Parametros, Por favor entre alguns +requestparams.params-in-req=Parametros neste pedido: +requestparams.title=Examplo de Parametros do Pedido + +sessions.adddata=Adicione data a sua sessao +sessions.created=Criada: +sessions.data=Os seguintes dados fazem parte da sua sessao: +sessions.dataname=Nome do atributo da sessao: +sessions.datavalue=Valor do atributo da Sessao: +sessions.id=Identificador da Sessao: +sessions.lastaccessed=Ultima vez acedida: +sessions.title=Examplo de sessoes diff --git a/tomcat/examples/WEB-INF/classes/RequestHeaderExample.class b/tomcat/examples/WEB-INF/classes/RequestHeaderExample.class new file mode 100644 index 0000000..d97595c Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/RequestHeaderExample.class differ diff --git a/tomcat/examples/WEB-INF/classes/RequestHeaderExample.java b/tomcat/examples/WEB-INF/classes/RequestHeaderExample.java new file mode 100644 index 0000000..79e7bac --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/RequestHeaderExample.java @@ -0,0 +1,109 @@ +/* +* 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. +*/ + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Enumeration; +import java.util.Locale; +import java.util.ResourceBundle; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import util.CookieFilter; +import util.HTMLFilter; + +/** + * Example servlet showing request headers + * + * @author James Duncan Davidson + */ + +public class RequestHeaderExample extends HttpServlet { + + private static final long serialVersionUID = 1L; + + private static final ResourceBundle RB = ResourceBundle.getBundle("LocalStrings"); + + @Override + public void doGet(HttpServletRequest request, + HttpServletResponse response) + throws IOException, ServletException + { + response.setContentType("text/html"); + response.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + out.println(""); + out.println(""); + out.println(""); + + String title = RB.getString("requestheader.title"); + out.println("" + title + ""); + out.println(""); + out.println(""); + + // all links relative + + // XXX + // making these absolute till we work out the + // addition of a PathInfo issue + + out.println(""); + out.println("\"view"); + out.println(""); + out.println("\"return\""); + + out.println("

    " + title + "

    "); + out.println(""); + Enumeration e = request.getHeaderNames(); + while (e.hasMoreElements()) { + String headerName = e.nextElement(); + String headerValue = request.getHeader(headerName); + out.println(""); + } + out.println("
    "); + out.println(HTMLFilter.filter(headerName)); + out.println(""); + if (headerName.toLowerCase(Locale.ENGLISH).contains("cookie")) { + HttpSession session = request.getSession(false); + String sessionId = null; + if (session != null) { + sessionId = session.getId(); + } + out.println(HTMLFilter.filter(CookieFilter.filter(headerValue, sessionId))); + } else { + out.println(HTMLFilter.filter(headerValue)); + } + out.println("
    "); + } + + @Override + public void doPost(HttpServletRequest request, + HttpServletResponse response) + throws IOException, ServletException + { + doGet(request, response); + } + +} + diff --git a/tomcat/examples/WEB-INF/classes/RequestInfoExample.class b/tomcat/examples/WEB-INF/classes/RequestInfoExample.class new file mode 100644 index 0000000..3b8df5c Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/RequestInfoExample.class differ diff --git a/tomcat/examples/WEB-INF/classes/RequestInfoExample.java b/tomcat/examples/WEB-INF/classes/RequestInfoExample.java new file mode 100644 index 0000000..952e501 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/RequestInfoExample.java @@ -0,0 +1,118 @@ +/* +* 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. +*/ + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.ResourceBundle; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import util.HTMLFilter; + +/** + * Example servlet showing request information. + * + * @author James Duncan Davidson + */ + +public class RequestInfoExample extends HttpServlet { + + private static final long serialVersionUID = 1L; + + private static final ResourceBundle RB = ResourceBundle.getBundle("LocalStrings"); + + @Override + public void doGet(HttpServletRequest request, + HttpServletResponse response) + throws IOException, ServletException + { + response.setContentType("text/html"); + response.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + out.println(""); + out.println(""); + out.println(""); + + String title = RB.getString("requestinfo.title"); + out.println("" + title + ""); + out.println(""); + out.println(""); + + // img stuff not req'd for source code html showing + // all links relative! + + // XXX + // making these absolute till we work out the + // addition of a PathInfo issue + + out.println(""); + out.println("\"view"); + out.println(""); + out.println("\"return\""); + + out.println("

    " + title + "

    "); + out.println(""); + + String cipherSuite= + (String)request.getAttribute("javax.servlet.request.cipher_suite"); + if(cipherSuite!=null){ + out.println(""); + } + + out.println("
    "); + out.println(RB.getString("requestinfo.label.method")); + out.println(""); + out.println(HTMLFilter.filter(request.getMethod())); + out.println("
    "); + out.println(RB.getString("requestinfo.label.requesturi")); + out.println(""); + out.println(HTMLFilter.filter(request.getRequestURI())); + out.println("
    "); + out.println(RB.getString("requestinfo.label.protocol")); + out.println(""); + out.println(HTMLFilter.filter(request.getProtocol())); + out.println("
    "); + out.println(RB.getString("requestinfo.label.pathinfo")); + out.println(""); + out.println(HTMLFilter.filter(request.getPathInfo())); + out.println("
    "); + out.println(RB.getString("requestinfo.label.remoteaddr")); + out.println(""); + out.println(HTMLFilter.filter(request.getRemoteAddr())); + out.println("
    "); + out.println("SSLCipherSuite:"); + out.println(""); + out.println(HTMLFilter.filter(cipherSuite)); + out.println("
    "); + } + + @Override + public void doPost(HttpServletRequest request, + HttpServletResponse response) + throws IOException, ServletException + { + doGet(request, response); + } + +} + diff --git a/tomcat/examples/WEB-INF/classes/RequestParamExample.class b/tomcat/examples/WEB-INF/classes/RequestParamExample.class new file mode 100644 index 0000000..2628337 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/RequestParamExample.class differ diff --git a/tomcat/examples/WEB-INF/classes/RequestParamExample.java b/tomcat/examples/WEB-INF/classes/RequestParamExample.java new file mode 100644 index 0000000..be07415 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/RequestParamExample.java @@ -0,0 +1,111 @@ +/* +* 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. +*/ + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.ResourceBundle; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import util.HTMLFilter; + +/** + * Example servlet showing request headers + * + * @author James Duncan Davidson + */ + +public class RequestParamExample extends HttpServlet { + + private static final long serialVersionUID = 1L; + + private static final ResourceBundle RB = ResourceBundle.getBundle("LocalStrings"); + + @Override + public void doGet(HttpServletRequest request, + HttpServletResponse response) + throws IOException, ServletException + { + response.setContentType("text/html"); + response.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + out.println(""); + out.println(""); + out.println(""); + + String title = RB.getString("requestparams.title"); + out.println("" + title + ""); + out.println(""); + out.println(""); + + // img stuff not req'd for source code html showing + + // all links relative + + // XXX + // making these absolute till we work out the + // addition of a PathInfo issue + + out.println(""); + out.println("\"view"); + out.println(""); + out.println("\"return\""); + + out.println("

    " + title + "

    "); + String firstName = request.getParameter("firstname"); + String lastName = request.getParameter("lastname"); + out.println(RB.getString("requestparams.params-in-req") + "
    "); + if (firstName != null || lastName != null) { + out.println(RB.getString("requestparams.firstname")); + out.println(" = " + HTMLFilter.filter(firstName) + "
    "); + out.println(RB.getString("requestparams.lastname")); + out.println(" = " + HTMLFilter.filter(lastName)); + } else { + out.println(RB.getString("requestparams.no-params")); + } + out.println("

    "); + out.print("

    "); + out.println(RB.getString("requestparams.firstname")); + out.println(""); + out.println("
    "); + out.println(RB.getString("requestparams.lastname")); + out.println(""); + out.println("
    "); + out.println(""); + out.println("
    "); + + out.println(""); + out.println(""); + } + + @Override + public void doPost(HttpServletRequest request, + HttpServletResponse response) + throws IOException, ServletException + { + doGet(request, response); + } + +} diff --git a/tomcat/examples/WEB-INF/classes/ServletToJsp.class b/tomcat/examples/WEB-INF/classes/ServletToJsp.class new file mode 100644 index 0000000..aecdc31 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/ServletToJsp.class differ diff --git a/tomcat/examples/WEB-INF/classes/ServletToJsp.java b/tomcat/examples/WEB-INF/classes/ServletToJsp.java new file mode 100644 index 0000000..53faba2 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/ServletToJsp.java @@ -0,0 +1,39 @@ +/* +* 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. +*/ + +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +public class ServletToJsp extends HttpServlet { + + private static final long serialVersionUID = 1L; + + @Override + public void doGet (HttpServletRequest request, + HttpServletResponse response) { + + try { + // Set the attribute and Forward to hello.jsp + request.setAttribute ("servletName", "servletToJsp"); + getServletConfig().getServletContext().getRequestDispatcher( + "/jsp/jsptoserv/hello.jsp").forward(request, response); + } catch (Exception ex) { + ex.printStackTrace (); + } + } +} diff --git a/tomcat/examples/WEB-INF/classes/SessionExample.class b/tomcat/examples/WEB-INF/classes/SessionExample.class new file mode 100644 index 0000000..383fa8d Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/SessionExample.class differ diff --git a/tomcat/examples/WEB-INF/classes/SessionExample.java b/tomcat/examples/WEB-INF/classes/SessionExample.java new file mode 100644 index 0000000..471b66b --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/SessionExample.java @@ -0,0 +1,147 @@ +/* +* 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. +*/ + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Date; +import java.util.Enumeration; +import java.util.ResourceBundle; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import util.HTMLFilter; + +/** + * Example servlet showing request headers + * + * @author James Duncan Davidson + */ + +public class SessionExample extends HttpServlet { + + private static final long serialVersionUID = 1L; + + private static final ResourceBundle RB = ResourceBundle.getBundle("LocalStrings"); + + @Override + public void doGet(HttpServletRequest request, + HttpServletResponse response) + throws IOException, ServletException + { + response.setContentType("text/html"); + response.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + out.println(""); + out.println(""); + out.println(""); + + + String title = RB.getString("sessions.title"); + out.println("" + title + ""); + out.println(""); + out.println(""); + + // img stuff not req'd for source code html showing + // relative links everywhere! + + // XXX + // making these absolute till we work out the + // addition of a PathInfo issue + + out.println(""); + out.println("\"view"); + out.println(""); + out.println("\"return\""); + + out.println("

    " + title + "

    "); + + HttpSession session = request.getSession(true); + out.println(RB.getString("sessions.id") + " " + session.getId()); + out.println("
    "); + out.println(RB.getString("sessions.created") + " "); + out.println(new Date(session.getCreationTime()) + "
    "); + out.println(RB.getString("sessions.lastaccessed") + " "); + out.println(new Date(session.getLastAccessedTime())); + + String dataName = request.getParameter("dataname"); + String dataValue = request.getParameter("datavalue"); + if (dataName != null && dataValue != null) { + session.setAttribute(dataName, dataValue); + } + + out.println("

    "); + out.println(RB.getString("sessions.data") + "
    "); + Enumeration names = session.getAttributeNames(); + while (names.hasMoreElements()) { + String name = names.nextElement(); + String value = session.getAttribute(name).toString(); + out.println(HTMLFilter.filter(name) + " = " + + HTMLFilter.filter(value) + "
    "); + } + + out.println("

    "); + out.print("

    "); + out.println(RB.getString("sessions.dataname")); + out.println(""); + out.println("
    "); + out.println(RB.getString("sessions.datavalue")); + out.println(""); + out.println("
    "); + out.println(""); + out.println("
    "); + + out.println("

    GET based form:
    "); + out.print("

    "); + out.println(RB.getString("sessions.dataname")); + out.println(""); + out.println("
    "); + out.println(RB.getString("sessions.datavalue")); + out.println(""); + out.println("
    "); + out.println(""); + out.println("
    "); + + out.print("

    URL encoded "); + + out.println(""); + out.println(""); + } + + @Override + public void doPost(HttpServletRequest request, + HttpServletResponse response) + throws IOException, ServletException + { + doGet(request, response); + } + +} diff --git a/tomcat/examples/WEB-INF/classes/async/Async0$1.class b/tomcat/examples/WEB-INF/classes/async/Async0$1.class new file mode 100644 index 0000000..e2c487b Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/async/Async0$1.class differ diff --git a/tomcat/examples/WEB-INF/classes/async/Async0.class b/tomcat/examples/WEB-INF/classes/async/Async0.class new file mode 100644 index 0000000..3597212 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/async/Async0.class differ diff --git a/tomcat/examples/WEB-INF/classes/async/Async0.java b/tomcat/examples/WEB-INF/classes/async/Async0.java new file mode 100644 index 0000000..5bc0ee4 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/async/Async0.java @@ -0,0 +1,71 @@ +/* +* 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. +*/ +package async; + +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.Date; + +import javax.servlet.AsyncContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.juli.logging.Log; +import org.apache.juli.logging.LogFactory; + +public class Async0 extends HttpServlet { + + private static final long serialVersionUID = 1L; + + private static final Log log = LogFactory.getLog(Async0.class); + + @Override + protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { + if (Boolean.TRUE.equals(req.getAttribute("dispatch"))) { + log.info("Received dispatch, completing on the worker thread."); + log.info("After complete called started:"+req.isAsyncStarted()); + Date date = new Date(System.currentTimeMillis()); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z"); + resp.getWriter().write("Async dispatch worked: " + sdf.format(date) + "\n"); + } else { + resp.setContentType("text/plain"); + final AsyncContext actx = req.startAsync(); + actx.setTimeout(Long.MAX_VALUE); + Runnable run = new Runnable() { + @Override + public void run() { + try { + req.setAttribute("dispatch", Boolean.TRUE); + Thread.currentThread().setName("Async0-Thread"); + log.info("Putting AsyncThread to sleep"); + Thread.sleep(2*1000); + log.info("Dispatching"); + actx.dispatch(); + }catch (InterruptedException x) { + log.error("Async1",x); + }catch (IllegalStateException x) { + log.error("Async1",x); + } + } + }; + Thread t = new Thread(run); + t.start(); + } + } +} diff --git a/tomcat/examples/WEB-INF/classes/async/Async1$1.class b/tomcat/examples/WEB-INF/classes/async/Async1$1.class new file mode 100644 index 0000000..1522c70 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/async/Async1$1.class differ diff --git a/tomcat/examples/WEB-INF/classes/async/Async1.class b/tomcat/examples/WEB-INF/classes/async/Async1.class new file mode 100644 index 0000000..5ecdd9a Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/async/Async1.class differ diff --git a/tomcat/examples/WEB-INF/classes/async/Async1.java b/tomcat/examples/WEB-INF/classes/async/Async1.java new file mode 100644 index 0000000..dc0dc59 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/async/Async1.java @@ -0,0 +1,62 @@ +/* +* 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. +*/ +package async; + +import java.io.IOException; + +import javax.servlet.AsyncContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.juli.logging.Log; +import org.apache.juli.logging.LogFactory; + +public class Async1 extends HttpServlet { + + private static final long serialVersionUID = 1L; + + private static final Log log = LogFactory.getLog(Async1.class); + + @Override + protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + final AsyncContext actx = req.startAsync(); + actx.setTimeout(30*1000); + Runnable run = new Runnable() { + @Override + public void run() { + try { + String path = "/jsp/async/async1.jsp"; + Thread.currentThread().setName("Async1-Thread"); + log.info("Putting AsyncThread to sleep"); + Thread.sleep(2*1000); + log.info("Dispatching to "+path); + actx.dispatch(path); + }catch (InterruptedException x) { + log.error("Async1",x); + }catch (IllegalStateException x) { + log.error("Async1",x); + } + } + }; + Thread t = new Thread(run); + t.start(); + } + + +} diff --git a/tomcat/examples/WEB-INF/classes/async/Async2$1.class b/tomcat/examples/WEB-INF/classes/async/Async2$1.class new file mode 100644 index 0000000..f47c277 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/async/Async2$1.class differ diff --git a/tomcat/examples/WEB-INF/classes/async/Async2.class b/tomcat/examples/WEB-INF/classes/async/Async2.class new file mode 100644 index 0000000..36734d8 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/async/Async2.class differ diff --git a/tomcat/examples/WEB-INF/classes/async/Async2.java b/tomcat/examples/WEB-INF/classes/async/Async2.java new file mode 100644 index 0000000..0682d62 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/async/Async2.java @@ -0,0 +1,70 @@ +/* +* 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. +*/ +package async; + +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.Date; + +import javax.servlet.AsyncContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.juli.logging.Log; +import org.apache.juli.logging.LogFactory; + +public class Async2 extends HttpServlet { + + private static final long serialVersionUID = 1L; + + private static final Log log = LogFactory.getLog(Async2.class); + + @Override + protected void service(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + final AsyncContext actx = req.startAsync(); + actx.setTimeout(30*1000); + Runnable run = new Runnable() { + @Override + public void run() { + try { + Thread.currentThread().setName("Async2-Thread"); + log.info("Putting AsyncThread to sleep"); + Thread.sleep(2*1000); + log.info("Writing data."); + Date date = new Date(System.currentTimeMillis()); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z"); + actx.getResponse().getWriter().write( + "Output from background thread. Time: " + sdf.format(date) + "\n"); + actx.complete(); + }catch (InterruptedException x) { + log.error("Async2",x); + }catch (IllegalStateException x) { + log.error("Async2",x); + }catch (IOException x) { + log.error("Async2",x); + } + } + }; + Thread t = new Thread(run); + t.start(); + } + + +} diff --git a/tomcat/examples/WEB-INF/classes/async/Async3.class b/tomcat/examples/WEB-INF/classes/async/Async3.class new file mode 100644 index 0000000..6353314 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/async/Async3.class differ diff --git a/tomcat/examples/WEB-INF/classes/async/Async3.java b/tomcat/examples/WEB-INF/classes/async/Async3.java new file mode 100644 index 0000000..e1ff5e0 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/async/Async3.java @@ -0,0 +1,39 @@ +/* +* 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. +*/ +package async; + +import java.io.IOException; + +import javax.servlet.AsyncContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +public class Async3 extends HttpServlet { + + private static final long serialVersionUID = 1L; + + @Override + protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + final AsyncContext actx = req.startAsync(); + actx.setTimeout(30*1000); + actx.dispatch("/jsp/async/async3.jsp"); + } + + +} diff --git a/tomcat/examples/WEB-INF/classes/async/AsyncStockContextListener.class b/tomcat/examples/WEB-INF/classes/async/AsyncStockContextListener.class new file mode 100644 index 0000000..b18d4ce Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/async/AsyncStockContextListener.class differ diff --git a/tomcat/examples/WEB-INF/classes/async/AsyncStockContextListener.java b/tomcat/examples/WEB-INF/classes/async/AsyncStockContextListener.java new file mode 100644 index 0000000..685ac23 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/async/AsyncStockContextListener.java @@ -0,0 +1,44 @@ +/* + * 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. + */ +package async; + +import javax.servlet.ServletContext; +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; + +/* + * Ensures the Stockticker is shut down cleanly when the context stops. This + * also covers the case when the server shuts down. + */ +public class AsyncStockContextListener implements ServletContextListener { + + public static final String STOCK_TICKER_KEY = "StockTicker"; + + @Override + public void contextInitialized(ServletContextEvent sce) { + Stockticker stockticker = new Stockticker(); + ServletContext sc = sce.getServletContext(); + sc.setAttribute(STOCK_TICKER_KEY, stockticker); + } + + @Override + public void contextDestroyed(ServletContextEvent sce) { + ServletContext sc = sce.getServletContext(); + Stockticker stockticker = (Stockticker) sc.getAttribute(STOCK_TICKER_KEY); + stockticker.shutdown(); + } +} diff --git a/tomcat/examples/WEB-INF/classes/async/AsyncStockServlet.class b/tomcat/examples/WEB-INF/classes/async/AsyncStockServlet.class new file mode 100644 index 0000000..68e6e45 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/async/AsyncStockServlet.class differ diff --git a/tomcat/examples/WEB-INF/classes/async/AsyncStockServlet.java b/tomcat/examples/WEB-INF/classes/async/AsyncStockServlet.java new file mode 100644 index 0000000..8b3ac15 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/async/AsyncStockServlet.java @@ -0,0 +1,149 @@ +/* + * 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. + */ +package async; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Iterator; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicInteger; + +import javax.servlet.AsyncContext; +import javax.servlet.AsyncEvent; +import javax.servlet.AsyncListener; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.juli.logging.Log; +import org.apache.juli.logging.LogFactory; + +import async.Stockticker.Stock; +import async.Stockticker.TickListener; + +public class AsyncStockServlet extends HttpServlet implements TickListener, AsyncListener{ + + private static final long serialVersionUID = 1L; + + private static final Log log = LogFactory.getLog(AsyncStockServlet.class); + + private static final ConcurrentLinkedQueue clients = + new ConcurrentLinkedQueue<>(); + private static final AtomicInteger clientcount = new AtomicInteger(0); + + public AsyncStockServlet() { + log.info("AsyncStockServlet created"); + } + + + @Override + protected void service(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + if (req.isAsyncStarted()) { + req.getAsyncContext().complete(); + } else if (req.isAsyncSupported()) { + AsyncContext actx = req.startAsync(); + actx.addListener(this); + resp.setContentType("text/plain"); + clients.add(actx); + if (clientcount.incrementAndGet()==1) { + Stockticker ticker = (Stockticker) req.getServletContext().getAttribute( + AsyncStockContextListener.STOCK_TICKER_KEY); + ticker.addTickListener(this); + } + } else { + new Exception("Async Not Supported").printStackTrace(); + resp.sendError(400,"Async is not supported."); + } + } + + + @Override + public void tick(Stock stock) { + Iterator it = clients.iterator(); + while (it.hasNext()) { + AsyncContext actx = it.next(); + try { + writeStock(actx, stock); + } catch (Exception e) { + // Ignore. The async error handling will deal with this. + } + } + } + + + public void writeStock(AsyncContext actx, Stock stock) throws IOException { + HttpServletResponse response = (HttpServletResponse)actx.getResponse(); + PrintWriter writer = response.getWriter(); + writer.write("STOCK#");//make client parsing easier + writer.write(stock.getSymbol()); + writer.write("#"); + writer.write(stock.getValueAsString()); + writer.write("#"); + writer.write(stock.getLastChangeAsString()); + writer.write("#"); + writer.write(String.valueOf(stock.getCnt())); + writer.write("\n"); + writer.flush(); + response.flushBuffer(); + } + + + @Override + public void shutdown() { + // The web application is shutting down. Complete any AsyncContexts + // associated with an active client. + Iterator it = clients.iterator(); + while (it.hasNext()) { + AsyncContext actx = it.next(); + try { + actx.complete(); + } catch (Exception e) { + // Ignore. The async error handling will deal with this. + } + } + } + + + @Override + public void onComplete(AsyncEvent event) throws IOException { + if (clients.remove(event.getAsyncContext()) && clientcount.decrementAndGet()==0) { + ServletContext sc = event.getAsyncContext().getRequest().getServletContext(); + Stockticker ticker = (Stockticker) sc.getAttribute( + AsyncStockContextListener.STOCK_TICKER_KEY); + ticker.removeTickListener(this); + } + } + + @Override + public void onError(AsyncEvent event) throws IOException { + event.getAsyncContext().complete(); + } + + @Override + public void onTimeout(AsyncEvent event) throws IOException { + event.getAsyncContext().complete(); + } + + + @Override + public void onStartAsync(AsyncEvent event) throws IOException { + // NOOP + } +} diff --git a/tomcat/examples/WEB-INF/classes/async/Stockticker$Stock.class b/tomcat/examples/WEB-INF/classes/async/Stockticker$Stock.class new file mode 100644 index 0000000..decef51 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/async/Stockticker$Stock.class differ diff --git a/tomcat/examples/WEB-INF/classes/async/Stockticker$TickListener.class b/tomcat/examples/WEB-INF/classes/async/Stockticker$TickListener.class new file mode 100644 index 0000000..e63e28c Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/async/Stockticker$TickListener.class differ diff --git a/tomcat/examples/WEB-INF/classes/async/Stockticker.class b/tomcat/examples/WEB-INF/classes/async/Stockticker.class new file mode 100644 index 0000000..f8fde4b Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/async/Stockticker.class differ diff --git a/tomcat/examples/WEB-INF/classes/async/Stockticker.java b/tomcat/examples/WEB-INF/classes/async/Stockticker.java new file mode 100644 index 0000000..e87744e --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/async/Stockticker.java @@ -0,0 +1,207 @@ +/* + * 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. + */ +package async; + +import java.text.DecimalFormat; +import java.util.List; +import java.util.Random; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicInteger; + +public class Stockticker implements Runnable { + public volatile boolean run = true; + protected final AtomicInteger counter = new AtomicInteger(0); + final List listeners = new CopyOnWriteArrayList<>(); + protected volatile Thread ticker = null; + protected volatile int ticknr = 0; + + public synchronized void start() { + run = true; + ticker = new Thread(this); + ticker.setName("Ticker Thread"); + ticker.start(); + } + + public synchronized void stop() { + // On context stop this can be called multiple times. + // NO-OP is the ticker thread is not set + // (i.e. stop() has already completed) + if (ticker == null) { + return; + } + run = false; + try { + ticker.join(); + }catch (InterruptedException x) { + Thread.interrupted(); + } + + ticker = null; + } + + public void shutdown() { + // Notify each listener of the shutdown. This enables them to + // trigger any necessary clean-up. + for (TickListener l : listeners) { + l.shutdown(); + } + // Wait for the thread to stop. This prevents warnings in the logs + // that the thread is still active when the context stops. + stop(); + } + + public void addTickListener(TickListener listener) { + if (listeners.add(listener)) { + if (counter.incrementAndGet()==1) start(); + } + + } + + public void removeTickListener(TickListener listener) { + if (listeners.remove(listener)) { + if (counter.decrementAndGet()==0) stop(); + } + } + + @Override + public void run() { + try { + + Stock[] stocks = new Stock[] { new Stock("GOOG", 435.43), + new Stock("YHOO", 27.88), new Stock("ASF", 1015.55), }; + Random r = new Random(System.currentTimeMillis()); + while (run) { + for (int j = 0; j < 1; j++) { + int i = r.nextInt() % 3; + if (i < 0) + i = i * (-1); + Stock stock = stocks[i]; + double change = r.nextDouble(); + boolean plus = r.nextBoolean(); + if (plus) { + stock.setValue(stock.getValue() + change); + } else { + stock.setValue(stock.getValue() - change); + } + stock.setCnt(++ticknr); + for (TickListener l : listeners) { + l.tick(stock); + } + + } + Thread.sleep(850); + } + } catch (InterruptedException ix) { + // Ignore + } catch (Exception x) { + x.printStackTrace(); + } + } + + + public static interface TickListener { + public void tick(Stock stock); + public void shutdown(); + } + + public static final class Stock implements Cloneable { + protected static final DecimalFormat df = new DecimalFormat("0.00"); + protected final String symbol; + protected double value = 0.0d; + protected double lastchange = 0.0d; + protected int cnt = 0; + + public Stock(String symbol, double initvalue) { + this.symbol = symbol; + this.value = initvalue; + } + + public void setCnt(int c) { + this.cnt = c; + } + + public int getCnt() { + return cnt; + } + + public String getSymbol() { + return symbol; + } + + public double getValue() { + return value; + } + + public void setValue(double value) { + double old = this.value; + this.value = value; + this.lastchange = value - old; + } + + public String getValueAsString() { + return df.format(value); + } + + public double getLastChange() { + return this.lastchange; + } + + public void setLastChange(double lastchange) { + this.lastchange = lastchange; + } + + public String getLastChangeAsString() { + return df.format(lastchange); + } + + @Override + public int hashCode() { + return symbol.hashCode(); + } + + @Override + public boolean equals(Object other) { + if (other instanceof Stock) { + return this.symbol.equals(((Stock) other).symbol); + } + + return false; + } + + @Override + public String toString() { + StringBuilder buf = new StringBuilder("STOCK#"); + buf.append(getSymbol()); + buf.append("#"); + buf.append(getValueAsString()); + buf.append("#"); + buf.append(getLastChangeAsString()); + buf.append("#"); + buf.append(String.valueOf(getCnt())); + return buf.toString(); + + } + + @Override + public Object clone() { + Stock s = new Stock(this.getSymbol(), this.getValue()); + s.setLastChange(this.getLastChange()); + s.setCnt(this.cnt); + return s; + } + } +} diff --git a/tomcat/examples/WEB-INF/classes/cal/Entries.class b/tomcat/examples/WEB-INF/classes/cal/Entries.class new file mode 100644 index 0000000..f3a612b Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/cal/Entries.class differ diff --git a/tomcat/examples/WEB-INF/classes/cal/Entries.java b/tomcat/examples/WEB-INF/classes/cal/Entries.java new file mode 100644 index 0000000..0286019 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/cal/Entries.java @@ -0,0 +1,60 @@ +/* + * 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. + */ +package cal; + +import java.util.Hashtable; + +import javax.servlet.http.HttpServletRequest; + +public class Entries { + + private final Hashtable entries; + private static final String[] time = { "8am", "9am", "10am", "11am", + "12pm", "1pm", "2pm", "3pm", "4pm", "5pm", "6pm", "7pm", "8pm" }; + public static final int rows = 12; + + public Entries() { + entries = new Hashtable<>(rows); + for (int i = 0; i < rows; i++) { + entries.put(time[i], new Entry(time[i])); + } + } + + public int getRows() { + return rows; + } + + public Entry getEntry(int index) { + return this.entries.get(time[index]); + } + + public int getIndex(String tm) { + for (int i = 0; i < rows; i++) + if (tm.equals(time[i])) + return i; + return -1; + } + + public void processRequest(HttpServletRequest request, String tm) { + int index = getIndex(tm); + if (index >= 0) { + String descr = request.getParameter("description"); + entries.get(time[index]).setDescription(descr); + } + } + +} diff --git a/tomcat/examples/WEB-INF/classes/cal/Entry.class b/tomcat/examples/WEB-INF/classes/cal/Entry.class new file mode 100644 index 0000000..e059797 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/cal/Entry.class differ diff --git a/tomcat/examples/WEB-INF/classes/cal/Entry.java b/tomcat/examples/WEB-INF/classes/cal/Entry.java new file mode 100644 index 0000000..68e7fdf --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/cal/Entry.java @@ -0,0 +1,53 @@ +/* + * 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. + */ + +package cal; + +public class Entry { + + final String hour; + String description; + + public Entry(String hour) { + this.hour = hour; + this.description = ""; + + } + + public String getHour() { + return this.hour; + } + + public String getColor() { + if (description.equals("")) { + return "lightblue"; + } + return "red"; + } + + public String getDescription() { + if (description.equals("")) { + return "None"; + } + return this.description; + } + + public void setDescription(String descr) { + description = descr; + } + +} diff --git a/tomcat/examples/WEB-INF/classes/cal/JspCalendar.class b/tomcat/examples/WEB-INF/classes/cal/JspCalendar.class new file mode 100644 index 0000000..986adc6 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/cal/JspCalendar.class differ diff --git a/tomcat/examples/WEB-INF/classes/cal/JspCalendar.java b/tomcat/examples/WEB-INF/classes/cal/JspCalendar.java new file mode 100644 index 0000000..f9cf20f --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/cal/JspCalendar.java @@ -0,0 +1,151 @@ +/* +* 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. +*/ + +package cal; + +import java.util.Calendar; +import java.util.Date; + +public class JspCalendar { + final Calendar calendar; + + public JspCalendar() { + calendar = Calendar.getInstance(); + Date trialTime = new Date(); + calendar.setTime(trialTime); + } + + + public int getYear() { + return calendar.get(Calendar.YEAR); + } + + public String getMonth() { + int m = getMonthInt(); + String[] months = new String [] { "January", "February", "March", + "April", "May", "June", + "July", "August", "September", + "October", "November", "December" }; + if (m > 12) + return "Unknown to Man"; + + return months[m - 1]; + + } + + public String getDay() { + int x = getDayOfWeek(); + String[] days = new String[] {"Sunday", "Monday", "Tuesday", "Wednesday", + "Thursday", "Friday", "Saturday"}; + + if (x > 7) + return "Unknown to Man"; + + return days[x - 1]; + + } + + public int getMonthInt() { + return 1 + calendar.get(Calendar.MONTH); + } + + public String getDate() { + return getMonthInt() + "/" + getDayOfMonth() + "/" + getYear(); + } + + public String getCurrentDate() { + Date dt = new Date (); + calendar.setTime (dt); + return getMonthInt() + "/" + getDayOfMonth() + "/" + getYear(); + + } + + public String getNextDate() { + calendar.set (Calendar.DAY_OF_MONTH, getDayOfMonth() + 1); + return getDate (); + } + + public String getPrevDate() { + calendar.set (Calendar.DAY_OF_MONTH, getDayOfMonth() - 1); + return getDate (); + } + + public String getTime() { + return getHour() + ":" + getMinute() + ":" + getSecond(); + } + + public int getDayOfMonth() { + return calendar.get(Calendar.DAY_OF_MONTH); + } + + public int getDayOfYear() { + return calendar.get(Calendar.DAY_OF_YEAR); + } + + public int getWeekOfYear() { + return calendar.get(Calendar.WEEK_OF_YEAR); + } + + public int getWeekOfMonth() { + return calendar.get(Calendar.WEEK_OF_MONTH); + } + + public int getDayOfWeek() { + return calendar.get(Calendar.DAY_OF_WEEK); + } + + public int getHour() { + return calendar.get(Calendar.HOUR_OF_DAY); + } + + public int getMinute() { + return calendar.get(Calendar.MINUTE); + } + + + public int getSecond() { + return calendar.get(Calendar.SECOND); + } + + + public int getEra() { + return calendar.get(Calendar.ERA); + } + + public String getUSTimeZone() { + String[] zones = new String[] {"Hawaii", "Alaskan", "Pacific", + "Mountain", "Central", "Eastern"}; + + return zones[10 + getZoneOffset()]; + } + + public int getZoneOffset() { + return calendar.get(Calendar.ZONE_OFFSET)/(60*60*1000); + } + + + public int getDSTOffset() { + return calendar.get(Calendar.DST_OFFSET)/(60*60*1000); + } + + + public int getAMPM() { + return calendar.get(Calendar.AM_PM); + } +} + + diff --git a/tomcat/examples/WEB-INF/classes/cal/TableBean.class b/tomcat/examples/WEB-INF/classes/cal/TableBean.class new file mode 100644 index 0000000..1878094 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/cal/TableBean.class differ diff --git a/tomcat/examples/WEB-INF/classes/cal/TableBean.java b/tomcat/examples/WEB-INF/classes/cal/TableBean.java new file mode 100644 index 0000000..483bd93 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/cal/TableBean.java @@ -0,0 +1,101 @@ +/* + * 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. + */ +package cal; + +import java.util.Hashtable; + +import javax.servlet.http.HttpServletRequest; + +public class TableBean { + + final Hashtable table; + final JspCalendar JspCal; + Entries entries; + String date; + String name = null; + String email = null; + boolean processError = false; + + public TableBean() { + this.table = new Hashtable<>(10); + this.JspCal = new JspCalendar(); + this.date = JspCal.getCurrentDate(); + } + + public void setName(String nm) { + this.name = nm; + } + + public String getName() { + return this.name; + } + + public void setEmail(String mail) { + this.email = mail; + } + + public String getEmail() { + return this.email; + } + + public String getDate() { + return this.date; + } + + public Entries getEntries() { + return this.entries; + } + + public void processRequest(HttpServletRequest request) { + + // Get the name and e-mail. + this.processError = false; + if (name == null || name.equals("")) + setName(request.getParameter("name")); + if (email == null || email.equals("")) + setEmail(request.getParameter("email")); + if (name == null || email == null || name.equals("") + || email.equals("")) { + this.processError = true; + return; + } + + // Get the date. + String dateR = request.getParameter("date"); + if (dateR == null) + date = JspCal.getCurrentDate(); + else if (dateR.equalsIgnoreCase("next")) + date = JspCal.getNextDate(); + else if (dateR.equalsIgnoreCase("prev")) + date = JspCal.getPrevDate(); + + entries = table.get(date); + if (entries == null) { + entries = new Entries(); + table.put(date, entries); + } + + // If time is provided add the event. + String time = request.getParameter("time"); + if (time != null) + entries.processRequest(request, time); + } + + public boolean getProcessError() { + return this.processError; + } +} diff --git a/tomcat/examples/WEB-INF/classes/checkbox/CheckTest.class b/tomcat/examples/WEB-INF/classes/checkbox/CheckTest.class new file mode 100644 index 0000000..ddedd95 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/checkbox/CheckTest.class differ diff --git a/tomcat/examples/WEB-INF/classes/checkbox/CheckTest.java b/tomcat/examples/WEB-INF/classes/checkbox/CheckTest.java new file mode 100644 index 0000000..e38269c --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/checkbox/CheckTest.java @@ -0,0 +1,31 @@ +/* +* 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. +*/ + +package checkbox; + +public class CheckTest { + + String b[] = new String[] { "1", "2", "3", "4" }; + + public String[] getFruit() { + return b; + } + + public void setFruit(String [] b) { + this.b = b; + } +} diff --git a/tomcat/examples/WEB-INF/classes/colors/ColorGameBean.class b/tomcat/examples/WEB-INF/classes/colors/ColorGameBean.class new file mode 100644 index 0000000..2b12ec4 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/colors/ColorGameBean.class differ diff --git a/tomcat/examples/WEB-INF/classes/colors/ColorGameBean.java b/tomcat/examples/WEB-INF/classes/colors/ColorGameBean.java new file mode 100644 index 0000000..7c64d94 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/colors/ColorGameBean.java @@ -0,0 +1,113 @@ +/* +* 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. +*/ +package colors; + +public class ColorGameBean { + + private String background = "yellow"; + private String foreground = "red"; + private String color1 = foreground; + private String color2 = background; + private String hint = "no"; + private int attempts = 0; + private int intval = 0; + private boolean tookHints = false; + + public void processRequest() { + + // background = "yellow"; + // foreground = "red"; + + if (! color1.equals(foreground)) { + if (color1.equalsIgnoreCase("black") || + color1.equalsIgnoreCase("cyan")) { + background = color1; + } + } + + if (! color2.equals(background)) { + if (color2.equalsIgnoreCase("black") || + color2.equalsIgnoreCase("cyan")) { + foreground = color2; + } + } + + attempts++; + } + + public void setColor2(String x) { + color2 = x; + } + + public void setColor1(String x) { + color1 = x; + } + + public void setAction(String x) { + if (!tookHints) + tookHints = x.equalsIgnoreCase("Hint"); + hint = x; + } + + public String getColor2() { + return background; + } + + public String getColor1() { + return foreground; + } + + public int getAttempts() { + return attempts; + } + + public boolean getHint() { + return hint.equalsIgnoreCase("Hint"); + } + + public boolean getSuccess() { + if (background.equalsIgnoreCase("black") || + background.equalsIgnoreCase("cyan")) { + + if (foreground.equalsIgnoreCase("black") || + foreground.equalsIgnoreCase("cyan")) { + return true; + } + return false; + } + + return false; + } + + public boolean getHintTaken() { + return tookHints; + } + + public void reset() { + foreground = "red"; + background = "yellow"; + } + + public void setIntval(int value) { + intval = value; + } + + public int getIntval() { + return intval; + } +} + diff --git a/tomcat/examples/WEB-INF/classes/compressionFilters/CompressionFilter.class b/tomcat/examples/WEB-INF/classes/compressionFilters/CompressionFilter.class new file mode 100644 index 0000000..e5a660c Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/compressionFilters/CompressionFilter.class differ diff --git a/tomcat/examples/WEB-INF/classes/compressionFilters/CompressionFilter.java b/tomcat/examples/WEB-INF/classes/compressionFilters/CompressionFilter.java new file mode 100644 index 0000000..4ffe92b --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/compressionFilters/CompressionFilter.java @@ -0,0 +1,240 @@ +/* +* 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. +*/ +package compressionFilters; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Enumeration; +import java.util.List; +import java.util.StringTokenizer; + +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; + +/** + * Implementation of javax.servlet.Filter used to compress + * the ServletResponse if it is bigger than a threshold. + * + * @author Amy Roh + * @author Dmitri Valdin + */ +public class CompressionFilter implements Filter { + + /** + * Minimal reasonable threshold. + */ + private static final int MIN_THRESHOLD = 128; + + /** + * Minimal reasonable buffer. + */ + // 8KB is what tomcat would use by default anyway + private static final int MIN_BUFFER = 8192; + + /** + * The threshold number to compress. + */ + protected int compressionThreshold = 0; + + /** + * The compression buffer size to avoid chunking. + */ + protected int compressionBuffer = 0; + + /** + * The mime types to compress. + */ + protected String[] compressionMimeTypes = {"text/html", "text/xml", "text/plain"}; + + /** + * Debug level for this filter. + */ + private int debug = 0; + + /** + * Place this filter into service. + * + * @param filterConfig The filter configuration object + */ + @Override + public void init(FilterConfig filterConfig) { + + if (filterConfig != null) { + String value = filterConfig.getInitParameter("debug"); + if (value!=null) { + debug = Integer.parseInt(value); + } + + String str = filterConfig.getInitParameter("compressionThreshold"); + if (str != null) { + compressionThreshold = Integer.parseInt(str); + if (compressionThreshold != 0 && compressionThreshold < MIN_THRESHOLD) { + if (debug > 0) { + System.out.println("compressionThreshold should be either 0 - no compression or >= " + MIN_THRESHOLD); + System.out.println("compressionThreshold set to " + MIN_THRESHOLD); + } + compressionThreshold = MIN_THRESHOLD; + } + } + + str = filterConfig.getInitParameter("compressionBuffer"); + if (str != null) { + compressionBuffer = Integer.parseInt(str); + if (compressionBuffer < MIN_BUFFER) { + if (debug > 0) { + System.out.println("compressionBuffer should be >= " + MIN_BUFFER); + System.out.println("compressionBuffer set to " + MIN_BUFFER); + } + compressionBuffer = MIN_BUFFER; + } + } + + str = filterConfig.getInitParameter("compressionMimeTypes"); + if (str != null) { + List values = new ArrayList<>(); + StringTokenizer st = new StringTokenizer(str, ","); + + while (st.hasMoreTokens()) { + String token = st.nextToken().trim(); + if (token.length() > 0) { + values.add(token); + } + } + + if (values.size() > 0) { + compressionMimeTypes = values.toArray( + new String[values.size()]); + } else { + compressionMimeTypes = null; + } + + if (debug > 0) { + System.out.println("compressionMimeTypes set to " + + Arrays.toString(compressionMimeTypes)); + } + } + } + + } + + /** + * Take this filter out of service. + */ + @Override + public void destroy() { + } + + /** + * The doFilter method of the Filter is called by the container + * each time a request/response pair is passed through the chain due + * to a client request for a resource at the end of the chain. + * The FilterChain passed into this method allows the Filter to pass on the + * request and response to the next entity in the chain.

    + * This method first examines the request to check whether the client support + * compression.
    + * It simply just pass the request and response if there is no support for + * compression.
    + * If the compression support is available, it creates a + * CompressionServletResponseWrapper object which compresses the content and + * modifies the header if the content length is big enough. + * It then invokes the next entity in the chain using the FilterChain object + * (chain.doFilter()),
    + **/ + @Override + public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain ) + throws IOException, ServletException { + + if (debug > 0) { + System.out.println("@doFilter"); + } + + if (compressionThreshold == 0) { + if (debug > 0) { + System.out.println("doFilter got called, but compressionThreshold is set to 0 - no compression"); + } + chain.doFilter(request, response); + return; + } + + boolean supportCompression = false; + if (request instanceof HttpServletRequest) { + if (debug > 1) { + System.out.println("requestURI = " + ((HttpServletRequest)request).getRequestURI()); + } + + // Are we allowed to compress ? + String s = ((HttpServletRequest)request).getParameter("gzip"); + if ("false".equals(s)) { + if (debug > 0) { + System.out.println("got parameter gzip=false --> don't compress, just chain filter"); + } + chain.doFilter(request, response); + return; + } + + Enumeration e = + ((HttpServletRequest)request).getHeaders("Accept-Encoding"); + while (e.hasMoreElements()) { + String name = e.nextElement(); + if (name.indexOf("gzip") != -1) { + if (debug > 0) { + System.out.println("supports compression"); + } + supportCompression = true; + } else { + if (debug > 0) { + System.out.println("no support for compression"); + } + } + } + } + + if (supportCompression) { + if (response instanceof HttpServletResponse) { + CompressionServletResponseWrapper wrappedResponse = + new CompressionServletResponseWrapper((HttpServletResponse)response); + wrappedResponse.setDebugLevel(debug); + wrappedResponse.setCompressionThreshold(compressionThreshold); + wrappedResponse.setCompressionBuffer(compressionBuffer); + wrappedResponse.setCompressionMimeTypes(compressionMimeTypes); + if (debug > 0) { + System.out.println("doFilter gets called with compression"); + } + try { + chain.doFilter(request, wrappedResponse); + } finally { + wrappedResponse.finishResponse(); + } + return; + } + } else { + if (debug > 0) { + System.out.println("doFilter gets called w/o compression"); + } + chain.doFilter(request, response); + return; + } + } +} + diff --git a/tomcat/examples/WEB-INF/classes/compressionFilters/CompressionFilterTestServlet.class b/tomcat/examples/WEB-INF/classes/compressionFilters/CompressionFilterTestServlet.class new file mode 100644 index 0000000..4fb6896 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/compressionFilters/CompressionFilterTestServlet.class differ diff --git a/tomcat/examples/WEB-INF/classes/compressionFilters/CompressionFilterTestServlet.java b/tomcat/examples/WEB-INF/classes/compressionFilters/CompressionFilterTestServlet.java new file mode 100644 index 0000000..af1a0b9 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/compressionFilters/CompressionFilterTestServlet.java @@ -0,0 +1,66 @@ +/* +* 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. +*/ +package compressionFilters; + +import java.io.IOException; +import java.util.Enumeration; + +import javax.servlet.ServletException; +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * Very Simple test servlet to test compression filter + * @author Amy Roh + */ +public class CompressionFilterTestServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + + @Override + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + + ServletOutputStream out = response.getOutputStream(); + response.setContentType("text/plain"); + + Enumeration e = request.getHeaders("Accept-Encoding"); + while (e.hasMoreElements()) { + String name = e.nextElement(); + out.println(name); + if (name.indexOf("gzip") != -1) { + out.println("gzip supported -- able to compress"); + } + else { + out.println("gzip not supported"); + } + } + + + out.println("Compression Filter Test Servlet"); + out.println("Minimum content length for compression is 128 bytes"); + out.println("********** 32 bytes **********"); + out.println("********** 32 bytes **********"); + out.println("********** 32 bytes **********"); + out.println("********** 32 bytes **********"); + out.close(); + } + +} + diff --git a/tomcat/examples/WEB-INF/classes/compressionFilters/CompressionResponseStream.class b/tomcat/examples/WEB-INF/classes/compressionFilters/CompressionResponseStream.class new file mode 100644 index 0000000..99da745 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/compressionFilters/CompressionResponseStream.class differ diff --git a/tomcat/examples/WEB-INF/classes/compressionFilters/CompressionResponseStream.java b/tomcat/examples/WEB-INF/classes/compressionFilters/CompressionResponseStream.java new file mode 100644 index 0000000..ccc6607 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/compressionFilters/CompressionResponseStream.java @@ -0,0 +1,435 @@ +/* +* 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. +*/ +package compressionFilters; + +import java.io.IOException; +import java.io.OutputStream; +import java.util.Arrays; +import java.util.zip.GZIPOutputStream; + +import javax.servlet.ServletOutputStream; +import javax.servlet.WriteListener; + +/** + * Implementation of ServletOutputStream that works with + * the CompressionServletResponseWrapper implementation. + * + * @author Amy Roh + * @author Dmitri Valdin + */ +public class CompressionResponseStream extends ServletOutputStream { + + // ----------------------------------------------------------- Constructors + + /** + * Construct a servlet output stream associated with the specified Response. + * + * @param responseWrapper The associated response wrapper + * @param originalOutput the output stream + */ + public CompressionResponseStream( + CompressionServletResponseWrapper responseWrapper, + ServletOutputStream originalOutput) { + + super(); + closed = false; + this.response = responseWrapper; + this.output = originalOutput; + } + + + // ----------------------------------------------------- Instance Variables + + + /** + * The threshold number which decides to compress or not. + * Users can configure in web.xml to set it to fit their needs. + */ + protected int compressionThreshold = 0; + + /** + * The compression buffer size to avoid chunking + */ + protected int compressionBuffer = 0; + + /** + * The mime types to compress + */ + protected String[] compressionMimeTypes = {"text/html", "text/xml", "text/plain"}; + + /** + * Debug level + */ + private int debug = 0; + + /** + * The buffer through which all of our output bytes are passed. + */ + protected byte[] buffer = null; + + /** + * The number of data bytes currently in the buffer. + */ + protected int bufferCount = 0; + + /** + * The underlying gzip output stream to which we should write data. + */ + protected OutputStream gzipstream = null; + + /** + * Has this stream been closed? + */ + protected boolean closed = false; + + /** + * The response with which this servlet output stream is associated. + */ + protected final CompressionServletResponseWrapper response; + + /** + * The underlying servlet output stream to which we should write data. + */ + protected final ServletOutputStream output; + + + // --------------------------------------------------------- Public Methods + + /** + * Set debug level. + * + * @param debug The higher the number, the more detail shown. Currently the + * range 0 (none) to 3 (everything) is used. + */ + public void setDebugLevel(int debug) { + this.debug = debug; + } + + + /** + * Set the compressionThreshold number and create buffer for this size + */ + protected void setCompressionThreshold(int compressionThreshold) { + this.compressionThreshold = compressionThreshold; + buffer = new byte[this.compressionThreshold]; + if (debug > 1) { + System.out.println("compressionThreshold is set to "+ this.compressionThreshold); + } + } + + /** + * The compression buffer size to avoid chunking + */ + protected void setCompressionBuffer(int compressionBuffer) { + this.compressionBuffer = compressionBuffer; + if (debug > 1) { + System.out.println("compressionBuffer is set to "+ this.compressionBuffer); + } + } + + /** + * Set supported mime types. + * + * @param compressionMimeTypes The mimetypes that will be compressed. + */ + public void setCompressionMimeTypes(String[] compressionMimeTypes) { + this.compressionMimeTypes = compressionMimeTypes; + if (debug > 1) { + System.out.println("compressionMimeTypes is set to " + + Arrays.toString(this.compressionMimeTypes)); + } + } + + /** + * Close this output stream, causing any buffered data to be flushed and + * any further output data to throw an IOException. + */ + @Override + public void close() throws IOException { + + if (debug > 1) { + System.out.println("close() @ CompressionResponseStream"); + } + if (closed) + throw new IOException("This output stream has already been closed"); + + if (gzipstream != null) { + flushToGZip(); + gzipstream.close(); + gzipstream = null; + } else { + if (bufferCount > 0) { + if (debug > 2) { + System.out.print("output.write("); + System.out.write(buffer, 0, bufferCount); + System.out.println(")"); + } + output.write(buffer, 0, bufferCount); + bufferCount = 0; + } + } + + output.close(); + closed = true; + + } + + + /** + * Flush any buffered data for this output stream, which also causes the + * response to be committed. + */ + @Override + public void flush() throws IOException { + + if (debug > 1) { + System.out.println("flush() @ CompressionResponseStream"); + } + if (closed) { + throw new IOException("Cannot flush a closed output stream"); + } + + if (gzipstream != null) { + gzipstream.flush(); + } + + } + + public void flushToGZip() throws IOException { + + if (debug > 1) { + System.out.println("flushToGZip() @ CompressionResponseStream"); + } + if (bufferCount > 0) { + if (debug > 1) { + System.out.println("flushing out to GZipStream, bufferCount = " + bufferCount); + } + writeToGZip(buffer, 0, bufferCount); + bufferCount = 0; + } + + } + + /** + * Write the specified byte to our output stream. + * + * @param b The byte to be written + * + * @exception IOException if an input/output error occurs + */ + @Override + public void write(int b) throws IOException { + + if (debug > 1) { + System.out.println("write "+b+" in CompressionResponseStream "); + } + if (closed) + throw new IOException("Cannot write to a closed output stream"); + + if (bufferCount >= buffer.length) { + flushToGZip(); + } + + buffer[bufferCount++] = (byte) b; + + } + + + /** + * Write b.length bytes from the specified byte array + * to our output stream. + * + * @param b The byte array to be written + * + * @exception IOException if an input/output error occurs + */ + @Override + public void write(byte b[]) throws IOException { + + write(b, 0, b.length); + + } + + + + /** + * TODO SERVLET 3.1 + */ + @Override + public boolean isReady() { + // TODO Auto-generated method stub + return false; + } + + + /** + * TODO SERVLET 3.1 + */ + @Override + public void setWriteListener(WriteListener listener) { + // TODO Auto-generated method stub + + } + + + /** + * Write len bytes from the specified byte array, starting + * at the specified offset, to our output stream. + * + * @param b The byte array containing the bytes to be written + * @param off Zero-relative starting offset of the bytes to be written + * @param len The number of bytes to be written + * + * @exception IOException if an input/output error occurs + */ + @Override + public void write(byte b[], int off, int len) throws IOException { + + if (debug > 1) { + System.out.println("write, bufferCount = " + bufferCount + " len = " + len + " off = " + off); + } + if (debug > 2) { + System.out.print("write("); + System.out.write(b, off, len); + System.out.println(")"); + } + + if (closed) + throw new IOException("Cannot write to a closed output stream"); + + if (len == 0) + return; + + // Can we write into buffer ? + if (len <= (buffer.length - bufferCount)) { + System.arraycopy(b, off, buffer, bufferCount, len); + bufferCount += len; + return; + } + + // There is not enough space in buffer. Flush it ... + flushToGZip(); + + // ... and try again. Note, that bufferCount = 0 here ! + if (len <= (buffer.length - bufferCount)) { + System.arraycopy(b, off, buffer, bufferCount, len); + bufferCount += len; + return; + } + + // write direct to gzip + writeToGZip(b, off, len); + } + + public void writeToGZip(byte b[], int off, int len) throws IOException { + + if (debug > 1) { + System.out.println("writeToGZip, len = " + len); + } + if (debug > 2) { + System.out.print("writeToGZip("); + System.out.write(b, off, len); + System.out.println(")"); + } + if (gzipstream == null) { + if (debug > 1) { + System.out.println("new GZIPOutputStream"); + } + + boolean alreadyCompressed = false; + String contentEncoding = response.getHeader("Content-Encoding"); + if (contentEncoding != null) { + if (contentEncoding.contains("gzip")) { + alreadyCompressed = true; + if (debug > 0) { + System.out.println("content is already compressed"); + } + } else { + if (debug > 0) { + System.out.println("content is not compressed yet"); + } + } + } + + boolean compressibleMimeType = false; + // Check for compatible MIME-TYPE + if (compressionMimeTypes != null) { + if (startsWithStringArray(compressionMimeTypes, response.getContentType())) { + compressibleMimeType = true; + if (debug > 0) { + System.out.println("mime type " + response.getContentType() + " is compressible"); + } + } else { + if (debug > 0) { + System.out.println("mime type " + response.getContentType() + " is not compressible"); + } + } + } + + if (response.isCommitted()) { + if (debug > 1) + System.out.print("Response already committed. Using original output stream"); + gzipstream = output; + } else if (alreadyCompressed) { + if (debug > 1) + System.out.print("Response already compressed. Using original output stream"); + gzipstream = output; + } else if (!compressibleMimeType) { + if (debug > 1) + System.out.print("Response mime type is not compressible. Using original output stream"); + gzipstream = output; + } else { + response.addHeader("Content-Encoding", "gzip"); + response.setContentLength(-1); // don't use any preset content-length as it will be wrong after gzipping + response.setBufferSize(compressionBuffer); + gzipstream = new GZIPOutputStream(output); + } + } + gzipstream.write(b, off, len); + + } + + + // -------------------------------------------------------- Package Methods + + /** + * Has this response stream been closed? + * + * @return true if the stream has been closed, otherwise false. + */ + public boolean closed() { + return closed; + } + + + /** + * Checks if any entry in the string array starts with the specified value + * + * @param sArray the StringArray + * @param value string + */ + private boolean startsWithStringArray(String sArray[], String value) { + if (value == null) + return false; + for (int i = 0; i < sArray.length; i++) { + if (value.startsWith(sArray[i])) { + return true; + } + } + return false; + } +} diff --git a/tomcat/examples/WEB-INF/classes/compressionFilters/CompressionServletResponseWrapper.class b/tomcat/examples/WEB-INF/classes/compressionFilters/CompressionServletResponseWrapper.class new file mode 100644 index 0000000..f3206bb Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/compressionFilters/CompressionServletResponseWrapper.class differ diff --git a/tomcat/examples/WEB-INF/classes/compressionFilters/CompressionServletResponseWrapper.java b/tomcat/examples/WEB-INF/classes/compressionFilters/CompressionServletResponseWrapper.java new file mode 100644 index 0000000..e12859d --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/compressionFilters/CompressionServletResponseWrapper.java @@ -0,0 +1,285 @@ +/* +* 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. +*/ +package compressionFilters; + +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpServletResponseWrapper; + +/** + * Implementation of HttpServletResponseWrapper that works with + * the CompressionServletResponseStream implementation.. + * + * @author Amy Roh + * @author Dmitri Valdin + */ +public class CompressionServletResponseWrapper + extends HttpServletResponseWrapper { + + // ----------------------------------------------------- Constructor + + /** + * Calls the parent constructor which creates a ServletResponse adaptor + * wrapping the given response object. + * + * @param response The response object to be wrapped. + */ + public CompressionServletResponseWrapper(HttpServletResponse response) { + super(response); + origResponse = response; + if (debug > 1) { + System.out.println("CompressionServletResponseWrapper constructor gets called"); + } + } + + + // ----------------------------------------------------- Instance Variables + + /** + * Original response + */ + protected final HttpServletResponse origResponse; + + /** + * The ServletOutputStream that has been returned by + * getOutputStream(), if any. + */ + protected ServletOutputStream stream = null; + + + /** + * The PrintWriter that has been returned by + * getWriter(), if any. + */ + protected PrintWriter writer = null; + + /** + * The threshold number to compress + */ + protected int compressionThreshold = 0; + + /** + * The compression buffer size + */ + protected int compressionBuffer = 8192; // 8KB default + + /** + * The mime types to compress + */ + protected String[] compressionMimeTypes = {"text/html", "text/xml", "text/plain"}; + + /** + * Debug level + */ + protected int debug = 0; + + /** + * keeps a copy of all headers set + */ + private final Map headerCopies = new HashMap<>(); + + + // --------------------------------------------------------- Public Methods + + + /** + * Set threshold number. + * + * @param threshold The new compression threshold + */ + public void setCompressionThreshold(int threshold) { + if (debug > 1) { + System.out.println("setCompressionThreshold to " + threshold); + } + this.compressionThreshold = threshold; + } + + /** + * Set compression buffer. + * + * @param buffer New size of buffer to use for compressed output + */ + public void setCompressionBuffer(int buffer) { + if (debug > 1) { + System.out.println("setCompressionBuffer to " + buffer); + } + this.compressionBuffer = buffer; + } + + /** + * Set compressible mime types. + * + * @param mimeTypes The new list of mime types that will be considered for + * compression + */ + public void setCompressionMimeTypes(String[] mimeTypes) { + if (debug > 1) { + System.out.println("setCompressionMimeTypes to " + + Arrays.toString(mimeTypes)); + } + this.compressionMimeTypes = mimeTypes; + } + + /** + * Set debug level. + * + * @param debug The new debug level + */ + public void setDebugLevel(int debug) { + this.debug = debug; + } + + + /** + * Create and return a ServletOutputStream to write the content + * associated with this Response. + * + * @exception IOException if an input/output error occurs + * + * @return A new servlet output stream that compressed any data written to + * it + */ + protected ServletOutputStream createOutputStream() throws IOException { + if (debug > 1) { + System.out.println("createOutputStream gets called"); + } + + CompressionResponseStream stream = new CompressionResponseStream( + this, origResponse.getOutputStream()); + stream.setDebugLevel(debug); + stream.setCompressionThreshold(compressionThreshold); + stream.setCompressionBuffer(compressionBuffer); + stream.setCompressionMimeTypes(compressionMimeTypes); + + return stream; + } + + + /** + * Finish a response. + */ + public void finishResponse() { + try { + if (writer != null) { + writer.close(); + } else { + if (stream != null) + stream.close(); + } + } catch (IOException e) { + // Ignore + } + } + + + // ------------------------------------------------ ServletResponse Methods + + + /** + * Flush the buffer and commit this response. + * + * @exception IOException if an input/output error occurs + */ + @Override + public void flushBuffer() throws IOException { + if (debug > 1) { + System.out.println("flush buffer @ GZipServletResponseWrapper"); + } + ((CompressionResponseStream)stream).flush(); + + } + + /** + * Return the servlet output stream associated with this Response. + * + * @exception IllegalStateException if getWriter has + * already been called for this response + * @exception IOException if an input/output error occurs + */ + @Override + public ServletOutputStream getOutputStream() throws IOException { + + if (writer != null) + throw new IllegalStateException("getWriter() has already been called for this response"); + + if (stream == null) + stream = createOutputStream(); + if (debug > 1) { + System.out.println("stream is set to "+stream+" in getOutputStream"); + } + + return stream; + } + + /** + * Return the writer associated with this Response. + * + * @exception IllegalStateException if getOutputStream has + * already been called for this response + * @exception IOException if an input/output error occurs + */ + @Override + public PrintWriter getWriter() throws IOException { + + if (writer != null) + return writer; + + if (stream != null) + throw new IllegalStateException("getOutputStream() has already been called for this response"); + + stream = createOutputStream(); + if (debug > 1) { + System.out.println("stream is set to "+stream+" in getWriter"); + } + String charEnc = origResponse.getCharacterEncoding(); + if (debug > 1) { + System.out.println("character encoding is " + charEnc); + } + writer = new PrintWriter(new OutputStreamWriter(stream, charEnc)); + + return writer; + } + + @Override + public String getHeader(String name) { + return headerCopies.get(name); + } + + @Override + public void addHeader(String name, String value) { + if (headerCopies.containsKey(name)) { + String existingValue = headerCopies.get(name); + if ((existingValue != null) && (existingValue.length() > 0)) headerCopies.put(name, existingValue + "," + value); + else headerCopies.put(name, value); + } else headerCopies.put(name, value); + super.addHeader(name, value); + } + + + @Override + public void setHeader(String name, String value) { + headerCopies.put(name, value); + super.setHeader(name, value); + } +} diff --git a/tomcat/examples/WEB-INF/classes/dates/JspCalendar.class b/tomcat/examples/WEB-INF/classes/dates/JspCalendar.class new file mode 100644 index 0000000..909826a Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/dates/JspCalendar.class differ diff --git a/tomcat/examples/WEB-INF/classes/dates/JspCalendar.java b/tomcat/examples/WEB-INF/classes/dates/JspCalendar.java new file mode 100644 index 0000000..759edee --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/dates/JspCalendar.java @@ -0,0 +1,153 @@ +/* +* 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. +*/ +package dates; + +import java.util.Calendar; +import java.util.Date; + +public class JspCalendar { + final Calendar calendar; + + public JspCalendar() { + calendar = Calendar.getInstance(); + Date trialTime = new Date(); + calendar.setTime(trialTime); + } + + public int getYear() { + return calendar.get(Calendar.YEAR); + } + + public String getMonth() { + int m = getMonthInt(); + String[] months = new String [] { "January", "February", "March", + "April", "May", "June", + "July", "August", "September", + "October", "November", "December" }; + if (m > 12) + return "Unknown to Man"; + + return months[m - 1]; + + } + + public String getDay() { + int x = getDayOfWeek(); + String[] days = new String[] {"Sunday", "Monday", "Tuesday", "Wednesday", + "Thursday", "Friday", "Saturday"}; + + if (x > 7) + return "Unknown to Man"; + + return days[x - 1]; + + } + + public int getMonthInt() { + return 1 + calendar.get(Calendar.MONTH); + } + + public String getDate() { + return getMonthInt() + "/" + getDayOfMonth() + "/" + getYear(); + + } + + public String getTime() { + return getHour() + ":" + getMinute() + ":" + getSecond(); + } + + public int getDayOfMonth() { + return calendar.get(Calendar.DAY_OF_MONTH); + } + + public int getDayOfYear() { + return calendar.get(Calendar.DAY_OF_YEAR); + } + + public int getWeekOfYear() { + return calendar.get(Calendar.WEEK_OF_YEAR); + } + + public int getWeekOfMonth() { + return calendar.get(Calendar.WEEK_OF_MONTH); + } + + public int getDayOfWeek() { + return calendar.get(Calendar.DAY_OF_WEEK); + } + + public int getHour() { + return calendar.get(Calendar.HOUR_OF_DAY); + } + + public int getMinute() { + return calendar.get(Calendar.MINUTE); + } + + + public int getSecond() { + return calendar.get(Calendar.SECOND); + } + + public static void main(String args[]) { + JspCalendar db = new JspCalendar(); + p("date: " + db.getDayOfMonth()); + p("year: " + db.getYear()); + p("month: " + db.getMonth()); + p("time: " + db.getTime()); + p("date: " + db.getDate()); + p("Day: " + db.getDay()); + p("DayOfYear: " + db.getDayOfYear()); + p("WeekOfYear: " + db.getWeekOfYear()); + p("era: " + db.getEra()); + p("ampm: " + db.getAMPM()); + p("DST: " + db.getDSTOffset()); + p("ZONE Offset: " + db.getZoneOffset()); + p("TIMEZONE: " + db.getUSTimeZone()); + } + + private static void p(String x) { + System.out.println(x); + } + + + public int getEra() { + return calendar.get(Calendar.ERA); + } + + public String getUSTimeZone() { + String[] zones = new String[] {"Hawaii", "Alaskan", "Pacific", + "Mountain", "Central", "Eastern"}; + + return zones[10 + getZoneOffset()]; + } + + public int getZoneOffset() { + return calendar.get(Calendar.ZONE_OFFSET)/(60*60*1000); + } + + + public int getDSTOffset() { + return calendar.get(Calendar.DST_OFFSET)/(60*60*1000); + } + + + public int getAMPM() { + return calendar.get(Calendar.AM_PM); + } +} + diff --git a/tomcat/examples/WEB-INF/classes/error/Smart.class b/tomcat/examples/WEB-INF/classes/error/Smart.class new file mode 100644 index 0000000..c676cb9 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/error/Smart.class differ diff --git a/tomcat/examples/WEB-INF/classes/error/Smart.java b/tomcat/examples/WEB-INF/classes/error/Smart.java new file mode 100644 index 0000000..82c22f6 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/error/Smart.java @@ -0,0 +1,30 @@ +/* + * 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. + */ +package error; + +public class Smart { + + String name = "JSP"; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/tomcat/examples/WEB-INF/classes/examples/ExampleTagBase.class b/tomcat/examples/WEB-INF/classes/examples/ExampleTagBase.class new file mode 100644 index 0000000..04bc6c1 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/examples/ExampleTagBase.class differ diff --git a/tomcat/examples/WEB-INF/classes/examples/ExampleTagBase.java b/tomcat/examples/WEB-INF/classes/examples/ExampleTagBase.java new file mode 100644 index 0000000..127eddf --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/examples/ExampleTagBase.java @@ -0,0 +1,74 @@ +/* +* 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. +*/ +package examples; + +import javax.servlet.jsp.JspException; +import javax.servlet.jsp.tagext.BodyContent; +import javax.servlet.jsp.tagext.BodyTagSupport; +import javax.servlet.jsp.tagext.Tag; + +public abstract class ExampleTagBase extends BodyTagSupport { + + private static final long serialVersionUID = 1L; + + @Override + public void setParent(Tag parent) { + this.parent = parent; + } + + @Override + public void setBodyContent(BodyContent bodyOut) { + this.bodyOut = bodyOut; + } + + @Override + public Tag getParent() { + return this.parent; + } + + @Override + public int doStartTag() throws JspException { + return SKIP_BODY; + } + + @Override + public int doEndTag() throws JspException { + return EVAL_PAGE; + } + + + @Override + public void doInitBody() throws JspException { + // Default implementations for BodyTag methods as well + // just in case a tag decides to implement BodyTag. + } + + @Override + public int doAfterBody() throws JspException { + return SKIP_BODY; + } + + @Override + public void release() { + bodyOut = null; + pageContext = null; + parent = null; + } + + protected BodyContent bodyOut; + protected Tag parent; +} diff --git a/tomcat/examples/WEB-INF/classes/examples/FooTag.class b/tomcat/examples/WEB-INF/classes/examples/FooTag.class new file mode 100644 index 0000000..52de017 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/examples/FooTag.class differ diff --git a/tomcat/examples/WEB-INF/classes/examples/FooTag.java b/tomcat/examples/WEB-INF/classes/examples/FooTag.java new file mode 100644 index 0000000..f4f3050 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/examples/FooTag.java @@ -0,0 +1,87 @@ +/* +* 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. +*/ +package examples; + +import java.io.IOException; + +import javax.servlet.jsp.JspException; +import javax.servlet.jsp.JspTagException; + +/** + * Example1: the simplest tag + * Collect attributes and call into some actions + * + * + */ + +public class FooTag extends ExampleTagBase { + + private static final long serialVersionUID = 1L; + + private final String atts[] = new String[3]; + int i = 0; + + private final void setAtt(int index, String value) { + atts[index] = value; + } + + public void setAtt1(String value) { + setAtt(0, value); + } + + public void setAtt2(String value) { + setAtt(1, value); + } + + public void setAtt3(String value) { + setAtt(2, value); + } + + /** + * Process start tag + * + * @return EVAL_BODY_INCLUDE + */ + @Override + public int doStartTag() throws JspException { + i = 0; + return EVAL_BODY_BUFFERED; + } + + @Override + public void doInitBody() throws JspException { + pageContext.setAttribute("member", atts[i]); + i++; + } + + @Override + public int doAfterBody() throws JspException { + try { + if (i == 3) { + bodyOut.writeOut(bodyOut.getEnclosingWriter()); + return SKIP_BODY; + } + + pageContext.setAttribute("member", atts[i]); + i++; + return EVAL_BODY_BUFFERED; + } catch (IOException ex) { + throw new JspTagException(ex.toString()); + } + } +} + diff --git a/tomcat/examples/WEB-INF/classes/examples/FooTagExtraInfo.class b/tomcat/examples/WEB-INF/classes/examples/FooTagExtraInfo.class new file mode 100644 index 0000000..e57ebf2 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/examples/FooTagExtraInfo.class differ diff --git a/tomcat/examples/WEB-INF/classes/examples/FooTagExtraInfo.java b/tomcat/examples/WEB-INF/classes/examples/FooTagExtraInfo.java new file mode 100644 index 0000000..e3fe371 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/examples/FooTagExtraInfo.java @@ -0,0 +1,36 @@ +/* +* 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. +*/ +package examples; + +import javax.servlet.jsp.tagext.TagData; +import javax.servlet.jsp.tagext.TagExtraInfo; +import javax.servlet.jsp.tagext.VariableInfo; + +public class FooTagExtraInfo extends TagExtraInfo { + @Override + public VariableInfo[] getVariableInfo(TagData data) { + return new VariableInfo[] + { + new VariableInfo("member", + "String", + true, + VariableInfo.NESTED) + }; + } +} + + diff --git a/tomcat/examples/WEB-INF/classes/examples/LogTag.class b/tomcat/examples/WEB-INF/classes/examples/LogTag.class new file mode 100644 index 0000000..40f55f6 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/examples/LogTag.class differ diff --git a/tomcat/examples/WEB-INF/classes/examples/LogTag.java b/tomcat/examples/WEB-INF/classes/examples/LogTag.java new file mode 100644 index 0000000..0f38280 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/examples/LogTag.java @@ -0,0 +1,61 @@ +/* +* 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. +*/ +package examples; + +import java.io.IOException; + +import javax.servlet.jsp.JspException; +import javax.servlet.jsp.JspTagException; + +/** + * Log the contents of the body. Could be used to handle errors etc. + */ +public class LogTag extends ExampleTagBase { + + private static final long serialVersionUID = 1L; + + boolean toBrowser = false; + + public void setToBrowser(String value) { + if (value == null) + toBrowser = false; + else if (value.equalsIgnoreCase("true")) + toBrowser = true; + else + toBrowser = false; + } + + @Override + public int doStartTag() throws JspException { + return EVAL_BODY_BUFFERED; + } + + @Override + public int doAfterBody() throws JspException { + try { + String s = bodyOut.getString(); + System.err.println(s); + if (toBrowser) + bodyOut.writeOut(bodyOut.getEnclosingWriter()); + return SKIP_BODY; + } catch (IOException ex) { + throw new JspTagException(ex.toString()); + } + } +} + + diff --git a/tomcat/examples/WEB-INF/classes/examples/ValuesTag.class b/tomcat/examples/WEB-INF/classes/examples/ValuesTag.class new file mode 100644 index 0000000..e9c4dea Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/examples/ValuesTag.class differ diff --git a/tomcat/examples/WEB-INF/classes/examples/ValuesTag.java b/tomcat/examples/WEB-INF/classes/examples/ValuesTag.java new file mode 100644 index 0000000..b335860 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/examples/ValuesTag.java @@ -0,0 +1,79 @@ +/* + * 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. + */ +package examples; + +import java.io.IOException; + +import javax.servlet.jsp.JspException; +import javax.servlet.jsp.JspTagException; +import javax.servlet.jsp.JspWriter; +import javax.servlet.jsp.tagext.TagSupport; + +/** + * Accept and display a value. + */ +public class ValuesTag extends TagSupport { + + private static final long serialVersionUID = 1L; + + // Using "-1" as the default value, + // in the assumption that it won't be used as the value. + // Cannot use null here, because null is an important case + // that should be present in the tests. + private Object objectValue = "-1"; + private String stringValue = "-1"; + private long longValue = -1; + private double doubleValue = -1; + + public void setObject(Object objectValue) { + this.objectValue = objectValue; + } + + public void setString(String stringValue) { + this.stringValue = stringValue; + } + + public void setLong(long longValue) { + this.longValue = longValue; + } + + public void setDouble(double doubleValue) { + this.doubleValue = doubleValue; + } + + @Override + public int doEndTag() throws JspException { + JspWriter out = pageContext.getOut(); + + try { + if (!"-1".equals(objectValue)) { + out.print(objectValue); + } else if (!"-1".equals(stringValue)) { + out.print(stringValue); + } else if (longValue != -1) { + out.print(longValue); + } else if (doubleValue != -1) { + out.print(doubleValue); + } else { + out.print("-1"); + } + } catch (IOException ex) { + throw new JspTagException("IOException: " + ex.toString(), ex); + } + return super.doEndTag(); + } +} diff --git a/tomcat/examples/WEB-INF/classes/filters/ExampleFilter.class b/tomcat/examples/WEB-INF/classes/filters/ExampleFilter.class new file mode 100644 index 0000000..b9c0768 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/filters/ExampleFilter.class differ diff --git a/tomcat/examples/WEB-INF/classes/filters/ExampleFilter.java b/tomcat/examples/WEB-INF/classes/filters/ExampleFilter.java new file mode 100644 index 0000000..db5ac40 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/filters/ExampleFilter.java @@ -0,0 +1,137 @@ +/* +* 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. +*/ + +package filters; + + +import java.io.IOException; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; + + +/** + * Example filter that can be attached to either an individual servlet + * or to a URL pattern. This filter performs the following functions: + *

      + *
    • Attaches itself as a request attribute, under the attribute name + * defined by the value of the attribute initialization + * parameter.
    • + *
    • Calculates the number of milliseconds required to perform the + * servlet processing required by this request, including any + * subsequently defined filters, and logs the result to the servlet + * context log for this application. + *
    + * + * @author Craig McClanahan + */ +public final class ExampleFilter implements Filter { + + + // ----------------------------------------------------- Instance Variables + + + /** + * The request attribute name under which we store a reference to ourself. + */ + private String attribute = null; + + + /** + * The filter configuration object we are associated with. If this value + * is null, this filter instance is not currently configured. + */ + private FilterConfig filterConfig = null; + + + // --------------------------------------------------------- Public Methods + + + /** + * Take this filter out of service. + */ + @Override + public void destroy() { + + this.attribute = null; + this.filterConfig = null; + + } + + + /** + * Time the processing that is performed by all subsequent filters in the + * current filter stack, including the ultimately invoked servlet. + * + * @param request The servlet request we are processing + * @param response The servlet response we are creating + * @param chain The filter chain we are processing + * + * @exception IOException if an input/output error occurs + * @exception ServletException if a servlet error occurs + */ + @Override + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain chain) + throws IOException, ServletException { + + // Store ourselves as a request attribute (if requested) + if (attribute != null) + request.setAttribute(attribute, this); + + // Time and log the subsequent processing + long startTime = System.currentTimeMillis(); + chain.doFilter(request, response); + long stopTime = System.currentTimeMillis(); + filterConfig.getServletContext().log + (this.toString() + ": " + (stopTime - startTime) + + " milliseconds"); + } + + + /** + * Place this filter into service. + * + * @param fConfig The filter configuration object + */ + @Override + public void init(FilterConfig fConfig) throws ServletException { + + this.filterConfig = fConfig; + this.attribute = fConfig.getInitParameter("attribute"); + } + + + /** + * Return a String representation of this object. + */ + @Override + public String toString() { + + if (filterConfig == null) + return ("TimingFilter()"); + StringBuilder sb = new StringBuilder("TimingFilter("); + sb.append(filterConfig); + sb.append(")"); + return sb.toString(); + } +} + diff --git a/tomcat/examples/WEB-INF/classes/jsp2/examples/BookBean.class b/tomcat/examples/WEB-INF/classes/jsp2/examples/BookBean.class new file mode 100644 index 0000000..9321a62 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/jsp2/examples/BookBean.class differ diff --git a/tomcat/examples/WEB-INF/classes/jsp2/examples/BookBean.java b/tomcat/examples/WEB-INF/classes/jsp2/examples/BookBean.java new file mode 100644 index 0000000..ff6a55d --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/jsp2/examples/BookBean.java @@ -0,0 +1,44 @@ +/* +* 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. +*/ + + +package jsp2.examples; + +public class BookBean { + private final String title; + private final String author; + private final String isbn; + + public BookBean( String title, String author, String isbn ) { + this.title = title; + this.author = author; + this.isbn = isbn; + } + + public String getTitle() { + return this.title; + } + + public String getAuthor() { + return this.author; + } + + public String getIsbn() { + return this.isbn; + } + +} diff --git a/tomcat/examples/WEB-INF/classes/jsp2/examples/FooBean.class b/tomcat/examples/WEB-INF/classes/jsp2/examples/FooBean.class new file mode 100644 index 0000000..b026851 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/jsp2/examples/FooBean.class differ diff --git a/tomcat/examples/WEB-INF/classes/jsp2/examples/FooBean.java b/tomcat/examples/WEB-INF/classes/jsp2/examples/FooBean.java new file mode 100644 index 0000000..4dc0a78 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/jsp2/examples/FooBean.java @@ -0,0 +1,36 @@ +/* +* 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. +*/ + + +package jsp2.examples; + +public class FooBean { + private String bar; + + public FooBean() { + bar = "Initial value"; + } + + public String getBar() { + return this.bar; + } + + public void setBar(String bar) { + this.bar = bar; + } + +} diff --git a/tomcat/examples/WEB-INF/classes/jsp2/examples/ValuesBean.class b/tomcat/examples/WEB-INF/classes/jsp2/examples/ValuesBean.class new file mode 100644 index 0000000..abaff0a Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/jsp2/examples/ValuesBean.class differ diff --git a/tomcat/examples/WEB-INF/classes/jsp2/examples/ValuesBean.java b/tomcat/examples/WEB-INF/classes/jsp2/examples/ValuesBean.java new file mode 100644 index 0000000..686039c --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/jsp2/examples/ValuesBean.java @@ -0,0 +1,52 @@ +/* +* 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. +*/ + + +package jsp2.examples; + +/** + * Accept and display a value. + */ +public class ValuesBean { + private String string; + private double doubleValue; + private long longValue; + + public String getStringValue() { + return this.string; + } + + public void setStringValue(String string) { + this.string = string; + } + + public double getDoubleValue() { + return doubleValue; + } + + public void setDoubleValue(double doubleValue) { + this.doubleValue = doubleValue; + } + + public long getLongValue() { + return longValue; + } + + public void setLongValue(long longValue) { + this.longValue = longValue; + } +} diff --git a/tomcat/examples/WEB-INF/classes/jsp2/examples/el/Functions.class b/tomcat/examples/WEB-INF/classes/jsp2/examples/el/Functions.class new file mode 100644 index 0000000..b3b0cf4 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/jsp2/examples/el/Functions.class differ diff --git a/tomcat/examples/WEB-INF/classes/jsp2/examples/el/Functions.java b/tomcat/examples/WEB-INF/classes/jsp2/examples/el/Functions.java new file mode 100644 index 0000000..77fdb9c --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/jsp2/examples/el/Functions.java @@ -0,0 +1,45 @@ +/* +* 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. +*/ +package jsp2.examples.el; + +import java.util.Locale; + +/** + * Defines the functions for the jsp2 example tag library. + * + *

    Each function is defined as a static method.

    + */ +public class Functions { + public static String reverse( String text ) { + return new StringBuilder( text ).reverse().toString(); + } + + public static int numVowels( String text ) { + String vowels = "aeiouAEIOU"; + int result = 0; + for( int i = 0; i < text.length(); i++ ) { + if( vowels.indexOf( text.charAt( i ) ) != -1 ) { + result++; + } + } + return result; + } + + public static String caps( String text ) { + return text.toUpperCase(Locale.ENGLISH); + } +} diff --git a/tomcat/examples/WEB-INF/classes/jsp2/examples/simpletag/EchoAttributesTag.class b/tomcat/examples/WEB-INF/classes/jsp2/examples/simpletag/EchoAttributesTag.class new file mode 100644 index 0000000..bb71203 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/jsp2/examples/simpletag/EchoAttributesTag.class differ diff --git a/tomcat/examples/WEB-INF/classes/jsp2/examples/simpletag/EchoAttributesTag.java b/tomcat/examples/WEB-INF/classes/jsp2/examples/simpletag/EchoAttributesTag.java new file mode 100644 index 0000000..c34237d --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/jsp2/examples/simpletag/EchoAttributesTag.java @@ -0,0 +1,58 @@ +/* +* 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. +*/ + + +package jsp2.examples.simpletag; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.jsp.JspException; +import javax.servlet.jsp.JspWriter; +import javax.servlet.jsp.tagext.DynamicAttributes; +import javax.servlet.jsp.tagext.SimpleTagSupport; + +/** + * SimpleTag handler that echoes all its attributes + */ +public class EchoAttributesTag + extends SimpleTagSupport + implements DynamicAttributes +{ + private final List keys = new ArrayList<>(); + private final List values = new ArrayList<>(); + + @Override + public void doTag() throws JspException, IOException { + JspWriter out = getJspContext().getOut(); + for( int i = 0; i < keys.size(); i++ ) { + String key = keys.get( i ); + Object value = values.get( i ); + out.println( "
  • " + key + " = " + value + "
  • " ); + } + } + + @Override + public void setDynamicAttribute( String uri, String localName, + Object value ) + throws JspException + { + keys.add( localName ); + values.add( value ); + } +} diff --git a/tomcat/examples/WEB-INF/classes/jsp2/examples/simpletag/FindBookSimpleTag.class b/tomcat/examples/WEB-INF/classes/jsp2/examples/simpletag/FindBookSimpleTag.class new file mode 100644 index 0000000..14b98f8 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/jsp2/examples/simpletag/FindBookSimpleTag.class differ diff --git a/tomcat/examples/WEB-INF/classes/jsp2/examples/simpletag/FindBookSimpleTag.java b/tomcat/examples/WEB-INF/classes/jsp2/examples/simpletag/FindBookSimpleTag.java new file mode 100644 index 0000000..6a55d19 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/jsp2/examples/simpletag/FindBookSimpleTag.java @@ -0,0 +1,46 @@ +/* +* 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. +*/ + + +package jsp2.examples.simpletag; + +import javax.servlet.jsp.JspException; +import javax.servlet.jsp.tagext.SimpleTagSupport; + +import jsp2.examples.BookBean; + +/** + * SimpleTag handler that pretends to search for a book, and stores + * the result in a scoped variable. + */ +public class FindBookSimpleTag extends SimpleTagSupport { + private String var; + + private static final String BOOK_TITLE = "The Lord of the Rings"; + private static final String BOOK_AUTHOR = "J. R. R. Tolkien"; + private static final String BOOK_ISBN = "0618002251"; + + @Override + public void doTag() throws JspException { + BookBean book = new BookBean( BOOK_TITLE, BOOK_AUTHOR, BOOK_ISBN ); + getJspContext().setAttribute( this.var, book ); + } + + public void setVar( String var ) { + this.var = var; + } +} diff --git a/tomcat/examples/WEB-INF/classes/jsp2/examples/simpletag/HelloWorldSimpleTag.class b/tomcat/examples/WEB-INF/classes/jsp2/examples/simpletag/HelloWorldSimpleTag.class new file mode 100644 index 0000000..d314eb4 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/jsp2/examples/simpletag/HelloWorldSimpleTag.class differ diff --git a/tomcat/examples/WEB-INF/classes/jsp2/examples/simpletag/HelloWorldSimpleTag.java b/tomcat/examples/WEB-INF/classes/jsp2/examples/simpletag/HelloWorldSimpleTag.java new file mode 100644 index 0000000..f87736f --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/jsp2/examples/simpletag/HelloWorldSimpleTag.java @@ -0,0 +1,34 @@ +/* +* 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. +*/ + + +package jsp2.examples.simpletag; + +import java.io.IOException; + +import javax.servlet.jsp.JspException; +import javax.servlet.jsp.tagext.SimpleTagSupport; + +/** + * SimpleTag handler that prints "Hello, world!" + */ +public class HelloWorldSimpleTag extends SimpleTagSupport { + @Override + public void doTag() throws JspException, IOException { + getJspContext().getOut().write( "Hello, world!" ); + } +} diff --git a/tomcat/examples/WEB-INF/classes/jsp2/examples/simpletag/RepeatSimpleTag.class b/tomcat/examples/WEB-INF/classes/jsp2/examples/simpletag/RepeatSimpleTag.class new file mode 100644 index 0000000..94e5c64 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/jsp2/examples/simpletag/RepeatSimpleTag.class differ diff --git a/tomcat/examples/WEB-INF/classes/jsp2/examples/simpletag/RepeatSimpleTag.java b/tomcat/examples/WEB-INF/classes/jsp2/examples/simpletag/RepeatSimpleTag.java new file mode 100644 index 0000000..41a9f3c --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/jsp2/examples/simpletag/RepeatSimpleTag.java @@ -0,0 +1,44 @@ +/* +* 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. +*/ + + +package jsp2.examples.simpletag; + +import java.io.IOException; + +import javax.servlet.jsp.JspException; +import javax.servlet.jsp.tagext.SimpleTagSupport; + +/** + * SimpleTag handler that accepts a num attribute and + * invokes its body 'num' times. + */ +public class RepeatSimpleTag extends SimpleTagSupport { + private int num; + + @Override + public void doTag() throws JspException, IOException { + for (int i=0; i
    " + this.label + + "
    " ); + } + + public void setColor( String color ) { + this.color = color; + } + + public void setLabel( String label ) { + this.label = label; + } +} diff --git a/tomcat/examples/WEB-INF/classes/listeners/ContextListener.class b/tomcat/examples/WEB-INF/classes/listeners/ContextListener.class new file mode 100644 index 0000000..27d7bc6 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/listeners/ContextListener.class differ diff --git a/tomcat/examples/WEB-INF/classes/listeners/ContextListener.java b/tomcat/examples/WEB-INF/classes/listeners/ContextListener.java new file mode 100644 index 0000000..31f5545 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/listeners/ContextListener.java @@ -0,0 +1,138 @@ +/* +* 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. +*/ +package listeners; + + +import javax.servlet.ServletContext; +import javax.servlet.ServletContextAttributeEvent; +import javax.servlet.ServletContextAttributeListener; +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; + + +/** + * Example listener for context-related application events, which were + * introduced in the 2.3 version of the Servlet API. This listener + * merely documents the occurrence of such events in the application log + * associated with our servlet context. + * + * @author Craig R. McClanahan + */ +public final class ContextListener + implements ServletContextAttributeListener, ServletContextListener { + + + // ----------------------------------------------------- Instance Variables + + + /** + * The servlet context with which we are associated. + */ + private ServletContext context = null; + + + // --------------------------------------------------------- Public Methods + + + /** + * Record the fact that a servlet context attribute was added. + * + * @param event The servlet context attribute event + */ + @Override + public void attributeAdded(ServletContextAttributeEvent event) { + + log("attributeAdded('" + event.getName() + "', '" + + event.getValue() + "')"); + + } + + + /** + * Record the fact that a servlet context attribute was removed. + * + * @param event The servlet context attribute event + */ + @Override + public void attributeRemoved(ServletContextAttributeEvent event) { + + log("attributeRemoved('" + event.getName() + "', '" + + event.getValue() + "')"); + + } + + + /** + * Record the fact that a servlet context attribute was replaced. + * + * @param event The servlet context attribute event + */ + @Override + public void attributeReplaced(ServletContextAttributeEvent event) { + + log("attributeReplaced('" + event.getName() + "', '" + + event.getValue() + "')"); + + } + + + /** + * Record the fact that this web application has been destroyed. + * + * @param event The servlet context event + */ + @Override + public void contextDestroyed(ServletContextEvent event) { + + log("contextDestroyed()"); + this.context = null; + + } + + + /** + * Record the fact that this web application has been initialized. + * + * @param event The servlet context event + */ + @Override + public void contextInitialized(ServletContextEvent event) { + + this.context = event.getServletContext(); + log("contextInitialized()"); + + } + + + // -------------------------------------------------------- Private Methods + + + /** + * Log a message to the servlet context application log. + * + * @param message Message to be logged + */ + private void log(String message) { + + if (context != null) + context.log("ContextListener: " + message); + else + System.out.println("ContextListener: " + message); + + } + +} diff --git a/tomcat/examples/WEB-INF/classes/listeners/SessionListener.class b/tomcat/examples/WEB-INF/classes/listeners/SessionListener.class new file mode 100644 index 0000000..d683d5d Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/listeners/SessionListener.class differ diff --git a/tomcat/examples/WEB-INF/classes/listeners/SessionListener.java b/tomcat/examples/WEB-INF/classes/listeners/SessionListener.java new file mode 100644 index 0000000..f03e48f --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/listeners/SessionListener.java @@ -0,0 +1,160 @@ +/* + * 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. + */ +package listeners; + +import javax.servlet.ServletContext; +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; +import javax.servlet.http.HttpSessionAttributeListener; +import javax.servlet.http.HttpSessionBindingEvent; +import javax.servlet.http.HttpSessionEvent; +import javax.servlet.http.HttpSessionListener; + +/** + * Example listener for context-related application events, which were + * introduced in the 2.3 version of the Servlet API. This listener merely + * documents the occurrence of such events in the application log associated + * with our servlet context. + * + * @author Craig R. McClanahan + */ +public final class SessionListener implements ServletContextListener, + HttpSessionAttributeListener, HttpSessionListener { + + // ----------------------------------------------------- Instance Variables + + /** + * The servlet context with which we are associated. + */ + private ServletContext context = null; + + // --------------------------------------------------------- Public Methods + + /** + * Record the fact that a servlet context attribute was added. + * + * @param event + * The session attribute event + */ + @Override + public void attributeAdded(HttpSessionBindingEvent event) { + + log("attributeAdded('" + event.getSession().getId() + "', '" + + event.getName() + "', '" + event.getValue() + "')"); + + } + + /** + * Record the fact that a servlet context attribute was removed. + * + * @param event + * The session attribute event + */ + @Override + public void attributeRemoved(HttpSessionBindingEvent event) { + + log("attributeRemoved('" + event.getSession().getId() + "', '" + + event.getName() + "', '" + event.getValue() + "')"); + + } + + /** + * Record the fact that a servlet context attribute was replaced. + * + * @param event + * The session attribute event + */ + @Override + public void attributeReplaced(HttpSessionBindingEvent event) { + + log("attributeReplaced('" + event.getSession().getId() + "', '" + + event.getName() + "', '" + event.getValue() + "')"); + + } + + /** + * Record the fact that this web application has been destroyed. + * + * @param event + * The servlet context event + */ + @Override + public void contextDestroyed(ServletContextEvent event) { + + log("contextDestroyed()"); + this.context = null; + + } + + /** + * Record the fact that this web application has been initialized. + * + * @param event + * The servlet context event + */ + @Override + public void contextInitialized(ServletContextEvent event) { + + this.context = event.getServletContext(); + log("contextInitialized()"); + + } + + /** + * Record the fact that a session has been created. + * + * @param event + * The session event + */ + @Override + public void sessionCreated(HttpSessionEvent event) { + + log("sessionCreated('" + event.getSession().getId() + "')"); + + } + + /** + * Record the fact that a session has been destroyed. + * + * @param event + * The session event + */ + @Override + public void sessionDestroyed(HttpSessionEvent event) { + + log("sessionDestroyed('" + event.getSession().getId() + "')"); + + } + + // -------------------------------------------------------- Private Methods + + /** + * Log a message to the servlet context application log. + * + * @param message + * Message to be logged + */ + private void log(String message) { + + if (context != null) + context.log("SessionListener: " + message); + else + System.out.println("SessionListener: " + message); + + } + +} diff --git a/tomcat/examples/WEB-INF/classes/nonblocking/ByteCounter$1.class b/tomcat/examples/WEB-INF/classes/nonblocking/ByteCounter$1.class new file mode 100644 index 0000000..accd7e0 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/nonblocking/ByteCounter$1.class differ diff --git a/tomcat/examples/WEB-INF/classes/nonblocking/ByteCounter$CounterListener.class b/tomcat/examples/WEB-INF/classes/nonblocking/ByteCounter$CounterListener.class new file mode 100644 index 0000000..3c5b2cf Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/nonblocking/ByteCounter$CounterListener.class differ diff --git a/tomcat/examples/WEB-INF/classes/nonblocking/ByteCounter.class b/tomcat/examples/WEB-INF/classes/nonblocking/ByteCounter.class new file mode 100644 index 0000000..132deab Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/nonblocking/ByteCounter.class differ diff --git a/tomcat/examples/WEB-INF/classes/nonblocking/ByteCounter.java b/tomcat/examples/WEB-INF/classes/nonblocking/ByteCounter.java new file mode 100644 index 0000000..3923780 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/nonblocking/ByteCounter.java @@ -0,0 +1,142 @@ +/* + * 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. + */ +package nonblocking; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; + +import javax.servlet.AsyncContext; +import javax.servlet.ReadListener; +import javax.servlet.ServletException; +import javax.servlet.ServletInputStream; +import javax.servlet.ServletOutputStream; +import javax.servlet.WriteListener; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * This doesn't do anything particularly useful - it just counts the total + * number of bytes in a request body while demonstrating how to perform + * non-blocking reads. + */ +public class ByteCounter extends HttpServlet { + + private static final long serialVersionUID = 1L; + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + + resp.setContentType("text/plain"); + resp.setCharacterEncoding("UTF-8"); + + resp.getWriter().println("Try again using a POST request."); + } + + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + + resp.setContentType("text/plain"); + resp.setCharacterEncoding("UTF-8"); + + // Non-blocking IO requires async + AsyncContext ac = req.startAsync(); + + // Use a single listener for read and write. Listeners often need to + // share state to coordinate reads and writes and this is much easier as + // a single object. + @SuppressWarnings("unused") + CounterListener listener = new CounterListener( + ac, req.getInputStream(), resp.getOutputStream()); + } + + + /** + * Keep in mind that each call may well be on a different thread to the + * previous call. Ensure that changes in values will be visible across + * threads. There should only ever be one container thread at a time calling + * the listener. + */ + private static class CounterListener implements ReadListener, WriteListener { + + private final AsyncContext ac; + private final ServletInputStream sis; + private final ServletOutputStream sos; + + private volatile boolean readFinished = false; + private volatile long totalBytesRead = 0; + private byte[] buffer = new byte[8192]; + + private CounterListener(AsyncContext ac, ServletInputStream sis, + ServletOutputStream sos) { + this.ac = ac; + this.sis = sis; + this.sos = sos; + + // In Tomcat, the order the listeners are set controls the order + // that the first calls are made. In this case, the read listener + // will be called before the write listener. + sis.setReadListener(this); + sos.setWriteListener(this); + } + + @Override + public void onDataAvailable() throws IOException { + int read = 0; + // Loop as long as there is data to read. If isReady() returns false + // the socket will be added to the poller and onDataAvailable() will + // be called again as soon as there is more data to read. + while (sis.isReady() && read > -1) { + read = sis.read(buffer); + if (read > 0) { + totalBytesRead += read; + } + } + } + + @Override + public void onAllDataRead() throws IOException { + readFinished = true; + + // If sos is not ready to write data, the call to isReady() will + // register the socket with the poller which will trigger a call to + // onWritePossible() when the socket is ready to have data written + // to it. + if (sos.isReady()) { + onWritePossible(); + } + } + + @Override + public void onWritePossible() throws IOException { + if (readFinished) { + // Must be ready to write data if onWritePossible was called + String msg = "Total bytes written = [" + totalBytesRead + "]"; + sos.write(msg.getBytes(StandardCharsets.UTF_8)); + ac.complete(); + } + } + + @Override + public void onError(Throwable throwable) { + // Should probably log the throwable + ac.complete(); + } + } +} diff --git a/tomcat/examples/WEB-INF/classes/nonblocking/NumberWriter$1.class b/tomcat/examples/WEB-INF/classes/nonblocking/NumberWriter$1.class new file mode 100644 index 0000000..e63768e Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/nonblocking/NumberWriter$1.class differ diff --git a/tomcat/examples/WEB-INF/classes/nonblocking/NumberWriter$NumberWriterListener.class b/tomcat/examples/WEB-INF/classes/nonblocking/NumberWriter$NumberWriterListener.class new file mode 100644 index 0000000..43beb94 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/nonblocking/NumberWriter$NumberWriterListener.class differ diff --git a/tomcat/examples/WEB-INF/classes/nonblocking/NumberWriter.class b/tomcat/examples/WEB-INF/classes/nonblocking/NumberWriter.class new file mode 100644 index 0000000..dc01a9f Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/nonblocking/NumberWriter.class differ diff --git a/tomcat/examples/WEB-INF/classes/nonblocking/NumberWriter.java b/tomcat/examples/WEB-INF/classes/nonblocking/NumberWriter.java new file mode 100644 index 0000000..d7a6680 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/nonblocking/NumberWriter.java @@ -0,0 +1,148 @@ +/* + * 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. + */ +package nonblocking; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.atomic.AtomicInteger; + +import javax.servlet.AsyncContext; +import javax.servlet.ReadListener; +import javax.servlet.ServletException; +import javax.servlet.ServletInputStream; +import javax.servlet.ServletOutputStream; +import javax.servlet.WriteListener; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * This doesn't do anything particularly useful - it just writes a series of + * numbers to the response body while demonstrating how to perform non-blocking + * writes. + */ +public class NumberWriter extends HttpServlet { + + private static final long serialVersionUID = 1L; + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + + resp.setContentType("text/plain"); + resp.setCharacterEncoding("UTF-8"); + + // Non-blocking IO requires async + AsyncContext ac = req.startAsync(); + + // Use a single listener for read and write. Listeners often need to + // share state to coordinate reads and writes and this is much easier as + // a single object. + @SuppressWarnings("unused") + NumberWriterListener listener = new NumberWriterListener( + ac, req.getInputStream(), resp.getOutputStream()); + + } + + + /** + * Keep in mind that each call may well be on a different thread to the + * previous call. Ensure that changes in values will be visible across + * threads. There should only ever be one container thread at a time calling + * the listener. + */ + private static class NumberWriterListener implements ReadListener, + WriteListener { + + private static final int LIMIT = 10000; + + private final AsyncContext ac; + private final ServletInputStream sis; + private final ServletOutputStream sos; + private final AtomicInteger counter = new AtomicInteger(0); + + private volatile boolean readFinished = false; + private byte[] buffer = new byte[8192]; + + private NumberWriterListener(AsyncContext ac, ServletInputStream sis, + ServletOutputStream sos) { + this.ac = ac; + this.sis = sis; + this.sos = sos; + + // In Tomcat, the order the listeners are set controls the order + // that the first calls are made. In this case, the read listener + // will be called before the write listener. + sis.setReadListener(this); + sos.setWriteListener(this); + } + + @Override + public void onDataAvailable() throws IOException { + + // There should be no data to read + + int read = 0; + // Loop as long as there is data to read. If isReady() returns false + // the socket will be added to the poller and onDataAvailable() will + // be called again as soon as there is more data to read. + while (sis.isReady() && read > -1) { + read = sis.read(buffer); + if (read > 0) { + throw new IOException("Data was present in input stream"); + } + } + } + + @Override + public void onAllDataRead() throws IOException { + readFinished = true; + + // If sos is not ready to write data, the call to isReady() will + // register the socket with the poller which will trigger a call to + // onWritePossible() when the socket is ready to have data written + // to it. + if (sos.isReady()) { + onWritePossible(); + } + } + + @Override + public void onWritePossible() throws IOException { + if (readFinished) { + int i = counter.get(); + boolean ready = true; + while (i < LIMIT && ready) { + i = counter.incrementAndGet(); + String msg = String.format("%1$020d\n", Integer.valueOf(i)); + sos.write(msg.getBytes(StandardCharsets.UTF_8)); + ready = sos.isReady(); + } + + if (i == LIMIT) { + ac.complete(); + } + } + } + + @Override + public void onError(Throwable throwable) { + // Should probably log the throwable + ac.complete(); + } + } +} diff --git a/tomcat/examples/WEB-INF/classes/num/NumberGuessBean.class b/tomcat/examples/WEB-INF/classes/num/NumberGuessBean.class new file mode 100644 index 0000000..75208b7 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/num/NumberGuessBean.class differ diff --git a/tomcat/examples/WEB-INF/classes/num/NumberGuessBean.java b/tomcat/examples/WEB-INF/classes/num/NumberGuessBean.java new file mode 100644 index 0000000..b78bd05 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/num/NumberGuessBean.java @@ -0,0 +1,99 @@ +/* + * 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. + */ + +/* + * Originally written by Jason Hunter, http://www.servlets.com. + */ + +package num; + +import java.io.Serializable; +import java.util.Random; + +public class NumberGuessBean implements Serializable { + + private static final long serialVersionUID = 1L; + + private int answer; + private String hint; + private int numGuesses; + private boolean success; + private final Random random = new Random(); + + public NumberGuessBean() { + reset(); + } + + public int getAnswer() { + return answer; + } + + public void setAnswer(int answer) { + this.answer = answer; + } + + public String getHint() { + return "" + hint; + } + + public void setHint(String hint) { + this.hint = hint; + } + + public void setNumGuesses(int numGuesses) { + this.numGuesses = numGuesses; + } + + public int getNumGuesses() { + return numGuesses; + } + + public boolean getSuccess() { + return success; + } + + public void setSuccess(boolean success) { + this.success = success; + } + + public void setGuess(String guess) { + numGuesses++; + + int g; + try { + g = Integer.parseInt(guess); + } catch (NumberFormatException e) { + g = -1; + } + + if (g == answer) { + success = true; + } else if (g == -1) { + hint = "a number next time"; + } else if (g < answer) { + hint = "higher"; + } else if (g > answer) { + hint = "lower"; + } + } + + public void reset() { + answer = Math.abs(random.nextInt() % 100) + 1; + success = false; + numGuesses = 0; + } +} diff --git a/tomcat/examples/WEB-INF/classes/sessions/DummyCart.class b/tomcat/examples/WEB-INF/classes/sessions/DummyCart.class new file mode 100644 index 0000000..8caf0ad Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/sessions/DummyCart.class differ diff --git a/tomcat/examples/WEB-INF/classes/sessions/DummyCart.java b/tomcat/examples/WEB-INF/classes/sessions/DummyCart.java new file mode 100644 index 0000000..bad0cb9 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/sessions/DummyCart.java @@ -0,0 +1,65 @@ +/* +* 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. +*/ +package sessions; + +import java.util.Vector; + +public class DummyCart { + final Vector v = new Vector<>(); + String submit = null; + String item = null; + + private void addItem(String name) { + v.addElement(name); + } + + private void removeItem(String name) { + v.removeElement(name); + } + + public void setItem(String name) { + item = name; + } + + public void setSubmit(String s) { + submit = s; + } + + public String[] getItems() { + String[] s = new String[v.size()]; + v.copyInto(s); + return s; + } + + public void processRequest() { + // null value for submit - user hit enter instead of clicking on + // "add" or "remove" + if (submit == null || submit.equals("add")) + addItem(item); + else if (submit.equals("remove")) + removeItem(item); + + // reset at the end of the request + reset(); + } + + // reset + private void reset() { + submit = null; + item = null; + } +} diff --git a/tomcat/examples/WEB-INF/classes/util/CookieFilter.class b/tomcat/examples/WEB-INF/classes/util/CookieFilter.class new file mode 100644 index 0000000..f1278ab Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/util/CookieFilter.class differ diff --git a/tomcat/examples/WEB-INF/classes/util/CookieFilter.java b/tomcat/examples/WEB-INF/classes/util/CookieFilter.java new file mode 100644 index 0000000..19243ee --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/util/CookieFilter.java @@ -0,0 +1,85 @@ +/* + * 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. + */ +package util; + +import java.util.Locale; +import java.util.StringTokenizer; + +/** + * Processes a cookie header and attempts to obfuscate any cookie values that + * represent session IDs from other web applications. Since session cookie names + * are configurable, as are session ID lengths, this filter is not expected to + * be 100% effective. + * + * It is required that the examples web application is removed in security + * conscious environments as documented in the Security How-To. This filter is + * intended to reduce the impact of failing to follow that advice. A failure by + * this filter to obfuscate a session ID or similar value is not a security + * vulnerability. In such instances the vulnerability is the failure to remove + * the examples web application. + */ +public class CookieFilter { + + private static final String OBFUSCATED = "[obfuscated]"; + + private CookieFilter() { + // Hide default constructor + } + + public static String filter(String cookieHeader, String sessionId) { + + StringBuilder sb = new StringBuilder(cookieHeader.length()); + + // Cookie name value pairs are ';' separated. + // Session IDs don't use ; in the value so don't worry about quoted + // values that contain ; + StringTokenizer st = new StringTokenizer(cookieHeader, ";"); + + boolean first = true; + while (st.hasMoreTokens()) { + if (first) { + first = false; + } else { + sb.append(';'); + } + sb.append(filterNameValuePair(st.nextToken(), sessionId)); + } + + + return sb.toString(); + } + + private static String filterNameValuePair(String input, String sessionId) { + int i = input.indexOf('='); + if (i == -1) { + return input; + } + String name = input.substring(0, i); + String value = input.substring(i + 1, input.length()); + + return name + "=" + filter(name, value, sessionId); + } + + public static String filter(String cookieName, String cookieValue, String sessionId) { + if (cookieName.toLowerCase(Locale.ENGLISH).contains("jsessionid") && + (sessionId == null || !cookieValue.contains(sessionId))) { + cookieValue = OBFUSCATED; + } + + return cookieValue; + } +} diff --git a/tomcat/examples/WEB-INF/classes/util/HTMLFilter.class b/tomcat/examples/WEB-INF/classes/util/HTMLFilter.class new file mode 100644 index 0000000..8c429cd Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/util/HTMLFilter.class differ diff --git a/tomcat/examples/WEB-INF/classes/util/HTMLFilter.java b/tomcat/examples/WEB-INF/classes/util/HTMLFilter.java new file mode 100644 index 0000000..29463fb --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/util/HTMLFilter.java @@ -0,0 +1,68 @@ +/* +* 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. +*/ +package util; + +/** + * HTML filter utility. + * + * @author Craig R. McClanahan + * @author Tim Tye + */ +public final class HTMLFilter { + + + /** + * Filter the specified message string for characters that are sensitive + * in HTML. This avoids potential attacks caused by including JavaScript + * codes in the request URL that is often reported in error messages. + * + * @param message The message string to be filtered + * + * @return the filtered version of the message + */ + public static String filter(String message) { + + if (message == null) + return null; + + char content[] = new char[message.length()]; + message.getChars(0, message.length(), content, 0); + StringBuilder result = new StringBuilder(content.length + 50); + for (int i = 0; i < content.length; i++) { + switch (content[i]) { + case '<': + result.append("<"); + break; + case '>': + result.append(">"); + break; + case '&': + result.append("&"); + break; + case '"': + result.append("""); + break; + default: + result.append(content[i]); + } + } + return result.toString(); + } + + +} + diff --git a/tomcat/examples/WEB-INF/classes/validators/DebugValidator.class b/tomcat/examples/WEB-INF/classes/validators/DebugValidator.class new file mode 100644 index 0000000..13d269c Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/validators/DebugValidator.class differ diff --git a/tomcat/examples/WEB-INF/classes/validators/DebugValidator.java b/tomcat/examples/WEB-INF/classes/validators/DebugValidator.java new file mode 100644 index 0000000..596065b --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/validators/DebugValidator.java @@ -0,0 +1,84 @@ +/* +* 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. +*/ + + +package validators; + + +import java.io.IOException; +import java.io.InputStream; + +import javax.servlet.jsp.tagext.PageData; +import javax.servlet.jsp.tagext.TagLibraryValidator; +import javax.servlet.jsp.tagext.ValidationMessage; + + +/** + * Example tag library validator that simply dumps the XML version of each + * page to standard output (which will typically be sent to the file + * $CATALINA_HOME/logs/catalina.out). To utilize it, simply + * include a taglib directive for this tag library at the top + * of your JSP page. + * + * @author Craig McClanahan + */ +public class DebugValidator extends TagLibraryValidator { + + + // ----------------------------------------------------- Instance Variables + + + // --------------------------------------------------------- Public Methods + + + /** + * Validate a JSP page. This will get invoked once per directive in the + * JSP page. This method will return null if the page is + * valid; otherwise the method should return an array of + * ValidationMessage objects. An array of length zero is + * also interpreted as no errors. + * + * @param prefix The value of the prefix argument in this directive + * @param uri The value of the URI argument in this directive + * @param page The page data for this page + */ + @Override + public ValidationMessage[] validate(String prefix, String uri, + PageData page) { + + System.out.println("---------- Prefix=" + prefix + " URI=" + uri + + "----------"); + + InputStream is = page.getInputStream(); + while (true) { + try { + int ch = is.read(); + if (ch < 0) + break; + System.out.print((char) ch); + } catch (IOException e) { + break; + } + } + System.out.println(); + System.out.println("-----------------------------------------------"); + return null; + + } + + +} diff --git a/tomcat/examples/WEB-INF/classes/websocket/ExamplesConfig.class b/tomcat/examples/WEB-INF/classes/websocket/ExamplesConfig.class new file mode 100644 index 0000000..e4fde99 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/ExamplesConfig.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/ExamplesConfig.java b/tomcat/examples/WEB-INF/classes/websocket/ExamplesConfig.java new file mode 100644 index 0000000..ba8c60b --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/websocket/ExamplesConfig.java @@ -0,0 +1,66 @@ +/* + * 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. + */ +package websocket; + +import java.util.HashSet; +import java.util.Set; + +import javax.websocket.Endpoint; +import javax.websocket.server.ServerApplicationConfig; +import javax.websocket.server.ServerEndpointConfig; + +import websocket.drawboard.DrawboardEndpoint; +import websocket.echo.EchoEndpoint; + +public class ExamplesConfig implements ServerApplicationConfig { + + @Override + public Set getEndpointConfigs( + Set> scanned) { + + Set result = new HashSet<>(); + + if (scanned.contains(EchoEndpoint.class)) { + result.add(ServerEndpointConfig.Builder.create( + EchoEndpoint.class, + "/websocket/echoProgrammatic").build()); + } + + if (scanned.contains(DrawboardEndpoint.class)) { + result.add(ServerEndpointConfig.Builder.create( + DrawboardEndpoint.class, + "/websocket/drawboard").build()); + } + + return result; + } + + + @Override + public Set> getAnnotatedEndpointClasses(Set> scanned) { + // Deploy all WebSocket endpoints defined by annotations in the examples + // web application. Filter out all others to avoid issues when running + // tests on Gump + Set> results = new HashSet<>(); + for (Class clazz : scanned) { + if (clazz.getPackage().getName().startsWith("websocket.")) { + results.add(clazz); + } + } + return results; + } +} diff --git a/tomcat/examples/WEB-INF/classes/websocket/chat/ChatAnnotation.class b/tomcat/examples/WEB-INF/classes/websocket/chat/ChatAnnotation.class new file mode 100644 index 0000000..0dda34f Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/chat/ChatAnnotation.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/chat/ChatAnnotation.java b/tomcat/examples/WEB-INF/classes/websocket/chat/ChatAnnotation.java new file mode 100644 index 0000000..d1d5523 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/websocket/chat/ChatAnnotation.java @@ -0,0 +1,109 @@ +/* + * 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. + */ +package websocket.chat; + +import java.io.IOException; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArraySet; +import java.util.concurrent.atomic.AtomicInteger; + +import javax.websocket.OnClose; +import javax.websocket.OnError; +import javax.websocket.OnMessage; +import javax.websocket.OnOpen; +import javax.websocket.Session; +import javax.websocket.server.ServerEndpoint; + +import org.apache.juli.logging.Log; +import org.apache.juli.logging.LogFactory; + +import util.HTMLFilter; + +@ServerEndpoint(value = "/websocket/chat") +public class ChatAnnotation { + + private static final Log log = LogFactory.getLog(ChatAnnotation.class); + + private static final String GUEST_PREFIX = "Guest"; + private static final AtomicInteger connectionIds = new AtomicInteger(0); + private static final Set connections = + new CopyOnWriteArraySet<>(); + + private final String nickname; + private Session session; + + public ChatAnnotation() { + nickname = GUEST_PREFIX + connectionIds.getAndIncrement(); + } + + + @OnOpen + public void start(Session session) { + this.session = session; + connections.add(this); + String message = String.format("* %s %s", nickname, "has joined."); + broadcast(message); + } + + + @OnClose + public void end() { + connections.remove(this); + String message = String.format("* %s %s", + nickname, "has disconnected."); + broadcast(message); + } + + + @OnMessage + public void incoming(String message) { + // Never trust the client + String filteredMessage = String.format("%s: %s", + nickname, HTMLFilter.filter(message.toString())); + broadcast(filteredMessage); + } + + + + + @OnError + public void onError(Throwable t) throws Throwable { + log.error("Chat Error: " + t.toString(), t); + } + + + private static void broadcast(String msg) { + for (ChatAnnotation client : connections) { + try { + synchronized (client) { + client.session.getBasicRemote().sendText(msg); + } + } catch (IOException e) { + log.debug("Chat Error: Failed to send message to client", e); + connections.remove(client); + try { + client.session.close(); + } catch (IOException e1) { + // Ignore + } + String message = String.format("* %s %s", + client.nickname, "has been disconnected."); + broadcast(message); + } + } + } +} diff --git a/tomcat/examples/WEB-INF/classes/websocket/drawboard/Client$1.class b/tomcat/examples/WEB-INF/classes/websocket/drawboard/Client$1.class new file mode 100644 index 0000000..ad80e02 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/drawboard/Client$1.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/drawboard/Client.class b/tomcat/examples/WEB-INF/classes/websocket/drawboard/Client.class new file mode 100644 index 0000000..e5e234a Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/drawboard/Client.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/drawboard/Client.java b/tomcat/examples/WEB-INF/classes/websocket/drawboard/Client.java new file mode 100644 index 0000000..909950d --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/websocket/drawboard/Client.java @@ -0,0 +1,230 @@ +/* + * 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. + */ +package websocket.drawboard; + +import java.io.IOException; +import java.util.LinkedList; + +import javax.websocket.CloseReason; +import javax.websocket.CloseReason.CloseCodes; +import javax.websocket.RemoteEndpoint.Async; +import javax.websocket.SendHandler; +import javax.websocket.SendResult; +import javax.websocket.Session; + +import websocket.drawboard.wsmessages.AbstractWebsocketMessage; +import websocket.drawboard.wsmessages.BinaryWebsocketMessage; +import websocket.drawboard.wsmessages.CloseWebsocketMessage; +import websocket.drawboard.wsmessages.StringWebsocketMessage; + +/** + * Represents a client with methods to send messages asynchronously. + */ +public class Client { + + private final Session session; + private final Async async; + + /** + * Contains the messages which are buffered until the previous + * send operation has finished. + */ + private final LinkedList messagesToSend = + new LinkedList<>(); + /** + * If this client is currently sending a messages asynchronously. + */ + private volatile boolean isSendingMessage = false; + /** + * If this client is closing. If true, new messages to + * send will be ignored. + */ + private volatile boolean isClosing = false; + /** + * The length of all current buffered messages, to avoid iterating + * over a linked list. + */ + private volatile long messagesToSendLength = 0; + + public Client(Session session) { + this.session = session; + this.async = session.getAsyncRemote(); + } + + /** + * Asynchronously closes the Websocket session. This will wait until all + * remaining messages have been sent to the Client and then close + * the Websocket session. + */ + public void close() { + sendMessage(new CloseWebsocketMessage()); + } + + /** + * Sends the given message asynchronously to the client. + * If there is already a async sending in progress, then the message + * will be buffered and sent when possible.

    + * + * This method can be called from multiple threads. + * + * @param msg The message to send + */ + public void sendMessage(AbstractWebsocketMessage msg) { + synchronized (messagesToSend) { + if (!isClosing) { + // Check if we have a Close message + if (msg instanceof CloseWebsocketMessage) { + isClosing = true; + } + + if (isSendingMessage) { + // Check if the buffered messages exceed + // a specific amount - in that case, disconnect the client + // to prevent DoS. + // In this case we check if there are >= 1000 messages + // or length(of all messages) >= 1000000 bytes. + if (messagesToSend.size() >= 1000 + || messagesToSendLength >= 1000000) { + isClosing = true; + + // Discard the new message and close the session immediately. + CloseReason cr = new CloseReason( + CloseCodes.VIOLATED_POLICY, + "Send Buffer exceeded"); + try { + // TODO: close() may block if the remote endpoint doesn't read the data + // (eventually there will be a TimeoutException). However, this method + // (sendMessage) is intended to run asynchronous code and shouldn't + // block. Otherwise it would temporarily stop processing of messages + // from other clients. + // Maybe call this method on another thread. + // Note that when this method is called, the RemoteEndpoint.Async + // is still in the process of sending data, so there probably should + // be another way to abort the Websocket connection. + // Ideally, there should be some abort() method that cancels the + // connection immediately... + session.close(cr); + } catch (IOException e) { + // Ignore + } + + } else { + + // Check if the last message and the new message are + // String messages - in that case we concatenate them + // to reduce TCP overhead (using ";" as separator). + if (msg instanceof StringWebsocketMessage + && !messagesToSend.isEmpty() + && messagesToSend.getLast() + instanceof StringWebsocketMessage) { + + StringWebsocketMessage ms = + (StringWebsocketMessage) messagesToSend.removeLast(); + messagesToSendLength -= calculateMessageLength(ms); + + String concatenated = ms.getString() + ";" + + ((StringWebsocketMessage) msg).getString(); + msg = new StringWebsocketMessage(concatenated); + } + + messagesToSend.add(msg); + messagesToSendLength += calculateMessageLength(msg); + } + } else { + isSendingMessage = true; + internalSendMessageAsync(msg); + } + } + + } + } + + private long calculateMessageLength(AbstractWebsocketMessage msg) { + if (msg instanceof BinaryWebsocketMessage) { + return ((BinaryWebsocketMessage) msg).getBytes().capacity(); + } else if (msg instanceof StringWebsocketMessage) { + return ((StringWebsocketMessage) msg).getString().length() * 2; + } + + return 0; + } + + /** + * Internally sends the messages asynchronously. + * @param msg + */ + private void internalSendMessageAsync(AbstractWebsocketMessage msg) { + try { + if (msg instanceof StringWebsocketMessage) { + StringWebsocketMessage sMsg = (StringWebsocketMessage) msg; + async.sendText(sMsg.getString(), sendHandler); + + } else if (msg instanceof BinaryWebsocketMessage) { + BinaryWebsocketMessage bMsg = (BinaryWebsocketMessage) msg; + async.sendBinary(bMsg.getBytes(), sendHandler); + + } else if (msg instanceof CloseWebsocketMessage) { + // Close the session. + session.close(); + } + } catch (IllegalStateException|IOException ex) { + // Trying to write to the client when the session has + // already been closed. + // Ignore + } + } + + + + /** + * SendHandler that will continue to send buffered messages. + */ + private final SendHandler sendHandler = new SendHandler() { + @Override + public void onResult(SendResult result) { + if (!result.isOK()) { + // Message could not be sent. In this case, we don't + // set isSendingMessage to false because we must assume the connection + // broke (and onClose will be called), so we don't try to send + // other messages. + // As a precaution, we close the session (e.g. if a send timeout occurred). + // TODO: session.close() blocks, while this handler shouldn't block. + // Ideally, there should be some abort() method that cancels the + // connection immediately... + try { + session.close(); + } catch (IOException ex) { + // Ignore + } + } + synchronized (messagesToSend) { + + if (!messagesToSend.isEmpty()) { + AbstractWebsocketMessage msg = messagesToSend.remove(); + messagesToSendLength -= calculateMessageLength(msg); + + internalSendMessageAsync(msg); + + } else { + isSendingMessage = false; + } + + } + } + }; + +} diff --git a/tomcat/examples/WEB-INF/classes/websocket/drawboard/DrawMessage$ParseException.class b/tomcat/examples/WEB-INF/classes/websocket/drawboard/DrawMessage$ParseException.class new file mode 100644 index 0000000..e626852 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/drawboard/DrawMessage$ParseException.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/drawboard/DrawMessage.class b/tomcat/examples/WEB-INF/classes/websocket/drawboard/DrawMessage.class new file mode 100644 index 0000000..a1d9ce8 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/drawboard/DrawMessage.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/drawboard/DrawMessage.java b/tomcat/examples/WEB-INF/classes/websocket/drawboard/DrawMessage.java new file mode 100644 index 0000000..8dceaba --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/websocket/drawboard/DrawMessage.java @@ -0,0 +1,250 @@ +/* + * 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. + */ +package websocket.drawboard; + +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.geom.Arc2D; +import java.awt.geom.Line2D; +import java.awt.geom.Rectangle2D; + +/** + * A message that represents a drawing action. + * Note that we use primitive types instead of Point, Color etc. + * to reduce object allocation.

    + * + * TODO: But a Color objects needs to be created anyway for drawing this + * onto a Graphics2D object, so this probably does not save much. + */ +public final class DrawMessage { + + private int type; + private byte colorR, colorG, colorB, colorA; + private double thickness; + private double x1, y1, x2, y2; + + /** + * The type. + * + * @return 1: Brush
    2: Line
    3: Rectangle
    4: Ellipse + */ + public int getType() { + return type; + } + public void setType(int type) { + this.type = type; + } + + public double getThickness() { + return thickness; + } + public void setThickness(double thickness) { + this.thickness = thickness; + } + + public byte getColorR() { + return colorR; + } + public void setColorR(byte colorR) { + this.colorR = colorR; + } + public byte getColorG() { + return colorG; + } + public void setColorG(byte colorG) { + this.colorG = colorG; + } + public byte getColorB() { + return colorB; + } + public void setColorB(byte colorB) { + this.colorB = colorB; + } + public byte getColorA() { + return colorA; + } + public void setColorA(byte colorA) { + this.colorA = colorA; + } + + public double getX1() { + return x1; + } + public void setX1(double x1) { + this.x1 = x1; + } + public double getX2() { + return x2; + } + public void setX2(double x2) { + this.x2 = x2; + } + public double getY1() { + return y1; + } + public void setY1(double y1) { + this.y1 = y1; + } + public double getY2() { + return y2; + } + public void setY2(double y2) { + this.y2 = y2; + } + + + public DrawMessage(int type, byte colorR, byte colorG, byte colorB, + byte colorA, double thickness, double x1, double x2, double y1, + double y2) { + + this.type = type; + this.colorR = colorR; + this.colorG = colorG; + this.colorB = colorB; + this.colorA = colorA; + this.thickness = thickness; + this.x1 = x1; + this.x2 = x2; + this.y1 = y1; + this.y2 = y2; + } + + + /** + * Draws this DrawMessage onto the given Graphics2D. + * + * @param g The target for the DrawMessage + */ + public void draw(Graphics2D g) { + + g.setStroke(new BasicStroke((float) thickness, + BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER)); + g.setColor(new Color(colorR & 0xFF, colorG & 0xFF, colorB & 0xFF, + colorA & 0xFF)); + + if (x1 == x2 && y1 == y2) { + // Always draw as arc to meet the behavior in the HTML5 Canvas. + Arc2D arc = new Arc2D.Double(x1, y1, 0, 0, + 0d, 360d, Arc2D.OPEN); + g.draw(arc); + + } else if (type == 1 || type == 2) { + // Draw a line. + Line2D line = new Line2D.Double(x1, y1, x2, y2); + g.draw(line); + + } else if (type == 3 || type == 4) { + double x1 = this.x1, x2 = this.x2, + y1 = this.y1, y2 = this.y2; + if (x1 > x2) { + x1 = this.x2; + x2 = this.x1; + } + if (y1 > y2) { + y1 = this.y2; + y2 = this.y1; + } + + // TODO: If (x1 == x2 || y1 == y2) draw as line. + + if (type == 3) { + // Draw a rectangle. + Rectangle2D rect = new Rectangle2D.Double(x1, y1, + x2 - x1, y2 - y1); + g.draw(rect); + + } else if (type == 4) { + // Draw an ellipse. + Arc2D arc = new Arc2D.Double(x1, y1, x2 - x1, y2 - y1, + 0d, 360d, Arc2D.OPEN); + g.draw(arc); + + } + } + } + + /** + * Converts this message into a String representation that + * can be sent over WebSocket.
    + * Since a DrawMessage consists only of numbers, + * we concatenate those numbers with a ",". + */ + @Override + public String toString() { + + return type + "," + (colorR & 0xFF) + "," + (colorG & 0xFF) + "," + + (colorB & 0xFF) + "," + (colorA & 0xFF) + "," + thickness + + "," + x1 + "," + y1 + "," + x2 + "," + y2; + } + + public static DrawMessage parseFromString(String str) + throws ParseException { + + int type; + byte[] colors = new byte[4]; + double thickness; + double[] coords = new double[4]; + + try { + String[] elements = str.split(","); + + type = Integer.parseInt(elements[0]); + if (!(type >= 1 && type <= 4)) + throw new ParseException("Invalid type: " + type); + + for (int i = 0; i < colors.length; i++) { + colors[i] = (byte) Integer.parseInt(elements[1 + i]); + } + + thickness = Double.parseDouble(elements[5]); + if (Double.isNaN(thickness) || thickness < 0 || thickness > 100) + throw new ParseException("Invalid thickness: " + thickness); + + for (int i = 0; i < coords.length; i++) { + coords[i] = Double.parseDouble(elements[6 + i]); + if (Double.isNaN(coords[i])) + throw new ParseException("Invalid coordinate: " + + coords[i]); + } + + } catch (RuntimeException ex) { + throw new ParseException(ex); + } + + DrawMessage m = new DrawMessage(type, colors[0], colors[1], + colors[2], colors[3], thickness, coords[0], coords[2], + coords[1], coords[3]); + + return m; + } + + public static class ParseException extends Exception { + private static final long serialVersionUID = -6651972769789842960L; + + public ParseException(Throwable root) { + super(root); + } + + public ParseException(String message) { + super(message); + } + } + + + +} diff --git a/tomcat/examples/WEB-INF/classes/websocket/drawboard/DrawboardContextListener.class b/tomcat/examples/WEB-INF/classes/websocket/drawboard/DrawboardContextListener.class new file mode 100644 index 0000000..82f642b Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/drawboard/DrawboardContextListener.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/drawboard/DrawboardContextListener.java b/tomcat/examples/WEB-INF/classes/websocket/drawboard/DrawboardContextListener.java new file mode 100644 index 0000000..dd022ba --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/websocket/drawboard/DrawboardContextListener.java @@ -0,0 +1,37 @@ +/* + * 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. + */ +package websocket.drawboard; + +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; + +public final class DrawboardContextListener implements ServletContextListener { + + @Override + public void contextInitialized(ServletContextEvent sce) { + // NO-OP + } + + @Override + public void contextDestroyed(ServletContextEvent sce) { + // Shutdown our room. + Room room = DrawboardEndpoint.getRoom(false); + if (room != null) { + room.shutdown(); + } + } +} diff --git a/tomcat/examples/WEB-INF/classes/websocket/drawboard/DrawboardEndpoint$1.class b/tomcat/examples/WEB-INF/classes/websocket/drawboard/DrawboardEndpoint$1.class new file mode 100644 index 0000000..7cdff24 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/drawboard/DrawboardEndpoint$1.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/drawboard/DrawboardEndpoint$2.class b/tomcat/examples/WEB-INF/classes/websocket/drawboard/DrawboardEndpoint$2.class new file mode 100644 index 0000000..b333aed Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/drawboard/DrawboardEndpoint$2.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/drawboard/DrawboardEndpoint$3$1.class b/tomcat/examples/WEB-INF/classes/websocket/drawboard/DrawboardEndpoint$3$1.class new file mode 100644 index 0000000..2fd73e1 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/drawboard/DrawboardEndpoint$3$1.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/drawboard/DrawboardEndpoint$3.class b/tomcat/examples/WEB-INF/classes/websocket/drawboard/DrawboardEndpoint$3.class new file mode 100644 index 0000000..6907213 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/drawboard/DrawboardEndpoint$3.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/drawboard/DrawboardEndpoint.class b/tomcat/examples/WEB-INF/classes/websocket/drawboard/DrawboardEndpoint.class new file mode 100644 index 0000000..c8bdc8e Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/drawboard/DrawboardEndpoint.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/drawboard/DrawboardEndpoint.java b/tomcat/examples/WEB-INF/classes/websocket/drawboard/DrawboardEndpoint.java new file mode 100644 index 0000000..cd99f49 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/websocket/drawboard/DrawboardEndpoint.java @@ -0,0 +1,236 @@ +/* + * 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. + */ +package websocket.drawboard; + +import java.io.EOFException; +import java.io.IOException; + +import javax.websocket.CloseReason; +import javax.websocket.Endpoint; +import javax.websocket.EndpointConfig; +import javax.websocket.MessageHandler; +import javax.websocket.Session; + +import org.apache.juli.logging.Log; +import org.apache.juli.logging.LogFactory; + +import websocket.drawboard.DrawMessage.ParseException; +import websocket.drawboard.wsmessages.StringWebsocketMessage; + + +public final class DrawboardEndpoint extends Endpoint { + + private static final Log log = + LogFactory.getLog(DrawboardEndpoint.class); + + + /** + * Our room where players can join. + */ + private static volatile Room room = null; + private static final Object roomLock = new Object(); + + public static Room getRoom(boolean create) { + if (create) { + if (room == null) { + synchronized (roomLock) { + if (room == null) { + room = new Room(); + } + } + } + return room; + } else { + return room; + } + } + + /** + * The player that is associated with this Endpoint and the current room. + * Note that this variable is only accessed from the Room Thread.

    + * + * TODO: Currently, Tomcat uses an Endpoint instance once - however + * the java doc of endpoint says: + * "Each instance of a websocket endpoint is guaranteed not to be called by + * more than one thread at a time per active connection." + * This could mean that after calling onClose(), the instance + * could be reused for another connection so onOpen() will get called + * (possibly from another thread).
    + * If this is the case, we would need a variable holder for the variables + * that are accessed by the Room thread, and read the reference to the holder + * at the beginning of onOpen, onMessage, onClose methods to ensure the room + * thread always gets the correct instance of the variable holder. + */ + private Room.Player player; + + + @Override + public void onOpen(Session session, EndpointConfig config) { + // Set maximum messages size to 10.000 bytes. + session.setMaxTextMessageBufferSize(10000); + session.addMessageHandler(stringHandler); + final Client client = new Client(session); + + final Room room = getRoom(true); + room.invokeAndWait(new Runnable() { + @Override + public void run() { + try { + + // Create a new Player and add it to the room. + try { + player = room.createAndAddPlayer(client); + } catch (IllegalStateException ex) { + // Probably the max. number of players has been + // reached. + client.sendMessage(new StringWebsocketMessage( + "0" + ex.getLocalizedMessage())); + // Close the connection. + client.close(); + } + + } catch (RuntimeException ex) { + log.error("Unexpected exception: " + ex.toString(), ex); + } + } + }); + + } + + + @Override + public void onClose(Session session, CloseReason closeReason) { + Room room = getRoom(false); + if (room != null) { + room.invokeAndWait(new Runnable() { + @Override + public void run() { + try { + // Player can be null if it couldn't enter the room + if (player != null) { + // Remove this player from the room. + player.removeFromRoom(); + + // Set player to null to prevent NPEs when onMessage events + // are processed (from other threads) after onClose has been + // called from different thread which closed the Websocket session. + player = null; + } + } catch (RuntimeException ex) { + log.error("Unexpected exception: " + ex.toString(), ex); + } + } + }); + } + } + + + + @Override + public void onError(Session session, Throwable t) { + // Most likely cause is a user closing their browser. Check to see if + // the root cause is EOF and if it is ignore it. + // Protect against infinite loops. + int count = 0; + Throwable root = t; + while (root.getCause() != null && count < 20) { + root = root.getCause(); + count ++; + } + if (root instanceof EOFException) { + // Assume this is triggered by the user closing their browser and + // ignore it. + } else if (!session.isOpen() && root instanceof IOException) { + // IOException after close. Assume this is a variation of the user + // closing their browser (or refreshing very quickly) and ignore it. + } else { + log.error("onError: " + t.toString(), t); + } + } + + + + private final MessageHandler.Whole stringHandler = + new MessageHandler.Whole() { + + @Override + public void onMessage(final String message) { + // Invoke handling of the message in the room. + room.invokeAndWait(new Runnable() { + @Override + public void run() { + try { + + // Currently, the only types of messages the client will send + // are draw messages prefixed by a Message ID + // (starting with char '1'), and pong messages (starting + // with char '0'). + // Draw messages should look like this: + // ID|type,colR,colB,colG,colA,thickness,x1,y1,x2,y2,lastInChain + + boolean dontSwallowException = false; + try { + char messageType = message.charAt(0); + String messageContent = message.substring(1); + switch (messageType) { + case '0': + // Pong message. + // Do nothing. + break; + + case '1': + // Draw message + int indexOfChar = messageContent.indexOf('|'); + long msgId = Long.parseLong( + messageContent.substring(0, indexOfChar)); + + DrawMessage msg = DrawMessage.parseFromString( + messageContent.substring(indexOfChar + 1)); + + // Don't ignore RuntimeExceptions thrown by + // this method + // TODO: Find a better solution than this variable + dontSwallowException = true; + if (player != null) { + player.handleDrawMessage(msg, msgId); + } + dontSwallowException = false; + + break; + } + } catch (ParseException e) { + // Client sent invalid data + // Ignore, TODO: maybe close connection + } catch (RuntimeException e) { + // Client sent invalid data. + // Ignore, TODO: maybe close connection + if (dontSwallowException) { + throw e; + } + } + + } catch (RuntimeException ex) { + log.error("Unexpected exception: " + ex.toString(), ex); + } + } + }); + + } + }; + + +} diff --git a/tomcat/examples/WEB-INF/classes/websocket/drawboard/Room$1$1.class b/tomcat/examples/WEB-INF/classes/websocket/drawboard/Room$1$1.class new file mode 100644 index 0000000..7385358 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/drawboard/Room$1$1.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/drawboard/Room$1.class b/tomcat/examples/WEB-INF/classes/websocket/drawboard/Room$1.class new file mode 100644 index 0000000..b376454 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/drawboard/Room$1.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/drawboard/Room$2.class b/tomcat/examples/WEB-INF/classes/websocket/drawboard/Room$2.class new file mode 100644 index 0000000..461fd84 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/drawboard/Room$2.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/drawboard/Room$MessageType.class b/tomcat/examples/WEB-INF/classes/websocket/drawboard/Room$MessageType.class new file mode 100644 index 0000000..226f142 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/drawboard/Room$MessageType.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/drawboard/Room$Player.class b/tomcat/examples/WEB-INF/classes/websocket/drawboard/Room$Player.class new file mode 100644 index 0000000..cf194a5 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/drawboard/Room$Player.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/drawboard/Room.class b/tomcat/examples/WEB-INF/classes/websocket/drawboard/Room.class new file mode 100644 index 0000000..81910ec Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/drawboard/Room.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/drawboard/Room.java b/tomcat/examples/WEB-INF/classes/websocket/drawboard/Room.java new file mode 100644 index 0000000..1d839fc --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/websocket/drawboard/Room.java @@ -0,0 +1,496 @@ +/* + * 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. + */ +package websocket.drawboard; + +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Timer; +import java.util.TimerTask; +import java.util.concurrent.locks.ReentrantLock; + +import javax.imageio.ImageIO; + +import websocket.drawboard.wsmessages.BinaryWebsocketMessage; +import websocket.drawboard.wsmessages.StringWebsocketMessage; + +/** + * A Room represents a drawboard where a number of + * users participate.

    + * + * Note: Instance methods should only be invoked by calling + * {@link #invokeAndWait(Runnable)} to ensure access is correctly synchronized. + */ +public final class Room { + + /** + * Specifies the type of a room message that is sent to a client.
    + * Note: Currently we are sending simple string messages - for production + * apps, a JSON lib should be used for object-level messages.

    + * + * The number (single char) will be prefixed to the string when sending + * the message. + */ + public enum MessageType { + /** + * '0': Error: contains error message. + */ + ERROR('0'), + /** + * '1': DrawMessage: contains serialized DrawMessage(s) prefixed + * with the current Player's {@link Player#lastReceivedMessageId} + * and ",".
    + * Multiple draw messages are concatenated with "|" as separator. + */ + DRAW_MESSAGE('1'), + /** + * '2': ImageMessage: Contains number of current players in this room. + * After this message a Binary Websocket message will follow, + * containing the current Room image as PNG.
    + * This is the first message that a Room sends to a new Player. + */ + IMAGE_MESSAGE('2'), + /** + * '3': PlayerChanged: contains "+" or "-" which indicate a player + * was added or removed to this Room. + */ + PLAYER_CHANGED('3'); + + private final char flag; + + private MessageType(char flag) { + this.flag = flag; + } + + } + + + /** + * The lock used to synchronize access to this Room. + */ + private final ReentrantLock roomLock = new ReentrantLock(); + + /** + * Indicates if this room has already been shutdown. + */ + private volatile boolean closed = false; + + /** + * If true, outgoing DrawMessages will be buffered until the + * drawmessageBroadcastTimer ticks. Otherwise they will be sent + * immediately. + */ + private static final boolean BUFFER_DRAW_MESSAGES = true; + + /** + * A timer which sends buffered drawmessages to the client at once + * at a regular interval, to avoid sending a lot of very small + * messages which would cause TCP overhead and high CPU usage. + */ + private final Timer drawmessageBroadcastTimer = new Timer(); + + private static final int TIMER_DELAY = 30; + + /** + * The current active broadcast timer task. If null, then no Broadcast task is scheduled. + * The Task will be scheduled if the first player enters the Room, and + * cancelled if the last player exits the Room, to avoid unnecessary timer executions. + */ + private TimerTask activeBroadcastTimerTask; + + + /** + * The current image of the room drawboard. DrawMessages that are + * received from Players will be drawn onto this image. + */ + private final BufferedImage roomImage = + new BufferedImage(900, 600, BufferedImage.TYPE_INT_RGB); + private final Graphics2D roomGraphics = roomImage.createGraphics(); + + + /** + * The maximum number of players that can join this room. + */ + private static final int MAX_PLAYER_COUNT = 100; + + /** + * List of all currently joined players. + */ + private final List players = new ArrayList<>(); + + + + public Room() { + roomGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + + // Clear the image with white background. + roomGraphics.setBackground(Color.WHITE); + roomGraphics.clearRect(0, 0, roomImage.getWidth(), + roomImage.getHeight()); + } + + private TimerTask createBroadcastTimerTask() { + return new TimerTask() { + @Override + public void run() { + invokeAndWait(new Runnable() { + @Override + public void run() { + broadcastTimerTick(); + } + }); + } + }; + } + + /** + * Creates a Player from the given Client and adds it to this room. + * + * @param client the client + * + * @return The newly created player + */ + public Player createAndAddPlayer(Client client) { + if (players.size() >= MAX_PLAYER_COUNT) { + throw new IllegalStateException("Maximum player count (" + + MAX_PLAYER_COUNT + ") has been reached."); + } + + Player p = new Player(this, client); + + // Broadcast to the other players that one player joined. + broadcastRoomMessage(MessageType.PLAYER_CHANGED, "+"); + + // Add the new player to the list. + players.add(p); + + // If currently no Broadcast Timer Task is scheduled, then we need to create one. + if (activeBroadcastTimerTask == null) { + activeBroadcastTimerTask = createBroadcastTimerTask(); + drawmessageBroadcastTimer.schedule(activeBroadcastTimerTask, + TIMER_DELAY, TIMER_DELAY); + } + + // Send him the current number of players and the current room image. + String content = String.valueOf(players.size()); + p.sendRoomMessage(MessageType.IMAGE_MESSAGE, content); + + // Store image as PNG + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + try { + ImageIO.write(roomImage, "PNG", bout); + } catch (IOException e) { /* Should never happen */ } + + + // Send the image as binary message. + BinaryWebsocketMessage msg = new BinaryWebsocketMessage( + ByteBuffer.wrap(bout.toByteArray())); + p.getClient().sendMessage(msg); + + return p; + + } + + /** + * @see Player#removeFromRoom() + * @param p + */ + private void internalRemovePlayer(Player p) { + boolean removed = players.remove(p); + assert removed; + + // If the last player left the Room, we need to cancel the Broadcast Timer Task. + if (players.size() == 0) { + // Cancel the task. + // Note that it can happen that the TimerTask is just about to execute (from + // the Timer thread) but waits until all players are gone (or even until a new + // player is added to the list), and then executes. This is OK. To prevent it, + // a TimerTask subclass would need to have some boolean "cancel" instance variable and + // query it in the invocation of Room#invokeAndWait. + activeBroadcastTimerTask.cancel(); + activeBroadcastTimerTask = null; + } + + // Broadcast that one player is removed. + broadcastRoomMessage(MessageType.PLAYER_CHANGED, "-"); + } + + /** + * @see Player#handleDrawMessage(DrawMessage, long) + * @param p + * @param msg + * @param msgId + */ + private void internalHandleDrawMessage(Player p, DrawMessage msg, + long msgId) { + p.setLastReceivedMessageId(msgId); + + // Draw the RoomMessage onto our Room Image. + msg.draw(roomGraphics); + + // Broadcast the Draw Message. + broadcastDrawMessage(msg); + } + + + /** + * Broadcasts the given drawboard message to all connected players.
    + * Note: For DrawMessages, please use + * {@link #broadcastDrawMessage(DrawMessage)} + * as this method will buffer them and prefix them with the correct + * last received Message ID. + * @param type + * @param content + */ + private void broadcastRoomMessage(MessageType type, String content) { + for (Player p : players) { + p.sendRoomMessage(type, content); + } + } + + + /** + * Broadcast the given DrawMessage. This will buffer the message + * and the {@link #drawmessageBroadcastTimer} will broadcast them + * at a regular interval, prefixing them with the player's current + * {@link Player#lastReceivedMessageId}. + * @param msg + */ + private void broadcastDrawMessage(DrawMessage msg) { + if (!BUFFER_DRAW_MESSAGES) { + String msgStr = msg.toString(); + + for (Player p : players) { + String s = String.valueOf(p.getLastReceivedMessageId()) + + "," + msgStr; + p.sendRoomMessage(MessageType.DRAW_MESSAGE, s); + } + } else { + for (Player p : players) { + p.getBufferedDrawMessages().add(msg); + } + } + } + + + /** + * Tick handler for the broadcastTimer. + */ + private void broadcastTimerTick() { + // For each Player, send all per Player buffered + // DrawMessages, prefixing each DrawMessage with the player's + // lastReceivedMessageId. + // Multiple messages are concatenated with "|". + + for (Player p : players) { + + StringBuilder sb = new StringBuilder(); + List drawMessages = p.getBufferedDrawMessages(); + + if (drawMessages.size() > 0) { + for (int i = 0; i < drawMessages.size(); i++) { + DrawMessage msg = drawMessages.get(i); + + String s = String.valueOf(p.getLastReceivedMessageId()) + + "," + msg.toString(); + if (i > 0) + sb.append("|"); + + sb.append(s); + } + drawMessages.clear(); + + p.sendRoomMessage(MessageType.DRAW_MESSAGE, sb.toString()); + } + } + } + + /** + * A list of cached {@link Runnable}s to prevent recursive invocation of Runnables + * by one thread. This variable is only used by one thread at a time and then + * set to null. + */ + private List cachedRunnables = null; + + /** + * Submits the given Runnable to the Room Executor and waits until it + * has been executed. Currently, this simply means that the Runnable + * will be run directly inside of a synchronized() block.
    + * Note that if a runnable recursively calls invokeAndWait() with another + * runnable on this Room, it will not be executed recursively, but instead + * cached until the original runnable is finished, to keep the behavior of + * using a Executor. + * + * @param task The task to be executed + */ + public void invokeAndWait(Runnable task) { + + // Check if the current thread already holds a lock on this room. + // If yes, then we must not directly execute the Runnable but instead + // cache it until the original invokeAndWait() has finished. + if (roomLock.isHeldByCurrentThread()) { + + if (cachedRunnables == null) { + cachedRunnables = new ArrayList<>(); + } + cachedRunnables.add(task); + + } else { + + roomLock.lock(); + try { + // Explicitly overwrite value to ensure data consistency in + // current thread + cachedRunnables = null; + + if (!closed) { + task.run(); + } + + // Run the cached runnables. + if (cachedRunnables != null) { + for (int i = 0; i < cachedRunnables.size(); i++) { + if (!closed) { + cachedRunnables.get(i).run(); + } + } + cachedRunnables = null; + } + + } finally { + roomLock.unlock(); + } + + } + + } + + /** + * Shuts down the roomExecutor and the drawmessageBroadcastTimer. + */ + public void shutdown() { + invokeAndWait(new Runnable() { + @Override + public void run() { + closed = true; + drawmessageBroadcastTimer.cancel(); + roomGraphics.dispose(); + } + }); + } + + + /** + * A Player participates in a Room. It is the interface between the + * {@link Room} and the {@link Client}.

    + * + * Note: This means a player object is actually a join between Room and + * Client. + */ + public static final class Player { + + /** + * The room to which this player belongs. + */ + private Room room; + + /** + * The room buffers the last draw message ID that was received from + * this player. + */ + private long lastReceivedMessageId = 0; + + private final Client client; + + /** + * Buffered DrawMessages that will be sent by a Timer. + */ + private final List bufferedDrawMessages = + new ArrayList<>(); + + private List getBufferedDrawMessages() { + return bufferedDrawMessages; + } + + private Player(Room room, Client client) { + this.room = room; + this.client = client; + } + + public Room getRoom() { + return room; + } + + public Client getClient() { + return client; + } + + /** + * Removes this player from its room, e.g. when + * the client disconnects. + */ + public void removeFromRoom() { + if (room != null) { + room.internalRemovePlayer(this); + room = null; + } + } + + + private long getLastReceivedMessageId() { + return lastReceivedMessageId; + } + private void setLastReceivedMessageId(long value) { + lastReceivedMessageId = value; + } + + + /** + * Handles the given DrawMessage by drawing it onto this Room's + * image and by broadcasting it to the connected players. + * + * @param msg The draw message received + * @param msgId The ID for the draw message received + */ + public void handleDrawMessage(DrawMessage msg, long msgId) { + room.internalHandleDrawMessage(this, msg, msgId); + } + + + /** + * Sends the given room message. + * @param type + * @param content + */ + private void sendRoomMessage(MessageType type, String content) { + Objects.requireNonNull(content); + Objects.requireNonNull(type); + + String completeMsg = String.valueOf(type.flag) + content; + + client.sendMessage(new StringWebsocketMessage(completeMsg)); + } + } +} diff --git a/tomcat/examples/WEB-INF/classes/websocket/drawboard/wsmessages/AbstractWebsocketMessage.class b/tomcat/examples/WEB-INF/classes/websocket/drawboard/wsmessages/AbstractWebsocketMessage.class new file mode 100644 index 0000000..c6953a4 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/drawboard/wsmessages/AbstractWebsocketMessage.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/drawboard/wsmessages/AbstractWebsocketMessage.java b/tomcat/examples/WEB-INF/classes/websocket/drawboard/wsmessages/AbstractWebsocketMessage.java new file mode 100644 index 0000000..d425393 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/websocket/drawboard/wsmessages/AbstractWebsocketMessage.java @@ -0,0 +1,25 @@ +/* + * 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. + */ +package websocket.drawboard.wsmessages; + +/** + * Abstract base class for Websocket Messages (binary or string) + * that can be buffered. + */ +public abstract class AbstractWebsocketMessage { + +} diff --git a/tomcat/examples/WEB-INF/classes/websocket/drawboard/wsmessages/BinaryWebsocketMessage.class b/tomcat/examples/WEB-INF/classes/websocket/drawboard/wsmessages/BinaryWebsocketMessage.class new file mode 100644 index 0000000..ada7b34 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/drawboard/wsmessages/BinaryWebsocketMessage.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/drawboard/wsmessages/BinaryWebsocketMessage.java b/tomcat/examples/WEB-INF/classes/websocket/drawboard/wsmessages/BinaryWebsocketMessage.java new file mode 100644 index 0000000..b16e1ae --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/websocket/drawboard/wsmessages/BinaryWebsocketMessage.java @@ -0,0 +1,34 @@ +/* + * 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. + */ +package websocket.drawboard.wsmessages; + +import java.nio.ByteBuffer; + +/** + * Represents a binary websocket message. + */ +public final class BinaryWebsocketMessage extends AbstractWebsocketMessage { + private final ByteBuffer bytes; + + public BinaryWebsocketMessage(ByteBuffer bytes) { + this.bytes = bytes; + } + + public ByteBuffer getBytes() { + return bytes; + } +} diff --git a/tomcat/examples/WEB-INF/classes/websocket/drawboard/wsmessages/CloseWebsocketMessage.class b/tomcat/examples/WEB-INF/classes/websocket/drawboard/wsmessages/CloseWebsocketMessage.class new file mode 100644 index 0000000..f080cee Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/drawboard/wsmessages/CloseWebsocketMessage.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/drawboard/wsmessages/CloseWebsocketMessage.java b/tomcat/examples/WEB-INF/classes/websocket/drawboard/wsmessages/CloseWebsocketMessage.java new file mode 100644 index 0000000..44f48ad --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/websocket/drawboard/wsmessages/CloseWebsocketMessage.java @@ -0,0 +1,24 @@ +/* + * 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. + */ +package websocket.drawboard.wsmessages; + +/** + * Represents a "close" message that closes the session. + */ +public class CloseWebsocketMessage extends AbstractWebsocketMessage { + +} diff --git a/tomcat/examples/WEB-INF/classes/websocket/drawboard/wsmessages/StringWebsocketMessage.class b/tomcat/examples/WEB-INF/classes/websocket/drawboard/wsmessages/StringWebsocketMessage.class new file mode 100644 index 0000000..2c03f92 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/drawboard/wsmessages/StringWebsocketMessage.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/drawboard/wsmessages/StringWebsocketMessage.java b/tomcat/examples/WEB-INF/classes/websocket/drawboard/wsmessages/StringWebsocketMessage.java new file mode 100644 index 0000000..49be369 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/websocket/drawboard/wsmessages/StringWebsocketMessage.java @@ -0,0 +1,34 @@ +/* + * 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. + */ +package websocket.drawboard.wsmessages; + +/** + * Represents a string websocket message. + * + */ +public final class StringWebsocketMessage extends AbstractWebsocketMessage { + private final String string; + + public StringWebsocketMessage(String string) { + this.string = string; + } + + public String getString() { + return string; + } + +} diff --git a/tomcat/examples/WEB-INF/classes/websocket/echo/EchoAnnotation.class b/tomcat/examples/WEB-INF/classes/websocket/echo/EchoAnnotation.class new file mode 100644 index 0000000..a7c1a02 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/echo/EchoAnnotation.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/echo/EchoAnnotation.java b/tomcat/examples/WEB-INF/classes/websocket/echo/EchoAnnotation.java new file mode 100644 index 0000000..34f0de2 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/websocket/echo/EchoAnnotation.java @@ -0,0 +1,75 @@ +/* + * 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. + */ +package websocket.echo; + +import java.io.IOException; +import java.nio.ByteBuffer; + +import javax.websocket.OnMessage; +import javax.websocket.PongMessage; +import javax.websocket.Session; +import javax.websocket.server.ServerEndpoint; + +/** + * The three annotated echo endpoints can be used to test with Autobahn and + * the following command "wstest -m fuzzingclient -s servers.json". See the + * Autobahn documentation for setup and general information. + */ +@ServerEndpoint("/websocket/echoAnnotation") +public class EchoAnnotation { + + @OnMessage + public void echoTextMessage(Session session, String msg, boolean last) { + try { + if (session.isOpen()) { + session.getBasicRemote().sendText(msg, last); + } + } catch (IOException e) { + try { + session.close(); + } catch (IOException e1) { + // Ignore + } + } + } + + @OnMessage + public void echoBinaryMessage(Session session, ByteBuffer bb, + boolean last) { + try { + if (session.isOpen()) { + session.getBasicRemote().sendBinary(bb, last); + } + } catch (IOException e) { + try { + session.close(); + } catch (IOException e1) { + // Ignore + } + } + } + + /** + * Process a received pong. This is a NO-OP. + * + * @param pm Ignored. + */ + @OnMessage + public void echoPongMessage(PongMessage pm) { + // NO-OP + } +} diff --git a/tomcat/examples/WEB-INF/classes/websocket/echo/EchoAsyncAnnotation$1.class b/tomcat/examples/WEB-INF/classes/websocket/echo/EchoAsyncAnnotation$1.class new file mode 100644 index 0000000..8224f30 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/echo/EchoAsyncAnnotation$1.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/echo/EchoAsyncAnnotation$CompletedFuture.class b/tomcat/examples/WEB-INF/classes/websocket/echo/EchoAsyncAnnotation$CompletedFuture.class new file mode 100644 index 0000000..5ed8542 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/echo/EchoAsyncAnnotation$CompletedFuture.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/echo/EchoAsyncAnnotation.class b/tomcat/examples/WEB-INF/classes/websocket/echo/EchoAsyncAnnotation.class new file mode 100644 index 0000000..e4bd6c5 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/echo/EchoAsyncAnnotation.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/echo/EchoAsyncAnnotation.java b/tomcat/examples/WEB-INF/classes/websocket/echo/EchoAsyncAnnotation.java new file mode 100644 index 0000000..39df783 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/websocket/echo/EchoAsyncAnnotation.java @@ -0,0 +1,128 @@ +/* + * 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. + */ +package websocket.echo; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import javax.websocket.OnMessage; +import javax.websocket.PongMessage; +import javax.websocket.Session; + +/** + * The three annotated echo endpoints can be used to test with Autobahn and + * the following command "wstest -m fuzzingclient -s servers.json". See the + * Autobahn documentation for setup and general information. + * + * Note: This one is disabled by default since it allocates memory, and needs + * to be enabled back. + */ +//@javax.websocket.server.ServerEndpoint("/websocket/echoAsyncAnnotation") +public class EchoAsyncAnnotation { + + private static final Future COMPLETED = new CompletedFuture(); + + Future f = COMPLETED; + StringBuilder sb = null; + ByteArrayOutputStream bytes = null; + + @OnMessage + public void echoTextMessage(Session session, String msg, boolean last) { + if (sb == null) { + sb = new StringBuilder(); + } + sb.append(msg); + if (last) { + // Before we send the next message, have to wait for the previous + // message to complete + try { + f.get(); + } catch (InterruptedException | ExecutionException e) { + // Let the container deal with it + throw new RuntimeException(e); + } + f = session.getAsyncRemote().sendText(sb.toString()); + sb = null; + } + } + + @OnMessage + public void echoBinaryMessage(byte[] msg, Session session, boolean last) + throws IOException { + if (bytes == null) { + bytes = new ByteArrayOutputStream(); + } + bytes.write(msg); + if (last) { + // Before we send the next message, have to wait for the previous + // message to complete + try { + f.get(); + } catch (InterruptedException | ExecutionException e) { + // Let the container deal with it + throw new RuntimeException(e); + } + f = session.getAsyncRemote().sendBinary(ByteBuffer.wrap(bytes.toByteArray())); + bytes = null; + } + } + + /** + * Process a received pong. This is a NO-OP. + * + * @param pm Ignored. + */ + @OnMessage + public void echoPongMessage(PongMessage pm) { + // NO-OP + } + + private static class CompletedFuture implements Future { + + @Override + public boolean cancel(boolean mayInterruptIfRunning) { + return false; + } + + @Override + public boolean isCancelled() { + return false; + } + + @Override + public boolean isDone() { + return true; + } + + @Override + public Void get() throws InterruptedException, ExecutionException { + return null; + } + + @Override + public Void get(long timeout, TimeUnit unit) + throws InterruptedException, ExecutionException, + TimeoutException { + return null; + } + } +} diff --git a/tomcat/examples/WEB-INF/classes/websocket/echo/EchoEndpoint$1.class b/tomcat/examples/WEB-INF/classes/websocket/echo/EchoEndpoint$1.class new file mode 100644 index 0000000..0235572 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/echo/EchoEndpoint$1.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/echo/EchoEndpoint$EchoMessageHandlerBinary.class b/tomcat/examples/WEB-INF/classes/websocket/echo/EchoEndpoint$EchoMessageHandlerBinary.class new file mode 100644 index 0000000..e6a13ec Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/echo/EchoEndpoint$EchoMessageHandlerBinary.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/echo/EchoEndpoint$EchoMessageHandlerText.class b/tomcat/examples/WEB-INF/classes/websocket/echo/EchoEndpoint$EchoMessageHandlerText.class new file mode 100644 index 0000000..d159f56 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/echo/EchoEndpoint$EchoMessageHandlerText.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/echo/EchoEndpoint.class b/tomcat/examples/WEB-INF/classes/websocket/echo/EchoEndpoint.class new file mode 100644 index 0000000..fb2cdad Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/echo/EchoEndpoint.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/echo/EchoEndpoint.java b/tomcat/examples/WEB-INF/classes/websocket/echo/EchoEndpoint.java new file mode 100644 index 0000000..3620238 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/websocket/echo/EchoEndpoint.java @@ -0,0 +1,80 @@ +/* + * 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. + */ +package websocket.echo; + +import java.io.IOException; +import java.nio.ByteBuffer; + +import javax.websocket.Endpoint; +import javax.websocket.EndpointConfig; +import javax.websocket.MessageHandler; +import javax.websocket.RemoteEndpoint; +import javax.websocket.Session; + +public class EchoEndpoint extends Endpoint { + + @Override + public void onOpen(Session session, EndpointConfig endpointConfig) { + RemoteEndpoint.Basic remoteEndpointBasic = session.getBasicRemote(); + session.addMessageHandler(new EchoMessageHandlerText(remoteEndpointBasic)); + session.addMessageHandler(new EchoMessageHandlerBinary(remoteEndpointBasic)); + } + + private static class EchoMessageHandlerText + implements MessageHandler.Partial { + + private final RemoteEndpoint.Basic remoteEndpointBasic; + + private EchoMessageHandlerText(RemoteEndpoint.Basic remoteEndpointBasic) { + this.remoteEndpointBasic = remoteEndpointBasic; + } + + @Override + public void onMessage(String message, boolean last) { + try { + if (remoteEndpointBasic != null) { + remoteEndpointBasic.sendText(message, last); + } + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + + private static class EchoMessageHandlerBinary + implements MessageHandler.Partial { + + private final RemoteEndpoint.Basic remoteEndpointBasic; + + private EchoMessageHandlerBinary(RemoteEndpoint.Basic remoteEndpointBasic) { + this.remoteEndpointBasic = remoteEndpointBasic; + } + + @Override + public void onMessage(ByteBuffer message, boolean last) { + try { + if (remoteEndpointBasic != null) { + remoteEndpointBasic.sendBinary(message, last); + } + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } +} diff --git a/tomcat/examples/WEB-INF/classes/websocket/echo/EchoStreamAnnotation.class b/tomcat/examples/WEB-INF/classes/websocket/echo/EchoStreamAnnotation.class new file mode 100644 index 0000000..de6f561 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/echo/EchoStreamAnnotation.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/echo/EchoStreamAnnotation.java b/tomcat/examples/WEB-INF/classes/websocket/echo/EchoStreamAnnotation.java new file mode 100644 index 0000000..7aef821 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/websocket/echo/EchoStreamAnnotation.java @@ -0,0 +1,75 @@ +/* + * 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. + */ +package websocket.echo; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.Writer; + +import javax.websocket.OnMessage; +import javax.websocket.PongMessage; +import javax.websocket.Session; +import javax.websocket.server.ServerEndpoint; + +/** + * The three annotated echo endpoints can be used to test with Autobahn and + * the following command "wstest -m fuzzingclient -s servers.json". See the + * Autobahn documentation for setup and general information. + */ +@ServerEndpoint("/websocket/echoStreamAnnotation") +public class EchoStreamAnnotation { + + Writer writer; + OutputStream stream; + + @OnMessage + public void echoTextMessage(Session session, String msg, boolean last) + throws IOException { + if (writer == null) { + writer = session.getBasicRemote().getSendWriter(); + } + writer.write(msg); + if (last) { + writer.close(); + writer = null; + } + } + + @OnMessage + public void echoBinaryMessage(byte[] msg, Session session, boolean last) + throws IOException { + if (stream == null) { + stream = session.getBasicRemote().getSendStream(); + } + stream.write(msg); + stream.flush(); + if (last) { + stream.close(); + stream = null; + } + } + + /** + * Process a received pong. This is a NO-OP. + * + * @param pm Ignored. + */ + @OnMessage + public void echoPongMessage(PongMessage pm) { + // NO-OP + } +} diff --git a/tomcat/examples/WEB-INF/classes/websocket/echo/servers.json b/tomcat/examples/WEB-INF/classes/websocket/echo/servers.json new file mode 100644 index 0000000..c816a7d --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/websocket/echo/servers.json @@ -0,0 +1,20 @@ +{ + "options": {"failByDrop": false}, + "outdir": "./reports/servers", + + "servers": [ + {"agent": "Basic", + "url": "ws://localhost:8080/examples/websocket/echoAnnotation", + "options": {"version": 18}}, + {"agent": "Stream", + "url": "ws://localhost:8080/examples/websocket/echoStreamAnnotation", + "options": {"version": 18}}, + {"agent": "Async", + "url": "ws://localhost:8080/examples/websocket/echoAsyncAnnotation", + "options": {"version": 18}} + ], + + "cases": ["*"], + "exclude-cases": [], + "exclude-agent-cases": {} +} diff --git a/tomcat/examples/WEB-INF/classes/websocket/snake/Direction.class b/tomcat/examples/WEB-INF/classes/websocket/snake/Direction.class new file mode 100644 index 0000000..9db474e Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/snake/Direction.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/snake/Direction.java b/tomcat/examples/WEB-INF/classes/websocket/snake/Direction.java new file mode 100644 index 0000000..4440c9d --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/websocket/snake/Direction.java @@ -0,0 +1,21 @@ +/* + * 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. + */ +package websocket.snake; + +public enum Direction { + NONE, NORTH, SOUTH, EAST, WEST +} diff --git a/tomcat/examples/WEB-INF/classes/websocket/snake/Location$1.class b/tomcat/examples/WEB-INF/classes/websocket/snake/Location$1.class new file mode 100644 index 0000000..a5ac306 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/snake/Location$1.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/snake/Location.class b/tomcat/examples/WEB-INF/classes/websocket/snake/Location.class new file mode 100644 index 0000000..284addb Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/snake/Location.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/snake/Location.java b/tomcat/examples/WEB-INF/classes/websocket/snake/Location.java new file mode 100644 index 0000000..acbfeb7 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/websocket/snake/Location.java @@ -0,0 +1,65 @@ +/* + * 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. + */ +package websocket.snake; + +public class Location { + + public int x; + public int y; + + public Location(int x, int y) { + this.x = x; + this.y = y; + } + + public Location getAdjacentLocation(Direction direction) { + switch (direction) { + case NORTH: + return new Location(x, y - SnakeAnnotation.GRID_SIZE); + case SOUTH: + return new Location(x, y + SnakeAnnotation.GRID_SIZE); + case EAST: + return new Location(x + SnakeAnnotation.GRID_SIZE, y); + case WEST: + return new Location(x - SnakeAnnotation.GRID_SIZE, y); + case NONE: + // fall through + default: + return this; + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Location location = (Location) o; + + if (x != location.x) return false; + if (y != location.y) return false; + + return true; + } + + @Override + public int hashCode() { + int result = x; + result = 31 * result + y; + return result; + } +} diff --git a/tomcat/examples/WEB-INF/classes/websocket/snake/Snake.class b/tomcat/examples/WEB-INF/classes/websocket/snake/Snake.class new file mode 100644 index 0000000..afdcf77 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/snake/Snake.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/snake/Snake.java b/tomcat/examples/WEB-INF/classes/websocket/snake/Snake.java new file mode 100644 index 0000000..7a11222 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/websocket/snake/Snake.java @@ -0,0 +1,150 @@ +/* + * 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. + */ +package websocket.snake; + +import java.io.IOException; +import java.util.ArrayDeque; +import java.util.Collection; +import java.util.Deque; + +import javax.websocket.CloseReason; +import javax.websocket.CloseReason.CloseCodes; +import javax.websocket.Session; + +public class Snake { + + private static final int DEFAULT_LENGTH = 5; + + private final int id; + private final Session session; + + private Direction direction; + private int length = DEFAULT_LENGTH; + private Location head; + private final Deque tail = new ArrayDeque<>(); + private final String hexColor; + + public Snake(int id, Session session) { + this.id = id; + this.session = session; + this.hexColor = SnakeAnnotation.getRandomHexColor(); + resetState(); + } + + private void resetState() { + this.direction = Direction.NONE; + this.head = SnakeAnnotation.getRandomLocation(); + this.tail.clear(); + this.length = DEFAULT_LENGTH; + } + + private synchronized void kill() { + resetState(); + sendMessage("{\"type\": \"dead\"}"); + } + + private synchronized void reward() { + length++; + sendMessage("{\"type\": \"kill\"}"); + } + + + protected void sendMessage(String msg) { + try { + session.getBasicRemote().sendText(msg); + } catch (IOException ioe) { + CloseReason cr = + new CloseReason(CloseCodes.CLOSED_ABNORMALLY, ioe.getMessage()); + try { + session.close(cr); + } catch (IOException ioe2) { + // Ignore + } + } + } + + public synchronized void update(Collection snakes) { + Location nextLocation = head.getAdjacentLocation(direction); + if (nextLocation.x >= SnakeAnnotation.PLAYFIELD_WIDTH) { + nextLocation.x = 0; + } + if (nextLocation.y >= SnakeAnnotation.PLAYFIELD_HEIGHT) { + nextLocation.y = 0; + } + if (nextLocation.x < 0) { + nextLocation.x = SnakeAnnotation.PLAYFIELD_WIDTH; + } + if (nextLocation.y < 0) { + nextLocation.y = SnakeAnnotation.PLAYFIELD_HEIGHT; + } + if (direction != Direction.NONE) { + tail.addFirst(head); + if (tail.size() > length) { + tail.removeLast(); + } + head = nextLocation; + } + + handleCollisions(snakes); + } + + private void handleCollisions(Collection snakes) { + for (Snake snake : snakes) { + boolean headCollision = id != snake.id && snake.getHead().equals(head); + boolean tailCollision = snake.getTail().contains(head); + if (headCollision || tailCollision) { + kill(); + if (id != snake.id) { + snake.reward(); + } + } + } + } + + public synchronized Location getHead() { + return head; + } + + public synchronized Collection getTail() { + return tail; + } + + public synchronized void setDirection(Direction direction) { + this.direction = direction; + } + + public synchronized String getLocationsJson() { + StringBuilder sb = new StringBuilder(); + sb.append(String.format("{\"x\": %d, \"y\": %d}", + Integer.valueOf(head.x), Integer.valueOf(head.y))); + for (Location location : tail) { + sb.append(','); + sb.append(String.format("{\"x\": %d, \"y\": %d}", + Integer.valueOf(location.x), Integer.valueOf(location.y))); + } + return String.format("{\"id\":%d,\"body\":[%s]}", + Integer.valueOf(id), sb.toString()); + } + + public int getId() { + return id; + } + + public String getHexColor() { + return hexColor; + } +} diff --git a/tomcat/examples/WEB-INF/classes/websocket/snake/SnakeAnnotation.class b/tomcat/examples/WEB-INF/classes/websocket/snake/SnakeAnnotation.class new file mode 100644 index 0000000..266344c Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/snake/SnakeAnnotation.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/snake/SnakeAnnotation.java b/tomcat/examples/WEB-INF/classes/websocket/snake/SnakeAnnotation.java new file mode 100644 index 0000000..c030dbc --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/websocket/snake/SnakeAnnotation.java @@ -0,0 +1,135 @@ +/* + * 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. + */ +package websocket.snake; + +import java.awt.Color; +import java.io.EOFException; +import java.util.Iterator; +import java.util.Random; +import java.util.concurrent.atomic.AtomicInteger; + +import javax.websocket.OnClose; +import javax.websocket.OnError; +import javax.websocket.OnMessage; +import javax.websocket.OnOpen; +import javax.websocket.Session; +import javax.websocket.server.ServerEndpoint; + +@ServerEndpoint(value = "/websocket/snake") +public class SnakeAnnotation { + + public static final int PLAYFIELD_WIDTH = 640; + public static final int PLAYFIELD_HEIGHT = 480; + public static final int GRID_SIZE = 10; + + private static final AtomicInteger snakeIds = new AtomicInteger(0); + private static final Random random = new Random(); + + + private final int id; + private Snake snake; + + public static String getRandomHexColor() { + float hue = random.nextFloat(); + // sat between 0.1 and 0.3 + float saturation = (random.nextInt(2000) + 1000) / 10000f; + float luminance = 0.9f; + Color color = Color.getHSBColor(hue, saturation, luminance); + return '#' + Integer.toHexString( + (color.getRGB() & 0xffffff) | 0x1000000).substring(1); + } + + + public static Location getRandomLocation() { + int x = roundByGridSize(random.nextInt(PLAYFIELD_WIDTH)); + int y = roundByGridSize(random.nextInt(PLAYFIELD_HEIGHT)); + return new Location(x, y); + } + + + private static int roundByGridSize(int value) { + value = value + (GRID_SIZE / 2); + value = value / GRID_SIZE; + value = value * GRID_SIZE; + return value; + } + + public SnakeAnnotation() { + this.id = snakeIds.getAndIncrement(); + } + + + @OnOpen + public void onOpen(Session session) { + this.snake = new Snake(id, session); + SnakeTimer.addSnake(snake); + StringBuilder sb = new StringBuilder(); + for (Iterator iterator = SnakeTimer.getSnakes().iterator(); + iterator.hasNext();) { + Snake snake = iterator.next(); + sb.append(String.format("{\"id\": %d, \"color\": \"%s\"}", + Integer.valueOf(snake.getId()), snake.getHexColor())); + if (iterator.hasNext()) { + sb.append(','); + } + } + SnakeTimer.broadcast(String.format("{\"type\": \"join\",\"data\":[%s]}", + sb.toString())); + } + + + @OnMessage + public void onTextMessage(String message) { + if ("west".equals(message)) { + snake.setDirection(Direction.WEST); + } else if ("north".equals(message)) { + snake.setDirection(Direction.NORTH); + } else if ("east".equals(message)) { + snake.setDirection(Direction.EAST); + } else if ("south".equals(message)) { + snake.setDirection(Direction.SOUTH); + } + } + + + @OnClose + public void onClose() { + SnakeTimer.removeSnake(snake); + SnakeTimer.broadcast(String.format("{\"type\": \"leave\", \"id\": %d}", + Integer.valueOf(id))); + } + + + @OnError + public void onError(Throwable t) throws Throwable { + // Most likely cause is a user closing their browser. Check to see if + // the root cause is EOF and if it is ignore it. + // Protect against infinite loops. + int count = 0; + Throwable root = t; + while (root.getCause() != null && count < 20) { + root = root.getCause(); + count ++; + } + if (root instanceof EOFException) { + // Assume this is triggered by the user closing their browser and + // ignore it. + } else { + throw t; + } + } +} diff --git a/tomcat/examples/WEB-INF/classes/websocket/snake/SnakeTimer$1.class b/tomcat/examples/WEB-INF/classes/websocket/snake/SnakeTimer$1.class new file mode 100644 index 0000000..59e00f4 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/snake/SnakeTimer$1.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/snake/SnakeTimer.class b/tomcat/examples/WEB-INF/classes/websocket/snake/SnakeTimer.class new file mode 100644 index 0000000..0ba3089 Binary files /dev/null and b/tomcat/examples/WEB-INF/classes/websocket/snake/SnakeTimer.class differ diff --git a/tomcat/examples/WEB-INF/classes/websocket/snake/SnakeTimer.java b/tomcat/examples/WEB-INF/classes/websocket/snake/SnakeTimer.java new file mode 100644 index 0000000..0115413 --- /dev/null +++ b/tomcat/examples/WEB-INF/classes/websocket/snake/SnakeTimer.java @@ -0,0 +1,115 @@ +/* + * 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. + */ +package websocket.snake; + +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; +import java.util.Timer; +import java.util.TimerTask; +import java.util.concurrent.ConcurrentHashMap; + +import org.apache.juli.logging.Log; +import org.apache.juli.logging.LogFactory; + +/** + * Sets up the timer for the multi-player snake game WebSocket example. + */ +public class SnakeTimer { + + private static final Log log = + LogFactory.getLog(SnakeTimer.class); + + private static Timer gameTimer = null; + + private static final long TICK_DELAY = 100; + + private static final ConcurrentHashMap snakes = + new ConcurrentHashMap<>(); + + protected static synchronized void addSnake(Snake snake) { + if (snakes.size() == 0) { + startTimer(); + } + snakes.put(Integer.valueOf(snake.getId()), snake); + } + + + protected static Collection getSnakes() { + return Collections.unmodifiableCollection(snakes.values()); + } + + + protected static synchronized void removeSnake(Snake snake) { + snakes.remove(Integer.valueOf(snake.getId())); + if (snakes.size() == 0) { + stopTimer(); + } + } + + + protected static void tick() { + StringBuilder sb = new StringBuilder(); + for (Iterator iterator = SnakeTimer.getSnakes().iterator(); + iterator.hasNext();) { + Snake snake = iterator.next(); + snake.update(SnakeTimer.getSnakes()); + sb.append(snake.getLocationsJson()); + if (iterator.hasNext()) { + sb.append(','); + } + } + broadcast(String.format("{\"type\": \"update\", \"data\" : [%s]}", + sb.toString())); + } + + protected static void broadcast(String message) { + for (Snake snake : SnakeTimer.getSnakes()) { + try { + snake.sendMessage(message); + } catch (IllegalStateException ise) { + // An ISE can occur if an attempt is made to write to a + // WebSocket connection after it has been closed. The + // alternative to catching this exception is to synchronise + // the writes to the clients along with the addSnake() and + // removeSnake() methods that are already synchronised. + } + } + } + + + public static void startTimer() { + gameTimer = new Timer(SnakeTimer.class.getSimpleName() + " Timer"); + gameTimer.scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + try { + tick(); + } catch (RuntimeException e) { + log.error("Caught to prevent timer from shutting down", e); + } + } + }, TICK_DELAY, TICK_DELAY); + } + + + public static void stopTimer() { + if (gameTimer != null) { + gameTimer.cancel(); + } + } +} diff --git a/tomcat/examples/WEB-INF/jsp/applet/Clock2.java b/tomcat/examples/WEB-INF/jsp/applet/Clock2.java new file mode 100644 index 0000000..c745815 --- /dev/null +++ b/tomcat/examples/WEB-INF/jsp/applet/Clock2.java @@ -0,0 +1,230 @@ +/* +* 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. +*/ + +import java.applet.Applet; +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; + +/** + * Time! + * + * @author Rachel Gollub + */ + +public class Clock2 extends Applet implements Runnable { + private static final long serialVersionUID = 1L; + Thread timer; // The thread that displays clock + int lastxs, lastys, lastxm, + lastym, lastxh, lastyh; // Dimensions used to draw hands + SimpleDateFormat formatter; // Formats the date displayed + String lastdate; // String to hold date displayed + Font clockFaceFont; // Font for number display on clock + Date currentDate; // Used to get date to display + Color handColor; // Color of main hands and dial + Color numberColor; // Color of second hand and numbers + + @Override + public void init() { + lastxs = lastys = lastxm = lastym = lastxh = lastyh = 0; + formatter = new SimpleDateFormat ("EEE MMM dd hh:mm:ss yyyy", Locale.getDefault()); + currentDate = new Date(); + lastdate = formatter.format(currentDate); + clockFaceFont = new Font("Serif", Font.PLAIN, 14); + handColor = Color.blue; + numberColor = Color.darkGray; + + try { + setBackground(new Color(Integer.parseInt(getParameter("bgcolor"),16))); + } catch (Exception e) { + // Ignore + } + try { + handColor = new Color(Integer.parseInt(getParameter("fgcolor1"),16)); + } catch (Exception e) { + // Ignore + } + try { + numberColor = new Color(Integer.parseInt(getParameter("fgcolor2"),16)); + } catch (Exception e) { + // Ignore + } + resize(300,300); // Set clock window size + } + + // Plotpoints allows calculation to only cover 45 degrees of the circle, + // and then mirror + public void plotpoints(int x0, int y0, int x, int y, Graphics g) { + g.drawLine(x0+x,y0+y,x0+x,y0+y); + g.drawLine(x0+y,y0+x,x0+y,y0+x); + g.drawLine(x0+y,y0-x,x0+y,y0-x); + g.drawLine(x0+x,y0-y,x0+x,y0-y); + g.drawLine(x0-x,y0-y,x0-x,y0-y); + g.drawLine(x0-y,y0-x,x0-y,y0-x); + g.drawLine(x0-y,y0+x,x0-y,y0+x); + g.drawLine(x0-x,y0+y,x0-x,y0+y); + } + + // Circle is just Bresenham's algorithm for a scan converted circle + public void circle(int x0, int y0, int r, Graphics g) { + int x,y; + float d; + x=0; + y=r; + d=5/4-r; + plotpoints(x0,y0,x,y,g); + + while (y>x){ + if (d<0) { + d=d+2*x+3; + x++; + } + else { + d=d+2*(x-y)+5; + x++; + y--; + } + plotpoints(x0,y0,x,y,g); + } + } + + // Paint is the main part of the program + @Override + public void paint(Graphics g) { + int xh, yh, xm, ym, xs, ys, s = 0, m = 10, h = 10, xcenter, ycenter; + String today; + + currentDate = new Date(); + SimpleDateFormat formatter = new SimpleDateFormat("s",Locale.getDefault()); + try { + s = Integer.parseInt(formatter.format(currentDate)); + } catch (NumberFormatException n) { + s = 0; + } + formatter.applyPattern("m"); + try { + m = Integer.parseInt(formatter.format(currentDate)); + } catch (NumberFormatException n) { + m = 10; + } + formatter.applyPattern("h"); + try { + h = Integer.parseInt(formatter.format(currentDate)); + } catch (NumberFormatException n) { + h = 10; + } + formatter.applyPattern("EEE MMM dd HH:mm:ss yyyy"); + today = formatter.format(currentDate); + xcenter=80; + ycenter=55; + + // a= s* pi/2 - pi/2 (to switch 0,0 from 3:00 to 12:00) + // x = r(cos a) + xcenter, y = r(sin a) + ycenter + + xs = (int)(Math.cos(s * Math.PI/30 - Math.PI/2) * 45 + xcenter); + ys = (int)(Math.sin(s * Math.PI/30 - Math.PI/2) * 45 + ycenter); + xm = (int)(Math.cos(m * Math.PI/30 - Math.PI/2) * 40 + xcenter); + ym = (int)(Math.sin(m * Math.PI/30 - Math.PI/2) * 40 + ycenter); + xh = (int)(Math.cos((h*30 + m/2) * Math.PI/180 - Math.PI/2) * 30 + xcenter); + yh = (int)(Math.sin((h*30 + m/2) * Math.PI/180 - Math.PI/2) * 30 + ycenter); + + // Draw the circle and numbers + + g.setFont(clockFaceFont); + g.setColor(handColor); + circle(xcenter,ycenter,50,g); + g.setColor(numberColor); + g.drawString("9",xcenter-45,ycenter+3); + g.drawString("3",xcenter+40,ycenter+3); + g.drawString("12",xcenter-5,ycenter-37); + g.drawString("6",xcenter-3,ycenter+45); + + // Erase if necessary, and redraw + + g.setColor(getBackground()); + if (xs != lastxs || ys != lastys) { + g.drawLine(xcenter, ycenter, lastxs, lastys); + g.drawString(lastdate, 5, 125); + } + if (xm != lastxm || ym != lastym) { + g.drawLine(xcenter, ycenter-1, lastxm, lastym); + g.drawLine(xcenter-1, ycenter, lastxm, lastym); } + if (xh != lastxh || yh != lastyh) { + g.drawLine(xcenter, ycenter-1, lastxh, lastyh); + g.drawLine(xcenter-1, ycenter, lastxh, lastyh); } + g.setColor(numberColor); + g.drawString("", 5, 125); + g.drawString(today, 5, 125); + g.drawLine(xcenter, ycenter, xs, ys); + g.setColor(handColor); + g.drawLine(xcenter, ycenter-1, xm, ym); + g.drawLine(xcenter-1, ycenter, xm, ym); + g.drawLine(xcenter, ycenter-1, xh, yh); + g.drawLine(xcenter-1, ycenter, xh, yh); + lastxs=xs; lastys=ys; + lastxm=xm; lastym=ym; + lastxh=xh; lastyh=yh; + lastdate = today; + currentDate=null; + } + + @Override + public void start() { + timer = new Thread(this); + timer.start(); + } + + @Override + public void stop() { + timer = null; + } + + @Override + public void run() { + Thread me = Thread.currentThread(); + while (timer == me) { + try { + Thread.sleep(100); + } catch (InterruptedException e) { + } + repaint(); + } + } + + @Override + public void update(Graphics g) { + paint(g); + } + + @Override + public String getAppletInfo() { + return "Title: A Clock \nAuthor: Rachel Gollub, 1995 \nAn analog clock."; + } + + @Override + public String[][] getParameterInfo() { + String[][] info = { + {"bgcolor", "hexadecimal RGB number", "The background color. Default is the color of your browser."}, + {"fgcolor1", "hexadecimal RGB number", "The color of the hands and dial. Default is blue."}, + {"fgcolor2", "hexadecimal RGB number", "The color of the seconds hand and numbers. Default is dark gray."} + }; + return info; + } +} diff --git a/tomcat/examples/WEB-INF/jsp/debug-taglib.tld b/tomcat/examples/WEB-INF/jsp/debug-taglib.tld new file mode 100644 index 0000000..8f082d3 --- /dev/null +++ b/tomcat/examples/WEB-INF/jsp/debug-taglib.tld @@ -0,0 +1,54 @@ + + + + + + + + 1.0 + 1.2 + debug + http://tomcat.apache.org/debug-taglib + + This tag library defines no tags. Instead, its purpose is encapsulated + in the TagLibraryValidator implementation that simply outputs the XML + version of a JSP page to standard output, whenever this tag library is + referenced in a "taglib" directive in a JSP page. + + + validators.DebugValidator + + + + + log + examples.LogTag + TAGDEPENDENT + + Perform a server side action; Log the message. + + + toBrowser + false + + + + + diff --git a/tomcat/examples/WEB-INF/jsp/example-taglib.tld b/tomcat/examples/WEB-INF/jsp/example-taglib.tld new file mode 100644 index 0000000..714e201 --- /dev/null +++ b/tomcat/examples/WEB-INF/jsp/example-taglib.tld @@ -0,0 +1,107 @@ + + + + + + + 1.0 + 1.2 + simple + http://tomcat.apache.org/example-taglib + + A simple tab library for the examples + + + + + + foo + examples.FooTag + examples.FooTagExtraInfo + JSP + + Perform a server side action; uses 3 mandatory attributes + + + + att1 + true + + + att2 + true + + + att3 + true + + + + + + + log + examples.LogTag + TAGDEPENDENT + + Perform a server side action; Log the message. + + + toBrowser + false + + + + + + + values + examples.ValuesTag + empty + + Accept and return values of different types. This tag is used + to illustrate type coercions. + + + object + false + true + java.lang.Object + + + string + false + true + java.lang.String + + + long + false + true + long + + + double + false + true + double + + + diff --git a/tomcat/examples/WEB-INF/jsp2/jsp2-example-taglib.tld b/tomcat/examples/WEB-INF/jsp2/jsp2-example-taglib.tld new file mode 100644 index 0000000..73173bd --- /dev/null +++ b/tomcat/examples/WEB-INF/jsp2/jsp2-example-taglib.tld @@ -0,0 +1,124 @@ + + + + + A tag library exercising SimpleTag handlers. + 1.0 + SimpleTagLibrary + http://tomcat.apache.org/jsp2-example-taglib + + Outputs Hello, World + helloWorld + jsp2.examples.simpletag.HelloWorldSimpleTag + empty + + + Repeats the body of the tag 'num' times + repeat + jsp2.examples.simpletag.RepeatSimpleTag + scriptless + + Current invocation count (1 to num) + count + + + num + true + true + + + + Populates the page context with a BookBean + findBook + jsp2.examples.simpletag.FindBookSimpleTag + empty + + var + true + true + + + + + Takes 3 fragments and invokes them in a random order + + shuffle + jsp2.examples.simpletag.ShuffleSimpleTag + empty + + fragment1 + true + true + + + fragment2 + true + true + + + fragment3 + true + true + + + + Outputs a colored tile + tile + jsp2.examples.simpletag.TileSimpleTag + empty + + color + true + + + label + true + + + + + Tag that echoes all its attributes and body content + + echoAttributes + jsp2.examples.simpletag.EchoAttributesTag + empty + true + + + Reverses the characters in the given String + reverse + jsp2.examples.el.Functions + java.lang.String reverse( java.lang.String ) + + + Counts the number of vowels (a,e,i,o,u) in the given String + countVowels + jsp2.examples.el.Functions + java.lang.String numVowels( java.lang.String ) + + + Converts the string to all caps + caps + jsp2.examples.el.Functions + java.lang.String caps( java.lang.String ) + + + diff --git a/tomcat/examples/WEB-INF/lib/taglibs-standard-impl-1.2.5.jar b/tomcat/examples/WEB-INF/lib/taglibs-standard-impl-1.2.5.jar new file mode 100644 index 0000000..9176777 Binary files /dev/null and b/tomcat/examples/WEB-INF/lib/taglibs-standard-impl-1.2.5.jar differ diff --git a/tomcat/examples/WEB-INF/lib/taglibs-standard-spec-1.2.5.jar b/tomcat/examples/WEB-INF/lib/taglibs-standard-spec-1.2.5.jar new file mode 100644 index 0000000..d547867 Binary files /dev/null and b/tomcat/examples/WEB-INF/lib/taglibs-standard-spec-1.2.5.jar differ diff --git a/tomcat/examples/WEB-INF/tags/displayProducts.tag b/tomcat/examples/WEB-INF/tags/displayProducts.tag new file mode 100644 index 0000000..41e8c35 --- /dev/null +++ b/tomcat/examples/WEB-INF/tags/displayProducts.tag @@ -0,0 +1,55 @@ + +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ attribute name="normalPrice" fragment="true" %> +<%@ attribute name="onSale" fragment="true" %> +<%@ variable name-given="name" %> +<%@ variable name-given="price" %> +<%@ variable name-given="origPrice" %> +<%@ variable name-given="salePrice" %> + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/tomcat/examples/WEB-INF/tags/helloWorld.tag b/tomcat/examples/WEB-INF/tags/helloWorld.tag new file mode 100644 index 0000000..192bf53 --- /dev/null +++ b/tomcat/examples/WEB-INF/tags/helloWorld.tag @@ -0,0 +1,17 @@ + +Hello, world! diff --git a/tomcat/examples/WEB-INF/tags/panel.tag b/tomcat/examples/WEB-INF/tags/panel.tag new file mode 100644 index 0000000..f4f30d0 --- /dev/null +++ b/tomcat/examples/WEB-INF/tags/panel.tag @@ -0,0 +1,29 @@ + +<%@ attribute name="color" %> +<%@ attribute name="bgcolor" %> +<%@ attribute name="title" %> + + + + + + + +
    ${title}
    + +
    diff --git a/tomcat/examples/WEB-INF/web.xml b/tomcat/examples/WEB-INF/web.xml new file mode 100644 index 0000000..ac4840e --- /dev/null +++ b/tomcat/examples/WEB-INF/web.xml @@ -0,0 +1,399 @@ + + + + + + Servlet and JSP Examples. + + Servlet and JSP Examples + + + + Timing Filter + filters.ExampleFilter + + attribute + filters.ExampleFilter + + + + + Request Dumper Filter + org.apache.catalina.filters.RequestDumperFilter + + + + + Set Character Encoding + org.apache.catalina.filters.SetCharacterEncodingFilter + true + + encoding + UTF-8 + + + ignore + false + + + + + Compression Filter + compressionFilters.CompressionFilter + + compressionThreshold + 128 + + + compressionBuffer + 8192 + + + compressionMimeTypes + text/html,text/plain,text/xml + + + debug + 0 + + + + + + + + + Set Character Encoding + /* + + + + + + + + + listeners.ContextListener + + + listeners.SessionListener + + + + + async.AsyncStockContextListener + + + + + + ServletToJsp + ServletToJsp + + + CompressionFilterTestServlet + compressionFilters.CompressionFilterTestServlet + + + HelloWorldExample + HelloWorldExample + + + RequestInfoExample + RequestInfoExample + + + RequestHeaderExample + RequestHeaderExample + + + RequestParamExample + RequestParamExample + + + CookieExample + CookieExample + + + SessionExample + SessionExample + + + + CompressionFilterTestServlet + /CompressionTest + + + HelloWorldExample + /servlets/servlet/HelloWorldExample + + + RequestInfoExample + /servlets/servlet/RequestInfoExample/* + + + RequestHeaderExample + /servlets/servlet/RequestHeaderExample + + + RequestParamExample + /servlets/servlet/RequestParamExample + + + CookieExample + /servlets/servlet/CookieExample + + + SessionExample + /servlets/servlet/SessionExample + + + ServletToJsp + /servletToJsp + + + + + + http://tomcat.apache.org/debug-taglib + + + /WEB-INF/jsp/debug-taglib.tld + + + + + + http://tomcat.apache.org/example-taglib + + + /WEB-INF/jsp/example-taglib.tld + + + + + + http://tomcat.apache.org/jsp2-example-taglib + + + /WEB-INF/jsp2/jsp2-example-taglib.tld + + + + + + Special property group for JSP Configuration JSP example. + + JSPConfiguration + /jsp/jsp2/misc/config.jsp + true + ISO-8859-1 + true + /jsp/jsp2/misc/prelude.jspf + /jsp/jsp2/misc/coda.jspf + + + + + Example Security Constraint - part 1 + + Protected Area - Allow methods + + /jsp/security/protected/* + + + DELETE + GET + POST + PUT + + + + tomcat + role1 + + + + Example Security Constraint - part 2 + + Protected Area - Deny methods + + /jsp/security/protected/* + DELETE + GET + POST + PUT + + + + + + + + FORM + Example Form-Based Authentication Area + + /jsp/security/protected/login.jsp + /jsp/security/protected/error.jsp + + + + + + role1 + + + tomcat + + + + + + minExemptions + java.lang.Integer + 1 + + + foo/name1 + java.lang.String + value1 + + + foo/bar/name2 + java.lang.Boolean + true + + + name3 + java.lang.Integer + 1 + + + foo/name4 + java.lang.Integer + 10 + + + + + async0 + async.Async0 + true + + + async0 + /async/async0 + + + async1 + async.Async1 + true + + + async1 + /async/async1 + + + async2 + async.Async2 + true + + + async2 + /async/async2 + + + async3 + async.Async3 + true + + + async3 + /async/async3 + + + stock + async.AsyncStockServlet + true + + + stock + /async/stockticker + + + + + bytecounter + nonblocking.ByteCounter + true + + + bytecounter + /servlets/nonblocking/bytecounter + + + numberwriter + nonblocking.NumberWriter + true + + + numberwriter + /servlets/nonblocking/numberwriter + + + + index.html + index.xhtml + index.htm + index.jsp + + + + + websocket.drawboard.DrawboardContextListener + + + diff --git a/tomcat/examples/index.html b/tomcat/examples/index.html new file mode 100644 index 0000000..0799e10 --- /dev/null +++ b/tomcat/examples/index.html @@ -0,0 +1,30 @@ + + + +Apache Tomcat Examples + + +

    +

    Apache Tomcat Examples

    +

    + + diff --git a/tomcat/examples/jsp/async/async1.jsp b/tomcat/examples/jsp/async/async1.jsp new file mode 100644 index 0000000..af88869 --- /dev/null +++ b/tomcat/examples/jsp/async/async1.jsp @@ -0,0 +1,28 @@ +<%-- + 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. +--%> +<%@page session="false" import="java.util.Date,java.text.SimpleDateFormat"%> +Output from async1.jsp +Type is <%=request.getDispatcherType()%> +<% + System.out.println("Inside Async 1"); + if (request.isAsyncStarted()) { + request.getAsyncContext().complete(); + } + Date date = new Date(System.currentTimeMillis()); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z"); +%> +Completed async request at <%=sdf.format(date)%> \ No newline at end of file diff --git a/tomcat/examples/jsp/async/async1.jsp.html b/tomcat/examples/jsp/async/async1.jsp.html new file mode 100644 index 0000000..2244765 --- /dev/null +++ b/tomcat/examples/jsp/async/async1.jsp.html @@ -0,0 +1,29 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<%@page session="false" import="java.util.Date,java.text.SimpleDateFormat"%>
    +Output from async1.jsp
    +Type is <%=request.getDispatcherType()%>
    +<%
    +  System.out.println("Inside Async 1");
    +  if (request.isAsyncStarted()) {
    +    request.getAsyncContext().complete();
    +  }
    +  Date date = new Date(System.currentTimeMillis());
    +  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
    +%>
    +Completed async request at <%=sdf.format(date)%>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/async/async3.jsp b/tomcat/examples/jsp/async/async3.jsp new file mode 100644 index 0000000..9d24e60 --- /dev/null +++ b/tomcat/examples/jsp/async/async3.jsp @@ -0,0 +1,25 @@ +<%-- + 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. +--%> +<%@page session="false" import="java.util.Date,java.text.SimpleDateFormat"%> +Output from async3.jsp +Type is <%=request.getDispatcherType()%> +<% + Date date = new Date(System.currentTimeMillis()); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z"); +%> + +Completed async 3 request at <%=sdf.format(date)%> \ No newline at end of file diff --git a/tomcat/examples/jsp/async/async3.jsp.html b/tomcat/examples/jsp/async/async3.jsp.html new file mode 100644 index 0000000..6deced8 --- /dev/null +++ b/tomcat/examples/jsp/async/async3.jsp.html @@ -0,0 +1,26 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<%@page session="false" import="java.util.Date,java.text.SimpleDateFormat"%>
    +Output from async3.jsp
    +Type is <%=request.getDispatcherType()%>
    +<%
    +  Date date = new Date(System.currentTimeMillis());
    +  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
    +%>
    +
    +Completed async 3 request at <%=sdf.format(date)%>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/async/index.jsp b/tomcat/examples/jsp/async/index.jsp new file mode 100644 index 0000000..be2d713 --- /dev/null +++ b/tomcat/examples/jsp/async/index.jsp @@ -0,0 +1,69 @@ +<%-- + 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. +--%> +<%@page session="false"%> + +
    +Use cases:
    +
    +1. Simple dispatch
    + - servlet does startAsync()
    + - background thread calls ctx.dispatch()
    +   "> Async 0 
    +
    +2. Simple dispatch
    + - servlet does startAsync()
    + - background thread calls dispatch(/path/to/jsp)
    +   "> Async 1 
    +
    +3. Simple dispatch
    + - servlet does startAsync()
    + - background thread calls writes and calls complete()
    +   "> Async 2 
    +
    +4. Simple dispatch
    + - servlet does a startAsync()
    + - servlet calls dispatch(/path/to/jsp)
    + - servlet calls complete()
    +   "> Async 3 
    +
    +3. Timeout s1
    + - servlet does a startAsync()
    + - servlet does a setAsyncTimeout
    + - returns - waits for timeout to happen should return error page
    +
    +4. Timeout s2
    + - servlet does a startAsync()
    + - servlet does a setAsyncTimeout
    + - servlet does a addAsyncListener
    + - returns - waits for timeout to happen and listener invoked
    +
    +5. Dispatch to asyncSupported=false servlet
    + - servlet1 does a startAsync()
    + - servlet1 dispatches to dispatch(/servlet2)
    + - the container calls complete() after servlet2 is complete
    + - TODO
    +
    +6. Chained dispatch
    + - servlet1 does a startAsync
    + - servlet1 does a dispatch to servlet2 (asyncsupported=true)
    + - servlet2 does a dispatch to servlet3 (asyncsupported=true)
    + - servlet3 does a dispatch to servlet4 (asyncsupported=false)
    +
    +
    +7. Stock ticker
    +   "> StockTicker 
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/async/index.jsp.html b/tomcat/examples/jsp/async/index.jsp.html new file mode 100644 index 0000000..778b643 --- /dev/null +++ b/tomcat/examples/jsp/async/index.jsp.html @@ -0,0 +1,70 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<%@page session="false"%>
    +
    +<pre>
    +Use cases:
    +
    +1. Simple dispatch
    + - servlet does startAsync()
    + - background thread calls ctx.dispatch()
    +   <a href="<%=response.encodeURL("/examples/async/async0")%>"> Async 0 </a>
    +
    +2. Simple dispatch
    + - servlet does startAsync()
    + - background thread calls dispatch(/path/to/jsp)
    +   <a href="<%=response.encodeURL("/examples/async/async1")%>"> Async 1 </a>
    +
    +3. Simple dispatch
    + - servlet does startAsync()
    + - background thread calls writes and calls complete()
    +   <a href="<%=response.encodeURL("/examples/async/async2")%>"> Async 2 </a>
    +
    +4. Simple dispatch
    + - servlet does a startAsync()
    + - servlet calls dispatch(/path/to/jsp)
    + - servlet calls complete()
    +   <a href="<%=response.encodeURL("/examples/async/async3")%>"> Async 3 </a>
    +
    +3. Timeout s1
    + - servlet does a startAsync()
    + - servlet does a setAsyncTimeout
    + - returns - waits for timeout to happen should return error page
    +
    +4. Timeout s2
    + - servlet does a startAsync()
    + - servlet does a setAsyncTimeout
    + - servlet does a addAsyncListener
    + - returns - waits for timeout to happen and listener invoked
    +
    +5. Dispatch to asyncSupported=false servlet
    + - servlet1 does a startAsync()
    + - servlet1 dispatches to dispatch(/servlet2)
    + - the container calls complete() after servlet2 is complete
    + - TODO
    +
    +6. Chained dispatch
    + - servlet1 does a startAsync
    + - servlet1 does a dispatch to servlet2 (asyncsupported=true)
    + - servlet2 does a dispatch to servlet3 (asyncsupported=true)
    + - servlet3 does a dispatch to servlet4 (asyncsupported=false)
    +
    +
    +7. Stock ticker
    +   <a href="<%=response.encodeURL("/examples/async/stockticker")%>"> StockTicker </a>
    +</pre>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/cal/Entries.java.html b/tomcat/examples/jsp/cal/Entries.java.html new file mode 100644 index 0000000..03f9a0c --- /dev/null +++ b/tomcat/examples/jsp/cal/Entries.java.html @@ -0,0 +1,61 @@ +Source Code
    /*
    + * 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.
    + */
    +package cal;
    +
    +import java.util.Hashtable;
    +
    +import javax.servlet.http.HttpServletRequest;
    +
    +public class Entries {
    +
    +    private final Hashtable<String, Entry> entries;
    +    private static final String[] time = { "8am", "9am", "10am", "11am",
    +            "12pm", "1pm", "2pm", "3pm", "4pm", "5pm", "6pm", "7pm", "8pm" };
    +    public static final int rows = 12;
    +
    +    public Entries() {
    +        entries = new Hashtable<>(rows);
    +        for (int i = 0; i < rows; i++) {
    +            entries.put(time[i], new Entry(time[i]));
    +        }
    +    }
    +
    +    public int getRows() {
    +        return rows;
    +    }
    +
    +    public Entry getEntry(int index) {
    +        return this.entries.get(time[index]);
    +    }
    +
    +    public int getIndex(String tm) {
    +        for (int i = 0; i < rows; i++)
    +            if (tm.equals(time[i]))
    +                return i;
    +        return -1;
    +    }
    +
    +    public void processRequest(HttpServletRequest request, String tm) {
    +        int index = getIndex(tm);
    +        if (index >= 0) {
    +            String descr = request.getParameter("description");
    +            entries.get(time[index]).setDescription(descr);
    +        }
    +    }
    +
    +}
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/cal/Entry.java.html b/tomcat/examples/jsp/cal/Entry.java.html new file mode 100644 index 0000000..7183a0a --- /dev/null +++ b/tomcat/examples/jsp/cal/Entry.java.html @@ -0,0 +1,54 @@ +Source Code
    /*
    + * 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.
    + */
    +
    +package cal;
    +
    +public class Entry {
    +
    +    final String hour;
    +    String description;
    +
    +    public Entry(String hour) {
    +        this.hour = hour;
    +        this.description = "";
    +
    +    }
    +
    +    public String getHour() {
    +        return this.hour;
    +    }
    +
    +    public String getColor() {
    +        if (description.equals("")) {
    +            return "lightblue";
    +        }
    +        return "red";
    +    }
    +
    +    public String getDescription() {
    +        if (description.equals("")) {
    +            return "None";
    +        }
    +        return this.description;
    +    }
    +
    +    public void setDescription(String descr) {
    +        description = descr;
    +    }
    +
    +}
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/cal/JspCalendar.java.html b/tomcat/examples/jsp/cal/JspCalendar.java.html new file mode 100644 index 0000000..118996e --- /dev/null +++ b/tomcat/examples/jsp/cal/JspCalendar.java.html @@ -0,0 +1,152 @@ +Source Code
    /*
    +* 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.
    +*/
    +
    +package cal;
    +
    +import java.util.Calendar;
    +import java.util.Date;
    +
    +public class JspCalendar {
    +    final Calendar  calendar;
    +
    +    public JspCalendar() {
    +        calendar = Calendar.getInstance();
    +        Date trialTime = new Date();
    +        calendar.setTime(trialTime);
    +    }
    +
    +
    +    public int getYear() {
    +        return calendar.get(Calendar.YEAR);
    +    }
    +
    +    public String getMonth() {
    +        int m = getMonthInt();
    +        String[] months = new String [] { "January", "February", "March",
    +                                        "April", "May", "June",
    +                                        "July", "August", "September",
    +                                        "October", "November", "December" };
    +        if (m > 12)
    +            return "Unknown to Man";
    +
    +        return months[m - 1];
    +
    +    }
    +
    +    public String getDay() {
    +        int x = getDayOfWeek();
    +        String[] days = new String[] {"Sunday", "Monday", "Tuesday", "Wednesday",
    +                                      "Thursday", "Friday", "Saturday"};
    +
    +        if (x > 7)
    +            return "Unknown to Man";
    +
    +        return days[x - 1];
    +
    +    }
    +
    +    public int getMonthInt() {
    +        return 1 + calendar.get(Calendar.MONTH);
    +    }
    +
    +    public String getDate() {
    +        return getMonthInt() + "/" + getDayOfMonth() + "/" +  getYear();
    +    }
    +
    +    public String getCurrentDate() {
    +        Date dt = new Date ();
    +        calendar.setTime (dt);
    +        return getMonthInt() + "/" + getDayOfMonth() + "/" +  getYear();
    +
    +    }
    +
    +    public String getNextDate() {
    +        calendar.set (Calendar.DAY_OF_MONTH, getDayOfMonth() + 1);
    +        return getDate ();
    +    }
    +
    +    public String getPrevDate() {
    +        calendar.set (Calendar.DAY_OF_MONTH, getDayOfMonth() - 1);
    +        return getDate ();
    +    }
    +
    +    public String getTime() {
    +        return getHour() + ":" + getMinute() + ":" + getSecond();
    +    }
    +
    +    public int getDayOfMonth() {
    +        return calendar.get(Calendar.DAY_OF_MONTH);
    +    }
    +
    +    public int getDayOfYear() {
    +        return calendar.get(Calendar.DAY_OF_YEAR);
    +    }
    +
    +    public int getWeekOfYear() {
    +        return calendar.get(Calendar.WEEK_OF_YEAR);
    +    }
    +
    +    public int getWeekOfMonth() {
    +        return calendar.get(Calendar.WEEK_OF_MONTH);
    +    }
    +
    +    public int getDayOfWeek() {
    +        return calendar.get(Calendar.DAY_OF_WEEK);
    +    }
    +
    +    public int getHour() {
    +        return calendar.get(Calendar.HOUR_OF_DAY);
    +    }
    +
    +    public int getMinute() {
    +        return calendar.get(Calendar.MINUTE);
    +    }
    +
    +
    +    public int getSecond() {
    +        return calendar.get(Calendar.SECOND);
    +    }
    +
    +
    +    public int getEra() {
    +        return calendar.get(Calendar.ERA);
    +    }
    +
    +    public String getUSTimeZone() {
    +        String[] zones = new String[] {"Hawaii", "Alaskan", "Pacific",
    +                                       "Mountain", "Central", "Eastern"};
    +
    +        return zones[10 + getZoneOffset()];
    +    }
    +
    +    public int getZoneOffset() {
    +        return calendar.get(Calendar.ZONE_OFFSET)/(60*60*1000);
    +    }
    +
    +
    +    public int getDSTOffset() {
    +        return calendar.get(Calendar.DST_OFFSET)/(60*60*1000);
    +    }
    +
    +
    +    public int getAMPM() {
    +        return calendar.get(Calendar.AM_PM);
    +    }
    +}
    +
    +
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/cal/TableBean.java.html b/tomcat/examples/jsp/cal/TableBean.java.html new file mode 100644 index 0000000..00a8a04 --- /dev/null +++ b/tomcat/examples/jsp/cal/TableBean.java.html @@ -0,0 +1,102 @@ +Source Code
    /*
    + * 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.
    + */
    +package cal;
    +
    +import java.util.Hashtable;
    +
    +import javax.servlet.http.HttpServletRequest;
    +
    +public class TableBean {
    +
    +    final Hashtable<String, Entries> table;
    +    final JspCalendar JspCal;
    +    Entries entries;
    +    String date;
    +    String name = null;
    +    String email = null;
    +    boolean processError = false;
    +
    +    public TableBean() {
    +        this.table = new Hashtable<>(10);
    +        this.JspCal = new JspCalendar();
    +        this.date = JspCal.getCurrentDate();
    +    }
    +
    +    public void setName(String nm) {
    +        this.name = nm;
    +    }
    +
    +    public String getName() {
    +        return this.name;
    +    }
    +
    +    public void setEmail(String mail) {
    +        this.email = mail;
    +    }
    +
    +    public String getEmail() {
    +        return this.email;
    +    }
    +
    +    public String getDate() {
    +        return this.date;
    +    }
    +
    +    public Entries getEntries() {
    +        return this.entries;
    +    }
    +
    +    public void processRequest(HttpServletRequest request) {
    +
    +        // Get the name and e-mail.
    +        this.processError = false;
    +        if (name == null || name.equals(""))
    +            setName(request.getParameter("name"));
    +        if (email == null || email.equals(""))
    +            setEmail(request.getParameter("email"));
    +        if (name == null || email == null || name.equals("")
    +                || email.equals("")) {
    +            this.processError = true;
    +            return;
    +        }
    +
    +        // Get the date.
    +        String dateR = request.getParameter("date");
    +        if (dateR == null)
    +            date = JspCal.getCurrentDate();
    +        else if (dateR.equalsIgnoreCase("next"))
    +            date = JspCal.getNextDate();
    +        else if (dateR.equalsIgnoreCase("prev"))
    +            date = JspCal.getPrevDate();
    +
    +        entries = table.get(date);
    +        if (entries == null) {
    +            entries = new Entries();
    +            table.put(date, entries);
    +        }
    +
    +        // If time is provided add the event.
    +        String time = request.getParameter("time");
    +        if (time != null)
    +            entries.processRequest(request, time);
    +    }
    +
    +    public boolean getProcessError() {
    +        return this.processError;
    +    }
    +}
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/cal/cal1.jsp b/tomcat/examples/jsp/cal/cal1.jsp new file mode 100644 index 0000000..e6b8a49 --- /dev/null +++ b/tomcat/examples/jsp/cal/cal1.jsp @@ -0,0 +1,94 @@ +<%-- + 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. +--%> +<%@page contentType="text/html; charset=UTF-8" %> + + + Calendar: A JSP APPLICATION + + + + + +<%@ page language="java" import="cal.*" %> + + +<% + table.processRequest(request); + if (table.getProcessError() == false) { +%> + + +
    + + + + +
    prev + Calendar:<%= table.getDate() %> next +
    + + + + + + + + +<% + for(int i=0; i + + + + +<% + } +%> + +
    Time Appointment
    + > + <%= entr.getHour() %> + > + <% out.print(util.HTMLFilter.filter(entr.getDescription())); %> +
    +
    + + + + + + +
    <% out.print(util.HTMLFilter.filter(table.getName())); %> : + <% out.print(util.HTMLFilter.filter(table.getEmail())); %>
    +
    + +<% + } else { +%> + + You must enter your name and email address correctly. + +<% + } +%> + + + + + + diff --git a/tomcat/examples/jsp/cal/cal1.jsp.html b/tomcat/examples/jsp/cal/cal1.jsp.html new file mode 100644 index 0000000..7daddf0 --- /dev/null +++ b/tomcat/examples/jsp/cal/cal1.jsp.html @@ -0,0 +1,95 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<%@page contentType="text/html; charset=UTF-8" %>
    +<HTML>
    +<HEAD><TITLE>
    +    Calendar: A JSP APPLICATION
    +</TITLE></HEAD>
    +
    +
    +<BODY BGCOLOR="white">
    +
    +<%@ page language="java" import="cal.*" %>
    +<jsp:useBean id="table" scope="session" class="cal.TableBean" />
    +
    +<%
    +    table.processRequest(request);
    +    if (table.getProcessError() == false) {
    +%>
    +
    +<!-- html table goes here -->
    +<CENTER>
    +<TABLE WIDTH=60% BGCOLOR=yellow CELLPADDING=15>
    +<TR>
    +<TD ALIGN=CENTER> <A HREF=cal1.jsp?date=prev> prev </A>
    +<TD ALIGN=CENTER> Calendar:<%= table.getDate() %></TD>
    +<TD ALIGN=CENTER> <A HREF=cal1.jsp?date=next> next </A>
    +</TR>
    +</TABLE>
    +
    +<!-- the main table -->
    +<TABLE WIDTH=60% BGCOLOR=lightblue BORDER=1 CELLPADDING=10>
    +<TR>
    +<TH> Time </TH>
    +<TH> Appointment </TH>
    +</TR>
    +<FORM METHOD=POST ACTION=cal1.jsp>
    +<%
    +    for(int i=0; i<table.getEntries().getRows(); i++) {
    +       cal.Entry entr = table.getEntries().getEntry(i);
    +%>
    +    <TR>
    +    <TD>
    +    <A HREF=cal2.jsp?time=<%= entr.getHour() %>>
    +        <%= entr.getHour() %> </A>
    +    </TD>
    +    <TD BGCOLOR=<%= entr.getColor() %>>
    +    <% out.print(util.HTMLFilter.filter(entr.getDescription())); %>
    +    </TD>
    +    </TR>
    +<%
    +    }
    +%>
    +</FORM>
    +</TABLE>
    +<BR>
    +
    +<!-- footer -->
    +<TABLE WIDTH=60% BGCOLOR=yellow CELLPADDING=15>
    +<TR>
    +<TD ALIGN=CENTER>  <% out.print(util.HTMLFilter.filter(table.getName())); %> :
    +             <% out.print(util.HTMLFilter.filter(table.getEmail())); %> </TD>
    +</TR>
    +</TABLE>
    +</CENTER>
    +
    +<%
    +    } else {
    +%>
    +<font size=5>
    +    You must enter your name and email address correctly.
    +</font>
    +<%
    +    }
    +%>
    +
    +
    +</BODY>
    +</HTML>
    +
    +
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/cal/cal2.jsp b/tomcat/examples/jsp/cal/cal2.jsp new file mode 100644 index 0000000..e7e14d8 --- /dev/null +++ b/tomcat/examples/jsp/cal/cal2.jsp @@ -0,0 +1,45 @@ +<%-- + 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. +--%> +<%@page contentType="text/html; charset=UTF-8" %> + + + Calendar: A JSP APPLICATION + + + + + + +<% + String time = request.getParameter ("time"); +%> + + Please add the following event: +

    Date <%= table.getDate() %> +
    Time <%= util.HTMLFilter.filter(time) %>

    +
    +
    +
    +
    +
    +

    Description of the event

    +
    +
    + + + + diff --git a/tomcat/examples/jsp/cal/cal2.jsp.html b/tomcat/examples/jsp/cal/cal2.jsp.html new file mode 100644 index 0000000..2cc191b --- /dev/null +++ b/tomcat/examples/jsp/cal/cal2.jsp.html @@ -0,0 +1,46 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<%@page contentType="text/html; charset=UTF-8" %>
    +<HTML>
    +<HEAD><TITLE>
    +    Calendar: A JSP APPLICATION
    +</TITLE></HEAD>
    +
    +
    +<BODY BGCOLOR="white">
    +<jsp:useBean id="table" scope="session" class="cal.TableBean" />
    +
    +<%
    +    String time = request.getParameter ("time");
    +%>
    +
    +<FONT SIZE=5> Please add the following event:
    +<BR> <h3> Date <%= table.getDate() %>
    +<BR> Time <%= util.HTMLFilter.filter(time) %> </h3>
    +</FONT>
    +<FORM METHOD=POST ACTION=cal1.jsp>
    +<BR>
    +<BR> <INPUT NAME="date" TYPE=HIDDEN VALUE="current">
    +<BR> <INPUT NAME="time" TYPE=HIDDEN VALUE="<%= util.HTMLFilter.filter(time) %>">
    +<BR> <h2> Description of the event <INPUT NAME="description" TYPE=TEXT SIZE=20> </h2>
    +<BR> <INPUT TYPE=SUBMIT VALUE="submit">
    +</FORM>
    +
    +</BODY>
    +</HTML>
    +
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/cal/calendar.html b/tomcat/examples/jsp/cal/calendar.html new file mode 100644 index 0000000..a0a3ea1 --- /dev/null +++ b/tomcat/examples/jsp/cal/calendar.html @@ -0,0 +1,43 @@ + + + + +Untitled Document + + + + +

    + +

    Source Code for Calendar Example.
    +

    cal1.jsp +

    +

    cal2.jsp +

    + +
    +

    Beans. +

    TableBean +

    +

    Entries +

    +

    Entry +

    + + + diff --git a/tomcat/examples/jsp/cal/login.html b/tomcat/examples/jsp/cal/login.html new file mode 100644 index 0000000..2c4aa55 --- /dev/null +++ b/tomcat/examples/jsp/cal/login.html @@ -0,0 +1,47 @@ + + + + + Login page for the calendar. + + + +
    + + Please Enter the following information: + +
    +
    + + Name + +
    + Email + +
    + + +
    +
    + Note: This application does not implement the complete +functionality of a typical calendar application. It demonstrates a way JSP can +be used with html tables and forms. + +
    + + diff --git a/tomcat/examples/jsp/checkbox/CheckTest.html b/tomcat/examples/jsp/checkbox/CheckTest.html new file mode 100644 index 0000000..284d9ec --- /dev/null +++ b/tomcat/examples/jsp/checkbox/CheckTest.html @@ -0,0 +1,56 @@ + + + + + +checkbox.CheckTest Bean Properties + + +

    +checkbox.CheckTest Bean Properties +

    +
    +
    +
    public class CheckTest
    extends Object
    + +

    +


    + +

    + + + + + + + + + +
    +Properties Summary
    + +String +CheckTest:fruit +
    +
    + +Multi +
    +


    + + diff --git a/tomcat/examples/jsp/checkbox/check.html b/tomcat/examples/jsp/checkbox/check.html new file mode 100644 index 0000000..b6d6b3b --- /dev/null +++ b/tomcat/examples/jsp/checkbox/check.html @@ -0,0 +1,38 @@ + + + + + + +
    +
    + +Check all Favorite fruits:
    + + Apples
    + Grapes
    + Oranges
    + Melons
    + + +
    + +
    +
    + + diff --git a/tomcat/examples/jsp/checkbox/checkresult.jsp b/tomcat/examples/jsp/checkbox/checkresult.jsp new file mode 100644 index 0000000..a8400e9 --- /dev/null +++ b/tomcat/examples/jsp/checkbox/checkresult.jsp @@ -0,0 +1,63 @@ +<%-- + 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. +--%> + + + +<%! String[] fruits; %> + + + +
    +The checked fruits (got using request) are:
    +<% + fruits = request.getParameterValues("fruit"); +%> +
      +<% + if (fruits != null) { + for (int i = 0; i < fruits.length; i++) { +%> +
    • +<% + out.println (util.HTMLFilter.filter(fruits[i])); + } + } else out.println ("none selected"); +%> +
    +
    +
    + +The checked fruits (got using beans) are
    + +<% + fruits = foo.getFruit(); +%> +
      +<% + if (!fruits[0].equals("1")) { + for (int i = 0; i < fruits.length; i++) { +%> +
    • +<% + out.println (util.HTMLFilter.filter(fruits[i])); + } + } else out.println ("none selected"); +%> +
    +
    + + diff --git a/tomcat/examples/jsp/checkbox/checkresult.jsp.html b/tomcat/examples/jsp/checkbox/checkresult.jsp.html new file mode 100644 index 0000000..4dd0d9b --- /dev/null +++ b/tomcat/examples/jsp/checkbox/checkresult.jsp.html @@ -0,0 +1,64 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<html>
    +<body bgcolor="white">
    +<font size=5 color="red">
    +<%! String[] fruits; %>
    +<jsp:useBean id="foo" scope="page" class="checkbox.CheckTest" />
    +
    +<jsp:setProperty name="foo" property="fruit" param="fruit" />
    +<hr>
    +The checked fruits (got using request) are: <br>
    +<%
    +    fruits = request.getParameterValues("fruit");
    +%>
    +<ul>
    +<%
    +    if (fruits != null) {
    +      for (int i = 0; i < fruits.length; i++) {
    +%>
    +<li>
    +<%
    +          out.println (util.HTMLFilter.filter(fruits[i]));
    +      }
    +    } else out.println ("none selected");
    +%>
    +</ul>
    +<br>
    +<hr>
    +
    +The checked fruits (got using beans) are <br>
    +
    +<%
    +        fruits = foo.getFruit();
    +%>
    +<ul>
    +<%
    +    if (!fruits[0].equals("1")) {
    +      for (int i = 0; i < fruits.length; i++) {
    +%>
    +<li>
    +<%
    +          out.println (util.HTMLFilter.filter(fruits[i]));
    +      }
    +    } else out.println ("none selected");
    +%>
    +</ul>
    +</font>
    +</body>
    +</html>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/checkbox/cresult.html b/tomcat/examples/jsp/checkbox/cresult.html new file mode 100644 index 0000000..b6a28d6 --- /dev/null +++ b/tomcat/examples/jsp/checkbox/cresult.html @@ -0,0 +1,34 @@ + + + + +Untitled Document + + + + +

    + +

    Source Code for Checkbox Example +

    + +

    Property Sheet for CheckTest +

    + + + diff --git a/tomcat/examples/jsp/colors/ColorGameBean.html b/tomcat/examples/jsp/colors/ColorGameBean.html new file mode 100644 index 0000000..172bc66 --- /dev/null +++ b/tomcat/examples/jsp/colors/ColorGameBean.html @@ -0,0 +1,116 @@ + + + + + +colors.ColorGameBean Bean Properties + + +

    +colors.ColorGameBean Bean Properties +

    +
    +
    +
    public class ColorGameBean
    extends Object
    + +

    +


    + +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +Properties Summary
    + +String +ColorGameBean:color2 +
    +
    + +Single +
    + +String +ColorGameBean:color1 +
    +
    + +Single +
    + +int +ColorGameBean:attempts +
    +
    + +Single +
    + +boolean +ColorGameBean:hint +
    +
    + +Single +
    + +boolean +ColorGameBean:success +
    +
    + +Single +
    + +boolean +ColorGameBean:hintTaken +
    +
    + +Single +
    +


    + + diff --git a/tomcat/examples/jsp/colors/clr.html b/tomcat/examples/jsp/colors/clr.html new file mode 100644 index 0000000..e411f59 --- /dev/null +++ b/tomcat/examples/jsp/colors/clr.html @@ -0,0 +1,34 @@ + + + + +Untitled Document + + + + +

    + +

    Source Code for Color Example +

    + +

    Property Sheet for ColorGameBean +

    + + + diff --git a/tomcat/examples/jsp/colors/colors.html b/tomcat/examples/jsp/colors/colors.html new file mode 100644 index 0000000..900651e --- /dev/null +++ b/tomcat/examples/jsp/colors/colors.html @@ -0,0 +1,47 @@ + + + + + + +
    +This web page is an example using JSP and BEANs. +

    +Guess my favorite two colors + +

    If you fail to guess both of them - you get yellow on red. + +

    If you guess one of them right, either your foreground or + your background will change to the color that was guessed right. + +

    Guess them both right and your browser foreground/background + will change to my two favorite colors to display this page. + +


    +
    +Color #1: +
    +Color #2: +

    + + +

    + +
    + + diff --git a/tomcat/examples/jsp/colors/colrs.jsp b/tomcat/examples/jsp/colors/colrs.jsp new file mode 100644 index 0000000..ec3af88 --- /dev/null +++ b/tomcat/examples/jsp/colors/colrs.jsp @@ -0,0 +1,70 @@ +<%-- + 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. +--%> + + + + + +<% + cb.processRequest(); +%> + +> +> +

    + +<% if (cb.getHint()==true) { %> + +

    Hint #1: Vampires prey at night! +

    Hint #2: Nancy without the n. + +<% } %> + +<% if (cb.getSuccess()==true) { %> + +

    CONGRATULATIONS!! + <% if (cb.getHintTaken()==true) { %> + +

    ( although I know you cheated and peeked into the hints) + + <% } %> + +<% } %> + +

    Total attempts so far: <%= cb.getAttempts() %> +

    + +

    + +

    + +Color #1: + +
    + +Color #2: + +

    + + + + +

    + +
    + + diff --git a/tomcat/examples/jsp/colors/colrs.jsp.html b/tomcat/examples/jsp/colors/colrs.jsp.html new file mode 100644 index 0000000..7ef38ae --- /dev/null +++ b/tomcat/examples/jsp/colors/colrs.jsp.html @@ -0,0 +1,71 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<html>
    +
    +<jsp:useBean id="cb" scope="session" class="colors.ColorGameBean" />
    +<jsp:setProperty name="cb" property="*" />
    +
    +<%
    +    cb.processRequest();
    +%>
    +
    +<body bgcolor=<%= cb.getColor1() %>>
    +<font size=6 color=<%= cb.getColor2() %>>
    +<p>
    +
    +<% if (cb.getHint()==true) { %>
    +
    +    <p> Hint #1: Vampires prey at night!
    +    <p>  <p> Hint #2: Nancy without the n.
    +
    +<% } %>
    +
    +<% if  (cb.getSuccess()==true) { %>
    +
    +    <p> CONGRATULATIONS!!
    +    <% if  (cb.getHintTaken()==true) { %>
    +
    +        <p> ( although I know you cheated and peeked into the hints)
    +
    +    <% } %>
    +
    +<% } %>
    +
    +<p> Total attempts so far: <%= cb.getAttempts() %>
    +<p>
    +
    +<p>
    +
    +<form method=POST action=colrs.jsp>
    +
    +Color #1: <input type=text name= color1 size=16>
    +
    +<br>
    +
    +Color #2: <input type=text name= color2 size=16>
    +
    +<p>
    +
    +<input type=submit name=action value="Submit">
    +<input type=submit name=action value="Hint">
    +
    +</form>
    +
    +</font>
    +</body>
    +</html>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/dates/date.html b/tomcat/examples/jsp/dates/date.html new file mode 100644 index 0000000..683ab4d --- /dev/null +++ b/tomcat/examples/jsp/dates/date.html @@ -0,0 +1,31 @@ + + + + +Untitled Document + + + + +

    + +

    Source Code for Date Example +

    + + + diff --git a/tomcat/examples/jsp/dates/date.jsp b/tomcat/examples/jsp/dates/date.jsp new file mode 100644 index 0000000..d6c6b86 --- /dev/null +++ b/tomcat/examples/jsp/dates/date.jsp @@ -0,0 +1,41 @@ +<%-- + 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. +--%> + + +<%@ page session="false"%> + + + + + +
      +
    • Day of month: is +
    • Year: is +
    • Month: is +
    • Time: is +
    • Date: is +
    • Day: is +
    • Day Of Year: is +
    • Week Of Year: is +
    • era: is +
    • DST Offset: is +
    • Zone Offset: is +
    +
    + + + diff --git a/tomcat/examples/jsp/dates/date.jsp.html b/tomcat/examples/jsp/dates/date.jsp.html new file mode 100644 index 0000000..3f2abfc --- /dev/null +++ b/tomcat/examples/jsp/dates/date.jsp.html @@ -0,0 +1,42 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<html>
    +
    +<%@ page session="false"%>
    +
    +<body bgcolor="white">
    +<jsp:useBean id='clock' scope='page' class='dates.JspCalendar' type="dates.JspCalendar" />
    +
    +<font size=4>
    +<ul>
    +<li>    Day of month: is  <jsp:getProperty name="clock" property="dayOfMonth"/>
    +<li>    Year: is  <jsp:getProperty name="clock" property="year"/>
    +<li>    Month: is  <jsp:getProperty name="clock" property="month"/>
    +<li>    Time: is  <jsp:getProperty name="clock" property="time"/>
    +<li>    Date: is  <jsp:getProperty name="clock" property="date"/>
    +<li>    Day: is  <jsp:getProperty name="clock" property="day"/>
    +<li>    Day Of Year: is  <jsp:getProperty name="clock" property="dayOfYear"/>
    +<li>    Week Of Year: is  <jsp:getProperty name="clock" property="weekOfYear"/>
    +<li>    era: is  <jsp:getProperty name="clock" property="era"/>
    +<li>    DST Offset: is  <jsp:getProperty name="clock" property="DSTOffset"/>
    +<li>    Zone Offset: is  <jsp:getProperty name="clock" property="zoneOffset"/>
    +</ul>
    +</font>
    +
    +</body>
    +</html>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/error/er.html b/tomcat/examples/jsp/error/er.html new file mode 100644 index 0000000..af78159 --- /dev/null +++ b/tomcat/examples/jsp/error/er.html @@ -0,0 +1,31 @@ + + + + +Untitled Document + + + + +

    + +

    Source Code for Error Example +

    + + + diff --git a/tomcat/examples/jsp/error/err.jsp b/tomcat/examples/jsp/error/err.jsp new file mode 100644 index 0000000..d188456 --- /dev/null +++ b/tomcat/examples/jsp/error/err.jsp @@ -0,0 +1,44 @@ +<%-- + 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. +--%> + + + + <%@ page errorPage="errorpge.jsp" %> + + <% + String name = null; + + if (request.getParameter("name") == null) { + %> + <%@ include file="error.html" %> + <% + } else { + foo.setName(request.getParameter("name")); + if (foo.getName().equalsIgnoreCase("integra")) + name = "acura"; + if (name.equalsIgnoreCase("acura")) { + %> + +

    Yes!!! Acura is my favorite car. + + <% + } + } + %> + + + diff --git a/tomcat/examples/jsp/error/err.jsp.html b/tomcat/examples/jsp/error/err.jsp.html new file mode 100644 index 0000000..3d607a5 --- /dev/null +++ b/tomcat/examples/jsp/error/err.jsp.html @@ -0,0 +1,45 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<html>
    +<body bgcolor="lightblue">
    +
    +    <%@ page errorPage="errorpge.jsp" %>
    +    <jsp:useBean id="foo" scope="request" class="error.Smart" />
    +    <%
    +        String name = null;
    +
    +        if (request.getParameter("name") == null) {
    +    %>
    +    <%@ include file="error.html" %>
    +    <%
    +        } else {
    +          foo.setName(request.getParameter("name"));
    +          if (foo.getName().equalsIgnoreCase("integra"))
    +              name = "acura";
    +          if (name.equalsIgnoreCase("acura")) {
    +    %>
    +
    +    <H1> Yes!!! <a href="http://www.acura.com">Acura</a> is my favorite car.
    +
    +    <%
    +          }
    +        }
    +    %>
    +</body>
    +</html>
    +
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/error/error.html b/tomcat/examples/jsp/error/error.html new file mode 100644 index 0000000..b1b029c --- /dev/null +++ b/tomcat/examples/jsp/error/error.html @@ -0,0 +1,37 @@ + + + + + +

    This example uses errorpage directive

    +
    +

    Select my favourite car.

    +
    + + +
    +
    + + + diff --git a/tomcat/examples/jsp/error/errorpge.jsp b/tomcat/examples/jsp/error/errorpge.jsp new file mode 100644 index 0000000..5c6eb0a --- /dev/null +++ b/tomcat/examples/jsp/error/errorpge.jsp @@ -0,0 +1,25 @@ +<%-- + 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. +--%> + + + + + <%@ page isErrorPage="true" %> +

    The exception <%= exception.getMessage() %> tells me you + made a wrong choice. + + diff --git a/tomcat/examples/jsp/error/errorpge.jsp.html b/tomcat/examples/jsp/error/errorpge.jsp.html new file mode 100644 index 0000000..3d690dc --- /dev/null +++ b/tomcat/examples/jsp/error/errorpge.jsp.html @@ -0,0 +1,26 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<html>
    +
    +<body bgcolor="red">
    +
    +    <%@ page isErrorPage="true" %>
    +    <h1> The exception <%= exception.getMessage() %> tells me you
    +         made a wrong choice.
    +</body>
    +</html>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/forward/forward.jsp b/tomcat/examples/jsp/forward/forward.jsp new file mode 100644 index 0000000..092d9b4 --- /dev/null +++ b/tomcat/examples/jsp/forward/forward.jsp @@ -0,0 +1,33 @@ +<%-- + 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. +--%> + +<% + double freeMem = Runtime.getRuntime().freeMemory(); + double totlMem = Runtime.getRuntime().totalMemory(); + double percent = freeMem/totlMem; + if (percent < 0.5) { +%> + + + +<% } else { %> + + + +<% } %> + + diff --git a/tomcat/examples/jsp/forward/forward.jsp.html b/tomcat/examples/jsp/forward/forward.jsp.html new file mode 100644 index 0000000..32f8bf7 --- /dev/null +++ b/tomcat/examples/jsp/forward/forward.jsp.html @@ -0,0 +1,34 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<html>
    +<%
    +   double freeMem = Runtime.getRuntime().freeMemory();
    +   double totlMem = Runtime.getRuntime().totalMemory();
    +   double percent = freeMem/totlMem;
    +   if (percent < 0.5) {
    +%>
    +
    +<jsp:forward page="one.jsp"/>
    +
    +<% } else { %>
    +
    +<jsp:forward page="two.html"/>
    +
    +<% } %>
    +
    +</html>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/forward/fwd.html b/tomcat/examples/jsp/forward/fwd.html new file mode 100644 index 0000000..b3b0219 --- /dev/null +++ b/tomcat/examples/jsp/forward/fwd.html @@ -0,0 +1,30 @@ + + + +Untitled Document + + + + +

    + +

    Source Code for Forward Example +

    + + + diff --git a/tomcat/examples/jsp/forward/one.jsp b/tomcat/examples/jsp/forward/one.jsp new file mode 100644 index 0000000..c7f0004 --- /dev/null +++ b/tomcat/examples/jsp/forward/one.jsp @@ -0,0 +1,23 @@ +<%-- + 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. +--%> + + + + + +VM Memory usage < 50%. + \ No newline at end of file diff --git a/tomcat/examples/jsp/forward/one.jsp.html b/tomcat/examples/jsp/forward/one.jsp.html new file mode 100644 index 0000000..af18501 --- /dev/null +++ b/tomcat/examples/jsp/forward/one.jsp.html @@ -0,0 +1,24 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<html>
    +
    +<body bgcolor="white">
    +<font color="red">
    +
    +VM Memory usage &lt; 50%.
    +</html>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/forward/two.html b/tomcat/examples/jsp/forward/two.html new file mode 100644 index 0000000..24f4c08 --- /dev/null +++ b/tomcat/examples/jsp/forward/two.html @@ -0,0 +1,23 @@ + + + + + + +VM Memory usage > 50%. + \ No newline at end of file diff --git a/tomcat/examples/jsp/images/code.gif b/tomcat/examples/jsp/images/code.gif new file mode 100644 index 0000000..93af2cd Binary files /dev/null and b/tomcat/examples/jsp/images/code.gif differ diff --git a/tomcat/examples/jsp/images/execute.gif b/tomcat/examples/jsp/images/execute.gif new file mode 100644 index 0000000..f64d70f Binary files /dev/null and b/tomcat/examples/jsp/images/execute.gif differ diff --git a/tomcat/examples/jsp/images/return.gif b/tomcat/examples/jsp/images/return.gif new file mode 100644 index 0000000..af4f68f Binary files /dev/null and b/tomcat/examples/jsp/images/return.gif differ diff --git a/tomcat/examples/jsp/include/foo.html b/tomcat/examples/jsp/include/foo.html new file mode 100644 index 0000000..168c8c8 --- /dev/null +++ b/tomcat/examples/jsp/include/foo.html @@ -0,0 +1,17 @@ + +To get the current time in ms diff --git a/tomcat/examples/jsp/include/foo.jsp b/tomcat/examples/jsp/include/foo.jsp new file mode 100644 index 0000000..bb476c7 --- /dev/null +++ b/tomcat/examples/jsp/include/foo.jsp @@ -0,0 +1,17 @@ +<%-- + 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. + +--%><%= System.currentTimeMillis() %> diff --git a/tomcat/examples/jsp/include/foo.jsp.html b/tomcat/examples/jsp/include/foo.jsp.html new file mode 100644 index 0000000..2a1ac7b --- /dev/null +++ b/tomcat/examples/jsp/include/foo.jsp.html @@ -0,0 +1,18 @@ +Source Code
    <%--
    + 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.
    +
    +--%><%= System.currentTimeMillis() %>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/include/inc.html b/tomcat/examples/jsp/include/inc.html new file mode 100644 index 0000000..fedaed0 --- /dev/null +++ b/tomcat/examples/jsp/include/inc.html @@ -0,0 +1,30 @@ + + + +Untitled Document + + + + +

    + +

    Source Code for Include Example +

    + + + diff --git a/tomcat/examples/jsp/include/include.jsp b/tomcat/examples/jsp/include/include.jsp new file mode 100644 index 0000000..62a8c22 --- /dev/null +++ b/tomcat/examples/jsp/include/include.jsp @@ -0,0 +1,30 @@ +<%-- + 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. +--%> + + + + + + +<%@ page buffer="5kb" autoFlush="false" %> + +

    In place evaluation of another JSP which gives you the current time: <%@ include file="foo.jsp" %> + +

    by including the output of another JSP: +:-) + + diff --git a/tomcat/examples/jsp/include/include.jsp.html b/tomcat/examples/jsp/include/include.jsp.html new file mode 100644 index 0000000..4f529c1 --- /dev/null +++ b/tomcat/examples/jsp/include/include.jsp.html @@ -0,0 +1,31 @@ +Source Code

    <%--
    + 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.
    +--%>
    +<html>
    +
    +<body bgcolor="white">
    +
    +<font color="red">
    +
    +<%@ page buffer="5kb" autoFlush="false" %>
    +
    +<p>In place evaluation of another JSP which gives you the current time: <%@ include file="foo.jsp" %>
    +
    +<p> <jsp:include page="foo.html" flush="true"/> by including the output of another JSP: <jsp:include page="foo.jsp" flush="true"/>
    +:-)
    +
    +</html>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/index.html b/tomcat/examples/jsp/index.html new file mode 100644 index 0000000..977ed04 --- /dev/null +++ b/tomcat/examples/jsp/index.html @@ -0,0 +1,369 @@ + + + + + + JSP Examples + + + +

    JSP +Samples

    +

    This is a collection of samples demonstrating the usage of different +parts of the Java Server Pages (JSP) specification. Both JSP 2.0 and +JSP 1.2 examples are presented below. +

    These examples will only work when these pages are being served by a +servlet engine; of course, we recommend +Tomcat. +They will not work if you are viewing these pages via a +"file://..." URL. +

    To navigate your way through the examples, the following icons will +help:

    +
      +
    • Execute the example
    • +
    • Look at the source code for the example
    • +
    • Return to this screen
    • +
    + +

    Tip: For session scoped beans to work, the cookies must be enabled. +This can be done using browser options.

    +

    JSP 2.0 Examples

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Expression Language
    Basic ArithmeticExecuteSource
    Basic ComparisonsExecuteSource
    Implicit ObjectsExecuteSource
    FunctionsExecuteSource
    Composite ExpressionsExecuteSource

    SimpleTag Handlers and JSP Fragments
    Hello World TagExecuteSource
    Repeat TagExecuteSource
    Book ExampleExecuteSource

    Tag Files
    Hello World Tag FileExecuteSource
    Panel Tag FileExecuteSource
    Display Products ExampleExecuteSource

    New JSP XML Syntax (.jspx)
    XHTML Basic ExampleExecuteSource
    SVG (Scalable Vector Graphics)ExecuteSource

    Other JSP 2.0 Features
    <jsp:attribute> and <jsp:body>ExecuteSource
    Shuffle ExampleExecuteSource
    Attributes With Dynamic NamesExecuteSource
    JSP ConfigurationExecuteSource
    + +

    JSP 1.2 Examples

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NumberguessExecuteSource
    DateExecuteSource
    SnoopExecuteSource
    ErrorPageExecuteSource
    CartsExecuteSource
    CheckboxExecuteSource
    ColorExecuteSource
    CalendarExecuteSource
    IncludeExecuteSource
    ForwardExecuteSource
    PluginExecuteSource
    JSP-Servlet-JSPExecuteSource
    Custom tag exampleExecuteSource
    XML syntax exampleExecuteSource
    + +

    Tag Plugins

    + + + + + + + + + + + + + + + + + + + + +
    If + + Execute + + + Source +
    ForEach + + Execute + + + Source +
    Choose + + Execute + + + Source +
    + +

    Other Examples

    + + + + + + + + + + + +
    FORM Authentication + Execute +
    Example that demonstrates protecting a resource and + using Form-Based authentication. To access the page the user must + have role of either "tomcat" or "role1". By default no user + is configured to have these roles.
    + + diff --git a/tomcat/examples/jsp/jsp2/el/Functions.java.html b/tomcat/examples/jsp/jsp2/el/Functions.java.html new file mode 100644 index 0000000..aa84ccc --- /dev/null +++ b/tomcat/examples/jsp/jsp2/el/Functions.java.html @@ -0,0 +1,46 @@ +Source Code
    /*
    +* 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.
    +*/
    +package jsp2.examples.el;
    +
    +import java.util.Locale;
    +
    +/**
    + * Defines the functions for the jsp2 example tag library.
    + *
    + * <p>Each function is defined as a static method.</p>
    + */
    +public class Functions {
    +    public static String reverse( String text ) {
    +        return new StringBuilder( text ).reverse().toString();
    +    }
    +
    +    public static int numVowels( String text ) {
    +        String vowels = "aeiouAEIOU";
    +        int result = 0;
    +        for( int i = 0; i < text.length(); i++ ) {
    +            if( vowels.indexOf( text.charAt( i ) ) != -1 ) {
    +                result++;
    +            }
    +        }
    +        return result;
    +    }
    +
    +    public static String caps( String text ) {
    +        return text.toUpperCase(Locale.ENGLISH);
    +    }
    +}
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsp2/el/ValuesBean.java.html b/tomcat/examples/jsp/jsp2/el/ValuesBean.java.html new file mode 100644 index 0000000..3744236 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/el/ValuesBean.java.html @@ -0,0 +1,53 @@ +Source Code
    /*
    +* 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.
    +*/
    +
    +
    +package jsp2.examples;
    +
    +/**
    + * Accept and display a value.
    + */
    +public class ValuesBean {
    +    private String string;
    +    private double doubleValue;
    +    private long longValue;
    +
    +    public String getStringValue() {
    +        return this.string;
    +    }
    +
    +    public void setStringValue(String string) {
    +        this.string = string;
    +    }
    +
    +    public double getDoubleValue() {
    +        return doubleValue;
    +    }
    +
    +    public void setDoubleValue(double doubleValue) {
    +        this.doubleValue = doubleValue;
    +    }
    +
    +    public long getLongValue() {
    +        return longValue;
    +    }
    +
    +    public void setLongValue(long longValue) {
    +        this.longValue = longValue;
    +    }
    +}
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsp2/el/ValuesTag.java.html b/tomcat/examples/jsp/jsp2/el/ValuesTag.java.html new file mode 100644 index 0000000..490d212 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/el/ValuesTag.java.html @@ -0,0 +1,80 @@ +Source Code
    /*
    + * 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.
    + */
    +package examples;
    +
    +import java.io.IOException;
    +
    +import javax.servlet.jsp.JspException;
    +import javax.servlet.jsp.JspTagException;
    +import javax.servlet.jsp.JspWriter;
    +import javax.servlet.jsp.tagext.TagSupport;
    +
    +/**
    + * Accept and display a value.
    + */
    +public class ValuesTag extends TagSupport {
    +
    +    private static final long serialVersionUID = 1L;
    +
    +    // Using "-1" as the default value,
    +    // in the assumption that it won't be used as the value.
    +    // Cannot use null here, because null is an important case
    +    // that should be present in the tests.
    +    private Object objectValue = "-1";
    +    private String stringValue = "-1";
    +    private long longValue = -1;
    +    private double doubleValue = -1;
    +
    +    public void setObject(Object objectValue) {
    +        this.objectValue = objectValue;
    +    }
    +
    +    public void setString(String stringValue) {
    +        this.stringValue = stringValue;
    +    }
    +
    +    public void setLong(long longValue) {
    +        this.longValue = longValue;
    +    }
    +
    +    public void setDouble(double doubleValue) {
    +        this.doubleValue = doubleValue;
    +    }
    +
    +    @Override
    +    public int doEndTag() throws JspException {
    +        JspWriter out = pageContext.getOut();
    +
    +        try {
    +            if (!"-1".equals(objectValue)) {
    +                out.print(objectValue);
    +            } else if (!"-1".equals(stringValue)) {
    +                out.print(stringValue);
    +            } else if (longValue != -1) {
    +                out.print(longValue);
    +            } else if (doubleValue != -1) {
    +                out.print(doubleValue);
    +            } else {
    +                out.print("-1");
    +            }
    +        } catch (IOException ex) {
    +            throw new JspTagException("IOException: " + ex.toString(), ex);
    +        }
    +        return super.doEndTag();
    +    }
    +}
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsp2/el/basic-arithmetic.html b/tomcat/examples/jsp/jsp2/el/basic-arithmetic.html new file mode 100644 index 0000000..8a2f0a6 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/el/basic-arithmetic.html @@ -0,0 +1,30 @@ + + + +View Source Code + + + + +

    + +

    Source Code for Basic Arithmetic Example +

    + + + diff --git a/tomcat/examples/jsp/jsp2/el/basic-arithmetic.jsp b/tomcat/examples/jsp/jsp2/el/basic-arithmetic.jsp new file mode 100644 index 0000000..757e809 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/el/basic-arithmetic.jsp @@ -0,0 +1,88 @@ +<%-- + 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. +--%> + + + JSP 2.0 Expression Language - Basic Arithmetic + + +

    JSP 2.0 Expression Language - Basic Arithmetic

    +
    + This example illustrates basic Expression Language arithmetic. + Addition (+), subtraction (-), multiplication (*), division (/ or div), + and modulus (% or mod) are all supported. Error conditions, like + division by zero, are handled gracefully. +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    EL ExpressionResult
    \${1}${1}
    \${1 + 2}${1 + 2}
    \${1.2 + 2.3}${1.2 + 2.3}
    \${1.2E4 + 1.4}${1.2E4 + 1.4}
    \${-4 - 2}${-4 - 2}
    \${21 * 2}${21 * 2}
    \${3/4}${3/4}
    \${3 div 4}${3 div 4}
    \${3/0}${3/0}
    \${10%4}${10%4}
    \${10 mod 4}${10 mod 4}
    \${(1==2) ? 3 : 4}${(1==2) ? 3 : 4}
    +
    +
    + + diff --git a/tomcat/examples/jsp/jsp2/el/basic-arithmetic.jsp.html b/tomcat/examples/jsp/jsp2/el/basic-arithmetic.jsp.html new file mode 100644 index 0000000..b8e1a69 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/el/basic-arithmetic.jsp.html @@ -0,0 +1,89 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<html>
    +  <head>
    +    <title>JSP 2.0 Expression Language - Basic Arithmetic</title>
    +  </head>
    +  <body>
    +    <h1>JSP 2.0 Expression Language - Basic Arithmetic</h1>
    +    <hr>
    +    This example illustrates basic Expression Language arithmetic.
    +    Addition (+), subtraction (-), multiplication (*), division (/ or div),
    +    and modulus (% or mod) are all supported.  Error conditions, like
    +    division by zero, are handled gracefully.
    +    <br>
    +    <blockquote>
    +      <code>
    +        <table border="1">
    +          <thead>
    +        <td><b>EL Expression</b></td>
    +        <td><b>Result</b></td>
    +      </thead>
    +      <tr>
    +        <td>\${1}</td>
    +        <td>${1}</td>
    +      </tr>
    +      <tr>
    +        <td>\${1 + 2}</td>
    +        <td>${1 + 2}</td>
    +      </tr>
    +      <tr>
    +        <td>\${1.2 + 2.3}</td>
    +        <td>${1.2 + 2.3}</td>
    +      </tr>
    +      <tr>
    +        <td>\${1.2E4 + 1.4}</td>
    +        <td>${1.2E4 + 1.4}</td>
    +      </tr>
    +      <tr>
    +        <td>\${-4 - 2}</td>
    +        <td>${-4 - 2}</td>
    +      </tr>
    +      <tr>
    +        <td>\${21 * 2}</td>
    +        <td>${21 * 2}</td>
    +      </tr>
    +      <tr>
    +        <td>\${3/4}</td>
    +        <td>${3/4}</td>
    +      </tr>
    +      <tr>
    +        <td>\${3 div 4}</td>
    +        <td>${3 div 4}</td>
    +      </tr>
    +      <tr>
    +        <td>\${3/0}</td>
    +        <td>${3/0}</td>
    +      </tr>
    +      <tr>
    +        <td>\${10%4}</td>
    +        <td>${10%4}</td>
    +      </tr>
    +      <tr>
    +        <td>\${10 mod 4}</td>
    +        <td>${10 mod 4}</td>
    +      </tr>
    +    <tr>
    +      <td>\${(1==2) ? 3 : 4}</td>
    +      <td>${(1==2) ? 3 : 4}</td>
    +    </tr>
    +    </table>
    +      </code>
    +    </blockquote>
    +  </body>
    +</html>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsp2/el/basic-comparisons.html b/tomcat/examples/jsp/jsp2/el/basic-comparisons.html new file mode 100644 index 0000000..60fb40a --- /dev/null +++ b/tomcat/examples/jsp/jsp2/el/basic-comparisons.html @@ -0,0 +1,30 @@ + + + +View Source Code + + + + +

    + +

    Source Code for Basic Comparisons Example +

    + + + diff --git a/tomcat/examples/jsp/jsp2/el/basic-comparisons.jsp b/tomcat/examples/jsp/jsp2/el/basic-comparisons.jsp new file mode 100644 index 0000000..d72f724 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/el/basic-comparisons.jsp @@ -0,0 +1,116 @@ +<%-- + 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. +--%> + + + JSP 2.0 Expression Language - Basic Comparisons + + +

    JSP 2.0 Expression Language - Basic Comparisons

    +
    + This example illustrates basic Expression Language comparisons. + The following comparison operators are supported: +
      +
    • Less-than (< or lt)
    • +
    • Greater-than (> or gt)
    • +
    • Less-than-or-equal (<= or le)
    • +
    • Greater-than-or-equal (>= or ge)
    • +
    • Equal (== or eq)
    • +
    • Not Equal (!= or ne)
    • +
    +
    + Numeric + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    EL ExpressionResult
    \${1 < 2}${1 < 2}
    \${1 lt 2}${1 lt 2}
    \${1 > (4/2)}${1 > (4/2)}
    \${1 gt (4/2)}${1 gt (4/2)}
    \${4.0 >= 3}${4.0 >= 3}
    \${4.0 ge 3}${4.0 ge 3}
    \${4 <= 3}${4 <= 3}
    \${4 le 3}${4 le 3}
    \${100.0 == 100}${100.0 == 100}
    \${100.0 eq 100}${100.0 eq 100}
    \${(10*10) != 100}${(10*10) != 100}
    \${(10*10) ne 100}${(10*10) ne 100}
    +
    +
    + Alphabetic + + + + + + + + + + + + + + + + + + +
    EL ExpressionResult
    \${'a' < 'b'}${'a' < 'b'}
    \${'hip' > 'hit'}${'hip' > 'hit'}
    \${'4' > 3}${'4' > 3}
    +
    +
    + + diff --git a/tomcat/examples/jsp/jsp2/el/basic-comparisons.jsp.html b/tomcat/examples/jsp/jsp2/el/basic-comparisons.jsp.html new file mode 100644 index 0000000..d20471e --- /dev/null +++ b/tomcat/examples/jsp/jsp2/el/basic-comparisons.jsp.html @@ -0,0 +1,117 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<html>
    +  <head>
    +    <title>JSP 2.0 Expression Language - Basic Comparisons</title>
    +  </head>
    +  <body>
    +    <h1>JSP 2.0 Expression Language - Basic Comparisons</h1>
    +    <hr>
    +    This example illustrates basic Expression Language comparisons.
    +    The following comparison operators are supported:
    +    <ul>
    +      <li>Less-than (&lt; or lt)</li>
    +      <li>Greater-than (&gt; or gt)</li>
    +      <li>Less-than-or-equal (&lt;= or le)</li>
    +      <li>Greater-than-or-equal (&gt;= or ge)</li>
    +      <li>Equal (== or eq)</li>
    +      <li>Not Equal (!= or ne)</li>
    +    </ul>
    +    <blockquote>
    +      <u><b>Numeric</b></u>
    +      <code>
    +        <table border="1">
    +          <thead>
    +        <td><b>EL Expression</b></td>
    +        <td><b>Result</b></td>
    +      </thead>
    +      <tr>
    +        <td>\${1 &lt; 2}</td>
    +        <td>${1 < 2}</td>
    +      </tr>
    +      <tr>
    +        <td>\${1 lt 2}</td>
    +        <td>${1 lt 2}</td>
    +      </tr>
    +      <tr>
    +        <td>\${1 &gt; (4/2)}</td>
    +        <td>${1 > (4/2)}</td>
    +      </tr>
    +      <tr>
    +        <td>\${1 gt (4/2)}</td>
    +        <td>${1 gt (4/2)}</td>
    +      </tr>
    +      <tr>
    +        <td>\${4.0 &gt;= 3}</td>
    +        <td>${4.0 >= 3}</td>
    +      </tr>
    +      <tr>
    +        <td>\${4.0 ge 3}</td>
    +        <td>${4.0 ge 3}</td>
    +      </tr>
    +      <tr>
    +        <td>\${4 &lt;= 3}</td>
    +        <td>${4 <= 3}</td>
    +      </tr>
    +      <tr>
    +        <td>\${4 le 3}</td>
    +        <td>${4 le 3}</td>
    +      </tr>
    +      <tr>
    +        <td>\${100.0 == 100}</td>
    +        <td>${100.0 == 100}</td>
    +      </tr>
    +      <tr>
    +        <td>\${100.0 eq 100}</td>
    +        <td>${100.0 eq 100}</td>
    +      </tr>
    +      <tr>
    +        <td>\${(10*10) != 100}</td>
    +        <td>${(10*10) != 100}</td>
    +      </tr>
    +      <tr>
    +        <td>\${(10*10) ne 100}</td>
    +        <td>${(10*10) ne 100}</td>
    +      </tr>
    +    </table>
    +      </code>
    +      <br>
    +      <u><b>Alphabetic</b></u>
    +      <code>
    +        <table border="1">
    +          <thead>
    +            <td><b>EL Expression</b></td>
    +            <td><b>Result</b></td>
    +          </thead>
    +          <tr>
    +            <td>\${'a' &lt; 'b'}</td>
    +            <td>${'a' < 'b'}</td>
    +          </tr>
    +          <tr>
    +            <td>\${'hip' &gt; 'hit'}</td>
    +            <td>${'hip' > 'hit'}</td>
    +          </tr>
    +          <tr>
    +            <td>\${'4' &gt; 3}</td>
    +            <td>${'4' > 3}</td>
    +          </tr>
    +        </table>
    +      </code>
    +    </blockquote>
    +  </body>
    +</html>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsp2/el/composite.html b/tomcat/examples/jsp/jsp2/el/composite.html new file mode 100644 index 0000000..5900008 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/el/composite.html @@ -0,0 +1,31 @@ + + + +View Source Code + + + + +

    + +

    Source Code for composite.jsp

    +

    Source Code for ValuesTag.java

    +

    Source Code for ValuesBean.java

    + + + diff --git a/tomcat/examples/jsp/jsp2/el/composite.jsp b/tomcat/examples/jsp/jsp2/el/composite.jsp new file mode 100644 index 0000000..ae671d48 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/el/composite.jsp @@ -0,0 +1,110 @@ +<%-- + 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. +--%> +<%@ taglib prefix="my" uri="http://tomcat.apache.org/example-taglib" %> + + + + JSP 2.0 Expression Language - Composite Expressions + + +

    JSP 2.0 Expression Language - Composite Expressions

    +
    + This example illustrates EL composite expressions. Composite expressions + are formed by grouping together multiple EL expressions. Each of them is + evaluated from left to right, coerced to String, all those strings are + concatenated, and the result is coerced to the expected type. + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    EL ExpressionTypeResult
    \${'hello'} wo\${'rld'}String${values.stringValue}
    \${'hello'} wo\${'rld'}String
    \${1+2}.\${220}Double${values.doubleValue}
    \${1+2}.\${220}Double
    000\${1}\${7}Long${values.longValue}
    000\${1}\${7}Long
    \${undefinedFoo}hello world\${undefinedBar}String${values.stringValue}
    \${undefinedFoo}hello world\${undefinedBar}String
    \${undefinedFoo}\${undefinedBar}Double${values.doubleValue}
    \${undefinedFoo}\${undefinedBar}Double
    \${undefinedFoo}\${undefinedBar}Long${values.longValue}
    \${undefinedFoo}\${undefinedBar}Long
    +
    +
    + + + diff --git a/tomcat/examples/jsp/jsp2/el/composite.jsp.html b/tomcat/examples/jsp/jsp2/el/composite.jsp.html new file mode 100644 index 0000000..375555f --- /dev/null +++ b/tomcat/examples/jsp/jsp2/el/composite.jsp.html @@ -0,0 +1,111 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<%@ taglib prefix="my" uri="http://tomcat.apache.org/example-taglib" %>
    +
    +<html>
    +  <head>
    +    <title>JSP 2.0 Expression Language - Composite Expressions</title>
    +  </head>
    +  <body>
    +    <h1>JSP 2.0 Expression Language - Composite Expressions</h1>
    +    <hr>
    +    This example illustrates EL composite expressions. Composite expressions
    +    are formed by grouping together multiple EL expressions. Each of them is
    +    evaluated from left to right, coerced to String, all those strings are
    +    concatenated, and the result is coerced to the expected type.
    +
    +    <jsp:useBean id="values" class="jsp2.examples.ValuesBean" />
    +
    +    <blockquote>
    +      <code>
    +        <table border="1">
    +          <thead>
    +        <td><b>EL Expression</b></td>
    +        <td><b>Type</b></td>
    +        <td><b>Result</b></td>
    +      </thead>
    +      <tr>
    +        <td>\${'hello'} wo\${'rld'}</td>
    +        <td>String</td>
    +        <td><jsp:setProperty name="values" property="stringValue" value="${'hello'} wo${'rld'}"/>${values.stringValue}</td>
    +      </tr>
    +      <tr>
    +        <td>\${'hello'} wo\${'rld'}</td>
    +        <td>String</td>
    +        <td><my:values string="${'hello'} wo${'rld'}"/></td>
    +      </tr>
    +      <tr>
    +        <td>\${1+2}.\${220}</td>
    +        <td>Double</td>
    +        <td><jsp:setProperty name="values" property="doubleValue" value="${1+2}.${220}"/>${values.doubleValue}</td>
    +      </tr>
    +      <tr>
    +        <td>\${1+2}.\${220}</td>
    +        <td>Double</td>
    +        <td><my:values double="${1+2}.${220}"/></td>
    +      </tr>
    +      <tr>
    +        <td>000\${1}\${7}</td>
    +        <td>Long</td>
    +        <td><jsp:setProperty name="values" property="longValue" value="000${1}${7}"/>${values.longValue}</td>
    +      </tr>
    +      <tr>
    +        <td>000\${1}\${7}</td>
    +        <td>Long</td>
    +        <td><my:values long="000${1}${7}"/></td>
    +      </tr>
    +      <!--
    +         Undefined values are to be coerced to String, to be "",
    +         https://bz.apache.org/bugzilla/show_bug.cgi?id=47413
    +       -->
    +      <tr>
    +        <td>\${undefinedFoo}hello world\${undefinedBar}</td>
    +        <td>String</td>
    +        <td><jsp:setProperty name="values" property="stringValue" value="${undefinedFoo}hello world${undefinedBar}"/>${values.stringValue}</td>
    +      </tr>
    +      <tr>
    +        <td>\${undefinedFoo}hello world\${undefinedBar}</td>
    +        <td>String</td>
    +        <td><my:values string="${undefinedFoo}hello world${undefinedBar}"/></td>
    +      </tr>
    +      <tr>
    +        <td>\${undefinedFoo}\${undefinedBar}</td>
    +        <td>Double</td>
    +        <td><jsp:setProperty name="values" property="doubleValue" value="${undefinedFoo}${undefinedBar}"/>${values.doubleValue}</td>
    +      </tr>
    +      <tr>
    +        <td>\${undefinedFoo}\${undefinedBar}</td>
    +        <td>Double</td>
    +        <td><my:values double="${undefinedFoo}${undefinedBar}"/></td>
    +      </tr>
    +      <tr>
    +        <td>\${undefinedFoo}\${undefinedBar}</td>
    +        <td>Long</td>
    +        <td><jsp:setProperty name="values" property="longValue" value="${undefinedFoo}${undefinedBar}"/>${values.longValue}</td>
    +      </tr>
    +      <tr>
    +        <td>\${undefinedFoo}\${undefinedBar}</td>
    +        <td>Long</td>
    +        <td><my:values long="${undefinedFoo}${undefinedBar}"/></td>
    +      </tr>
    +    </table>
    +      </code>
    +    </blockquote>
    +  </body>
    +</html>
    +
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsp2/el/functions.html b/tomcat/examples/jsp/jsp2/el/functions.html new file mode 100644 index 0000000..726dda3 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/el/functions.html @@ -0,0 +1,32 @@ + + + +View Source Code + + + + +

    + +

    Source Code for functions.jsp +

    +

    Source Code for Functions.java +

    + + + diff --git a/tomcat/examples/jsp/jsp2/el/functions.jsp b/tomcat/examples/jsp/jsp2/el/functions.jsp new file mode 100644 index 0000000..12b3fa9 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/el/functions.jsp @@ -0,0 +1,67 @@ +<%-- + 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. +--%> +<%@page contentType="text/html; charset=UTF-8" %> +<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> +<%@ taglib prefix="my" uri="http://tomcat.apache.org/jsp2-example-taglib"%> + + + + JSP 2.0 Expression Language - Functions + + +

    JSP 2.0 Expression Language - Functions

    +
    + An upgrade from the JSTL expression language, the JSP 2.0 EL also + allows for simple function invocation. Functions are defined + by tag libraries and are implemented by a Java programmer as + static methods. + +
    + Change Parameter +
    + foo = + +
    +
    + + + + + + + + + + + + + + + + + + + + + + +
    EL ExpressionResult
    \${param["foo"]}${fn:escapeXml(param["foo"])} 
    \${my:reverse(param["foo"])}${my:reverse(fn:escapeXml(param["foo"]))} 
    \${my:reverse(my:reverse(param["foo"]))}${my:reverse(my:reverse(fn:escapeXml(param["foo"])))} 
    \${my:countVowels(param["foo"])}${my:countVowels(fn:escapeXml(param["foo"]))} 
    +
    +
    + + + diff --git a/tomcat/examples/jsp/jsp2/el/functions.jsp.html b/tomcat/examples/jsp/jsp2/el/functions.jsp.html new file mode 100644 index 0000000..1a3cdb4 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/el/functions.jsp.html @@ -0,0 +1,68 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<%@page contentType="text/html; charset=UTF-8" %>
    +<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
    +<%@ taglib prefix="my" uri="http://tomcat.apache.org/jsp2-example-taglib"%>
    +
    +<html>
    +  <head>
    +    <title>JSP 2.0 Expression Language - Functions</title>
    +  </head>
    +  <body>
    +    <h1>JSP 2.0 Expression Language - Functions</h1>
    +    <hr>
    +    An upgrade from the JSTL expression language, the JSP 2.0 EL also
    +    allows for simple function invocation.  Functions are defined
    +    by tag libraries and are implemented by a Java programmer as
    +    static methods.
    +
    +    <blockquote>
    +      <u><b>Change Parameter</b></u>
    +      <form action="functions.jsp" method="GET">
    +          foo = <input type="text" name="foo" value="${fn:escapeXml(param["foo"])}">
    +          <input type="submit">
    +      </form>
    +      <br>
    +      <code>
    +        <table border="1">
    +          <thead>
    +            <td><b>EL Expression</b></td>
    +            <td><b>Result</b></td>
    +          </thead>
    +          <tr>
    +            <td>\${param["foo"]}</td>
    +            <td>${fn:escapeXml(param["foo"])}&nbsp;</td>
    +          </tr>
    +          <tr>
    +            <td>\${my:reverse(param["foo"])}</td>
    +            <td>${my:reverse(fn:escapeXml(param["foo"]))}&nbsp;</td>
    +          </tr>
    +          <tr>
    +            <td>\${my:reverse(my:reverse(param["foo"]))}</td>
    +            <td>${my:reverse(my:reverse(fn:escapeXml(param["foo"])))}&nbsp;</td>
    +          </tr>
    +          <tr>
    +            <td>\${my:countVowels(param["foo"])}</td>
    +            <td>${my:countVowels(fn:escapeXml(param["foo"]))}&nbsp;</td>
    +          </tr>
    +        </table>
    +      </code>
    +    </blockquote>
    +  </body>
    +</html>
    +
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsp2/el/implicit-objects.html b/tomcat/examples/jsp/jsp2/el/implicit-objects.html new file mode 100644 index 0000000..15268db --- /dev/null +++ b/tomcat/examples/jsp/jsp2/el/implicit-objects.html @@ -0,0 +1,31 @@ + + + +View Source Code + + + + +

    +

    + +

    Source Code for Implicit Objects Example +

    + + + diff --git a/tomcat/examples/jsp/jsp2/el/implicit-objects.jsp b/tomcat/examples/jsp/jsp2/el/implicit-objects.jsp new file mode 100644 index 0000000..b557714 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/el/implicit-objects.jsp @@ -0,0 +1,90 @@ +<%-- + 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. +--%> +<%@page contentType="text/html; charset=UTF-8" %> +<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> + + + + JSP 2.0 Expression Language - Implicit Objects + + +

    JSP 2.0 Expression Language - Implicit Objects

    +
    + This example illustrates some of the implicit objects available + in the Expression Language. The following implicit objects are + available (not all illustrated here): +
      +
    • pageContext - the PageContext object
    • +
    • pageScope - a Map that maps page-scoped attribute names to + their values
    • +
    • requestScope - a Map that maps request-scoped attribute names + to their values
    • +
    • sessionScope - a Map that maps session-scoped attribute names + to their values
    • +
    • applicationScope - a Map that maps application-scoped attribute + names to their values
    • +
    • param - a Map that maps parameter names to a single String + parameter value
    • +
    • paramValues - a Map that maps parameter names to a String[] of + all values for that parameter
    • +
    • header - a Map that maps header names to a single String + header value
    • +
    • headerValues - a Map that maps header names to a String[] of + all values for that header
    • +
    • initParam - a Map that maps context initialization parameter + names to their String parameter value
    • +
    • cookie - a Map that maps cookie names to a single Cookie object.
    • +
    + +
    + Change Parameter +
    + foo = + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    EL ExpressionResult
    \${param.foo}${fn:escapeXml(param["foo"])} 
    \${param["foo"]}${fn:escapeXml(param["foo"])} 
    \${header["host"]}${fn:escapeXml(header["host"])} 
    \${header["accept"]}${fn:escapeXml(header["accept"])} 
    \${header["user-agent"]}${fn:escapeXml(header["user-agent"])} 
    +
    +
    + + diff --git a/tomcat/examples/jsp/jsp2/el/implicit-objects.jsp.html b/tomcat/examples/jsp/jsp2/el/implicit-objects.jsp.html new file mode 100644 index 0000000..db967e7 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/el/implicit-objects.jsp.html @@ -0,0 +1,91 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<%@page contentType="text/html; charset=UTF-8" %>
    +<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
    +
    +<html>
    +  <head>
    +    <title>JSP 2.0 Expression Language - Implicit Objects</title>
    +  </head>
    +  <body>
    +    <h1>JSP 2.0 Expression Language - Implicit Objects</h1>
    +    <hr>
    +    This example illustrates some of the implicit objects available
    +    in the Expression Language.  The following implicit objects are
    +    available (not all illustrated here):
    +    <ul>
    +      <li>pageContext - the PageContext object</li>
    +      <li>pageScope - a Map that maps page-scoped attribute names to
    +          their values</li>
    +      <li>requestScope - a Map that maps request-scoped attribute names
    +          to their values</li>
    +      <li>sessionScope - a Map that maps session-scoped attribute names
    +          to their values</li>
    +      <li>applicationScope - a Map that maps application-scoped attribute
    +          names to their values</li>
    +      <li>param - a Map that maps parameter names to a single String
    +          parameter value</li>
    +      <li>paramValues - a Map that maps parameter names to a String[] of
    +          all values for that parameter</li>
    +      <li>header - a Map that maps header names to a single String
    +          header value</li>
    +      <li>headerValues - a Map that maps header names to a String[] of
    +          all values for that header</li>
    +      <li>initParam - a Map that maps context initialization parameter
    +          names to their String parameter value</li>
    +      <li>cookie - a Map that maps cookie names to a single Cookie object.</li>
    +    </ul>
    +
    +    <blockquote>
    +      <u><b>Change Parameter</b></u>
    +      <form action="implicit-objects.jsp" method="GET">
    +          foo = <input type="text" name="foo" value="${fn:escapeXml(param["foo"])}">
    +          <input type="submit">
    +      </form>
    +      <br>
    +      <code>
    +        <table border="1">
    +          <thead>
    +            <td><b>EL Expression</b></td>
    +            <td><b>Result</b></td>
    +          </thead>
    +          <tr>
    +            <td>\${param.foo}</td>
    +            <td>${fn:escapeXml(param["foo"])}&nbsp;</td>
    +          </tr>
    +          <tr>
    +            <td>\${param["foo"]}</td>
    +            <td>${fn:escapeXml(param["foo"])}&nbsp;</td>
    +          </tr>
    +          <tr>
    +            <td>\${header["host"]}</td>
    +            <td>${fn:escapeXml(header["host"])}&nbsp;</td>
    +          </tr>
    +          <tr>
    +            <td>\${header["accept"]}</td>
    +            <td>${fn:escapeXml(header["accept"])}&nbsp;</td>
    +          </tr>
    +          <tr>
    +            <td>\${header["user-agent"]}</td>
    +            <td>${fn:escapeXml(header["user-agent"])}&nbsp;</td>
    +          </tr>
    +        </table>
    +      </code>
    +    </blockquote>
    +  </body>
    +</html>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsp2/jspattribute/FooBean.java.html b/tomcat/examples/jsp/jsp2/jspattribute/FooBean.java.html new file mode 100644 index 0000000..a5ddf41 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/jspattribute/FooBean.java.html @@ -0,0 +1,37 @@ +Source Code
    /*
    +* 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.
    +*/
    +
    +
    +package jsp2.examples;
    +
    +public class FooBean {
    +    private String bar;
    +
    +    public FooBean() {
    +        bar = "Initial value";
    +    }
    +
    +    public String getBar() {
    +        return this.bar;
    +    }
    +
    +    public void setBar(String bar) {
    +        this.bar = bar;
    +    }
    +
    +}
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsp2/jspattribute/HelloWorldSimpleTag.java.html b/tomcat/examples/jsp/jsp2/jspattribute/HelloWorldSimpleTag.java.html new file mode 100644 index 0000000..8c0bd4d --- /dev/null +++ b/tomcat/examples/jsp/jsp2/jspattribute/HelloWorldSimpleTag.java.html @@ -0,0 +1,35 @@ +Source Code
    /*
    +* 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.
    +*/
    +
    +
    +package jsp2.examples.simpletag;
    +
    +import java.io.IOException;
    +
    +import javax.servlet.jsp.JspException;
    +import javax.servlet.jsp.tagext.SimpleTagSupport;
    +
    +/**
    + * SimpleTag handler that prints "Hello, world!"
    + */
    +public class HelloWorldSimpleTag extends SimpleTagSupport {
    +    @Override
    +    public void doTag() throws JspException, IOException {
    +        getJspContext().getOut().write( "Hello, world!" );
    +    }
    +}
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsp2/jspattribute/ShuffleSimpleTag.java.html b/tomcat/examples/jsp/jsp2/jspattribute/ShuffleSimpleTag.java.html new file mode 100644 index 0000000..8d36084 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/jspattribute/ShuffleSimpleTag.java.html @@ -0,0 +1,88 @@ +Source Code
    /*
    +* 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.
    +*/
    +
    +
    +package jsp2.examples.simpletag;
    +
    +import java.io.IOException;
    +import java.util.Random;
    +
    +import javax.servlet.jsp.JspException;
    +import javax.servlet.jsp.tagext.JspFragment;
    +import javax.servlet.jsp.tagext.SimpleTagSupport;
    +
    +/**
    + * SimpleTag handler that accepts takes three attributes of type
    + * JspFragment and invokes then in a random order.
    + */
    +public class ShuffleSimpleTag extends SimpleTagSupport {
    +    // No need for this to use SecureRandom
    +    private static final Random random = new Random();
    +
    +    private JspFragment fragment1;
    +    private JspFragment fragment2;
    +    private JspFragment fragment3;
    +
    +    @Override
    +    public void doTag() throws JspException, IOException {
    +        switch(random.nextInt(6)) {
    +            case 0:
    +                fragment1.invoke( null );
    +                fragment2.invoke( null );
    +                fragment3.invoke( null );
    +                break;
    +            case 1:
    +                fragment1.invoke( null );
    +                fragment3.invoke( null );
    +                fragment2.invoke( null );
    +                break;
    +            case 2:
    +                fragment2.invoke( null );
    +                fragment1.invoke( null );
    +                fragment3.invoke( null );
    +                break;
    +            case 3:
    +                fragment2.invoke( null );
    +                fragment3.invoke( null );
    +                fragment1.invoke( null );
    +                break;
    +            case 4:
    +                fragment3.invoke( null );
    +                fragment1.invoke( null );
    +                fragment2.invoke( null );
    +                break;
    +            case 5:
    +                fragment3.invoke( null );
    +                fragment2.invoke( null );
    +                fragment1.invoke( null );
    +                break;
    +        }
    +    }
    +
    +    public void setFragment1( JspFragment fragment1 ) {
    +        this.fragment1 = fragment1;
    +    }
    +
    +    public void setFragment2( JspFragment fragment2 ) {
    +        this.fragment2 = fragment2;
    +    }
    +
    +    public void setFragment3( JspFragment fragment3 ) {
    +        this.fragment3 = fragment3;
    +    }
    +}
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsp2/jspattribute/TileSimpleTag.java.html b/tomcat/examples/jsp/jsp2/jspattribute/TileSimpleTag.java.html new file mode 100644 index 0000000..75d6daf --- /dev/null +++ b/tomcat/examples/jsp/jsp2/jspattribute/TileSimpleTag.java.html @@ -0,0 +1,49 @@ +Source Code
    /*
    +* 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.
    +*/
    +
    +
    +package jsp2.examples.simpletag;
    +
    +import java.io.IOException;
    +
    +import javax.servlet.jsp.JspException;
    +import javax.servlet.jsp.tagext.SimpleTagSupport;
    +
    +/**
    + * Displays a tile as a single cell in a table.
    + */
    +public class TileSimpleTag extends SimpleTagSupport {
    +    private String color;
    +    private String label;
    +
    +    @Override
    +    public void doTag() throws JspException, IOException {
    +        getJspContext().getOut().write(
    +                "<td width=\"32\" height=\"32\" bgcolor=\"" + this.color +
    +                "\"><font color=\"#ffffff\"><center>" + this.label +
    +                "</center></font></td>" );
    +    }
    +
    +    public void setColor( String color ) {
    +        this.color = color;
    +    }
    +
    +    public void setLabel( String label ) {
    +        this.label = label;
    +    }
    +}
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsp2/jspattribute/jspattribute.html b/tomcat/examples/jsp/jsp2/jspattribute/jspattribute.html new file mode 100644 index 0000000..df1b6e6 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/jspattribute/jspattribute.html @@ -0,0 +1,37 @@ + + + +View Source Code + + + + +

    +

    + +

    Source Code for jspattribute.jsp +

    + +

    Source Code for HelloWorldSimpleTag.java +

    + +

    Source Code for FooBean.java +

    + + + diff --git a/tomcat/examples/jsp/jsp2/jspattribute/jspattribute.jsp b/tomcat/examples/jsp/jsp2/jspattribute/jspattribute.jsp new file mode 100644 index 0000000..8050b34 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/jspattribute/jspattribute.jsp @@ -0,0 +1,46 @@ +<%-- + 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. +--%> +<%@ taglib prefix="my" uri="http://tomcat.apache.org/jsp2-example-taglib"%> + + + + JSP 2.0 Examples - jsp:attribute and jsp:body + + +

    JSP 2.0 Examples - jsp:attribute and jsp:body

    +
    +

    The new <jsp:attribute> and <jsp:body> + standard actions can be used to specify the value of any standard + action or custom action attribute.

    +

    This example uses the <jsp:attribute> + standard action to use the output of a custom action invocation + (one that simply outputs "Hello, World!") to set the value of a + bean property. This would normally require an intermediary + step, such as using JSTL's <c:set> action.

    +
    + + Bean created! Setting foo.bar...
    + + + + + +
    +
    + Result: ${foo.bar} + + diff --git a/tomcat/examples/jsp/jsp2/jspattribute/jspattribute.jsp.html b/tomcat/examples/jsp/jsp2/jspattribute/jspattribute.jsp.html new file mode 100644 index 0000000..9596997 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/jspattribute/jspattribute.jsp.html @@ -0,0 +1,47 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<%@ taglib prefix="my" uri="http://tomcat.apache.org/jsp2-example-taglib"%>
    +
    +<html>
    +  <head>
    +    <title>JSP 2.0 Examples - jsp:attribute and jsp:body</title>
    +  </head>
    +  <body>
    +    <h1>JSP 2.0 Examples - jsp:attribute and jsp:body</h1>
    +    <hr>
    +    <p>The new &lt;jsp:attribute&gt; and &lt;jsp:body&gt;
    +    standard actions can be used to specify the value of any standard
    +    action or custom action attribute.</p>
    +    <p>This example uses the &lt;jsp:attribute&gt;
    +    standard action to use the output of a custom action invocation
    +    (one that simply outputs "Hello, World!") to set the value of a
    +    bean property.  This would normally require an intermediary
    +    step, such as using JSTL's &lt;c:set&gt; action.</p>
    +    <br>
    +    <jsp:useBean id="foo" class="jsp2.examples.FooBean">
    +      Bean created!  Setting foo.bar...<br>
    +      <jsp:setProperty name="foo" property="bar">
    +        <jsp:attribute name="value">
    +          <my:helloWorld/>
    +        </jsp:attribute>
    +      </jsp:setProperty>
    +    </jsp:useBean>
    +    <br>
    +    Result: ${foo.bar}
    +  </body>
    +</html>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsp2/jspattribute/shuffle.html b/tomcat/examples/jsp/jsp2/jspattribute/shuffle.html new file mode 100644 index 0000000..5711860 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/jspattribute/shuffle.html @@ -0,0 +1,37 @@ + + + +View Source Code + + + + +

    +

    + +

    Source Code for shuffle.jsp +

    + +

    Source Code for ShuffleSimpleTag.java +

    + +

    Source Code for TileSimpleTag.java +

    + + + diff --git a/tomcat/examples/jsp/jsp2/jspattribute/shuffle.jsp b/tomcat/examples/jsp/jsp2/jspattribute/shuffle.jsp new file mode 100644 index 0000000..737ff65 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/jspattribute/shuffle.jsp @@ -0,0 +1,90 @@ +<%-- + 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. +--%> +<%@ taglib prefix="my" uri="http://tomcat.apache.org/jsp2-example-taglib"%> + + + + JSP 2.0 Examples - Shuffle Example + + +

    JSP 2.0 Examples - Shuffle Example

    +
    +

    Try reloading the page a few times. Both the rows and the columns + are shuffled and appear different each time.

    +

    Here's how the code works. The SimpleTag handler called + <my:shuffle> accepts three attributes. Each attribute is a + JSP Fragment, meaning it is a fragment of JSP code that can be + dynamically executed by the shuffle tag handler on demand. The + shuffle tag handler executes the three fragments in a random order. + To shuffle both the rows and the columns, the shuffle tag is used + with itself as a parameter.

    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    +
    + + diff --git a/tomcat/examples/jsp/jsp2/jspattribute/shuffle.jsp.html b/tomcat/examples/jsp/jsp2/jspattribute/shuffle.jsp.html new file mode 100644 index 0000000..dcb137d --- /dev/null +++ b/tomcat/examples/jsp/jsp2/jspattribute/shuffle.jsp.html @@ -0,0 +1,91 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<%@ taglib prefix="my" uri="http://tomcat.apache.org/jsp2-example-taglib"%>
    +
    +<html>
    +  <head>
    +    <title>JSP 2.0 Examples - Shuffle Example</title>
    +  </head>
    +  <body>
    +    <h1>JSP 2.0 Examples - Shuffle Example</h1>
    +    <hr>
    +    <p>Try reloading the page a few times.  Both the rows and the columns
    +    are shuffled and appear different each time.</p>
    +    <p>Here's how the code works.  The SimpleTag handler called
    +    &lt;my:shuffle&gt; accepts three attributes.  Each attribute is a
    +    JSP Fragment, meaning it is a fragment of JSP code that can be
    +    dynamically executed by the shuffle tag handler on demand.  The
    +    shuffle tag handler executes the three fragments in a random order.
    +    To shuffle both the rows and the columns, the shuffle tag is used
    +    with itself as a parameter.</p>
    +    <hr>
    +    <blockquote>
    +     <font color="#ffffff">
    +      <table>
    +        <my:shuffle>
    +          <jsp:attribute name="fragment1">
    +            <tr>
    +              <my:shuffle>
    +                <jsp:attribute name="fragment1">
    +                  <my:tile color="#ff0000" label="A"/>
    +                </jsp:attribute>
    +                <jsp:attribute name="fragment2">
    +                  <my:tile color="#00ff00" label="B"/>
    +                </jsp:attribute>
    +                <jsp:attribute name="fragment3">
    +                  <my:tile color="#0000ff" label="C"/>
    +                </jsp:attribute>
    +              </my:shuffle>
    +            </tr>
    +          </jsp:attribute>
    +          <jsp:attribute name="fragment2">
    +            <tr>
    +              <my:shuffle>
    +                <jsp:attribute name="fragment1">
    +                  <my:tile color="#ff0000" label="1"/>
    +                </jsp:attribute>
    +                <jsp:attribute name="fragment2">
    +                  <my:tile color="#00ff00" label="2"/>
    +                </jsp:attribute>
    +                <jsp:attribute name="fragment3">
    +                  <my:tile color="#0000ff" label="3"/>
    +                </jsp:attribute>
    +              </my:shuffle>
    +            </tr>
    +          </jsp:attribute>
    +          <jsp:attribute name="fragment3">
    +            <tr>
    +              <my:shuffle>
    +                <jsp:attribute name="fragment1">
    +                  <my:tile color="#ff0000" label="!"/>
    +                </jsp:attribute>
    +                <jsp:attribute name="fragment2">
    +                  <my:tile color="#00ff00" label="@"/>
    +                </jsp:attribute>
    +                <jsp:attribute name="fragment3">
    +                  <my:tile color="#0000ff" label="#"/>
    +                </jsp:attribute>
    +              </my:shuffle>
    +            </tr>
    +          </jsp:attribute>
    +        </my:shuffle>
    +      </table>
    +     </font>
    +    </blockquote>
    +  </body>
    +</html>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsp2/jspx/basic.html b/tomcat/examples/jsp/jsp2/jspx/basic.html new file mode 100644 index 0000000..f9df6a4 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/jspx/basic.html @@ -0,0 +1,31 @@ + + + + + +View Source Code + + + +

    ExecuteReturn

    + +

    Source Code for XHTML Basic Example

    + + + diff --git a/tomcat/examples/jsp/jsp2/jspx/basic.jspx b/tomcat/examples/jsp/jsp2/jspx/basic.jspx new file mode 100644 index 0000000..fc1e45f --- /dev/null +++ b/tomcat/examples/jsp/jsp2/jspx/basic.jspx @@ -0,0 +1,48 @@ + + + + + + + JSPX - XHTML Basic Example + + +

    JSPX - XHTML Basic Example

    + This example illustrates how to use JSPX to produce an XHTML basic + document suitable for use with mobile phones, televisions, + PDAs, vending machines, pagers, car navigation systems, + mobile game machines, digital book readers, smart watches, etc. +

    + JSPX lets you create dynamic documents in a pure XML syntax compatible + with existing XML tools. The XML syntax in JSP 1.2 was awkward and + required &lt;jsp:root&gt; to be the root element of the document. + This is no longer the case in JSP 2.0. +

    + This particular example uses + namespace declarations to make the output of this page a valid XHTML + document. +

    + Just to prove this is live, here's some dynamic content: + + + + diff --git a/tomcat/examples/jsp/jsp2/jspx/basic.jspx.html b/tomcat/examples/jsp/jsp2/jspx/basic.jspx.html new file mode 100644 index 0000000..6b38336 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/jspx/basic.jspx.html @@ -0,0 +1,49 @@ +Source Code

    <?xml version="1.0" encoding="UTF-8"?>
    +<!--
    +  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.
    +-->
    +<html xmlns:jsp="http://java.sun.com/JSP/Page"
    +      xmlns:fmt="http://java.sun.com/jsp/jstl/fmt"
    +      xmlns="http://www.w3.org/1999/xhtml">
    +  <jsp:output doctype-root-element="html"
    +              doctype-public="-//W3C//DTD XHTML Basic 1.0//EN"
    +              doctype-system="http://www.w3.org/TR/xhtml-basic/xhtml-basic10.dtd"/>
    +  <jsp:directive.page contentType="application/xhtml+xml" />
    +  <head>
    +    <title>JSPX - XHTML Basic Example</title>
    +  </head>
    +  <body>
    +    <h1>JSPX - XHTML Basic Example</h1>
    +    This example illustrates how to use JSPX to produce an XHTML basic
    +    document suitable for use with mobile phones, televisions,
    +    PDAs, vending machines, pagers, car navigation systems,
    +    mobile game machines, digital book readers, smart watches, etc.
    +    <p/>
    +    JSPX lets you create dynamic documents in a pure XML syntax compatible
    +    with existing XML tools.  The XML syntax in JSP 1.2 was awkward and
    +    required &amp;lt;jsp:root&amp;gt; to be the root element of the document.
    +    This is no longer the case in JSP 2.0.
    +    <p/>
    +    This particular example uses
    +    namespace declarations to make the output of this page a valid XHTML
    +    document.
    +    <p/>
    +    Just to prove this is live, here's some dynamic content:
    +    <jsp:useBean id="now" class="java.util.Date" />
    +    <fmt:formatDate value="${now}" pattern="MMMM d, yyyy, H:mm:ss"/>
    +  </body>
    +</html>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsp2/jspx/svgexample.html b/tomcat/examples/jsp/jsp2/jspx/svgexample.html new file mode 100644 index 0000000..f7d591a --- /dev/null +++ b/tomcat/examples/jsp/jsp2/jspx/svgexample.html @@ -0,0 +1,46 @@ + + + + + JSP 2.0 SVG Example + + +

    JSP 2.0 SVG Example

    + This example uses JSP 2.0's new, simplified JSPX syntax to render a + Scalable Vector Graphics (SVG) document. When you view the source, + notice the lack of a <jsp:root> element! The text to be rendered + can be modified by changing the value of the name parameter. +

    + SVG has many potential uses, such as searchable images, or images + customized with the name of your site's visitor (e.g. a "Susan's Store" + tab image). JSPX is a natural fit for generating dynamic XML content + such as SVG. +

    + To execute this example you will need a browser with basic SVG support. Any + remotely recent browser should have this. +

      +
    1. Use this URL: + textRotate.jspx?name=JSPX
    2. +
    3. Customize by changing the name=JSPX parameter
    4. +
    +

    + The following is a screenshot of the resulting image, for those using a + browser without SVG support:
    + [Screenshot image] + + diff --git a/tomcat/examples/jsp/jsp2/jspx/textRotate.html b/tomcat/examples/jsp/jsp2/jspx/textRotate.html new file mode 100644 index 0000000..5b3befe --- /dev/null +++ b/tomcat/examples/jsp/jsp2/jspx/textRotate.html @@ -0,0 +1,32 @@ + + + + + +View Source Code + + + +

    Execute Return

    + +

    Source Code for SVG (Scalable Vector Graphics) +Example

    + + + diff --git a/tomcat/examples/jsp/jsp2/jspx/textRotate.jpg b/tomcat/examples/jsp/jsp2/jspx/textRotate.jpg new file mode 100644 index 0000000..9e98736 Binary files /dev/null and b/tomcat/examples/jsp/jsp2/jspx/textRotate.jpg differ diff --git a/tomcat/examples/jsp/jsp2/jspx/textRotate.jspx b/tomcat/examples/jsp/jsp2/jspx/textRotate.jspx new file mode 100644 index 0000000..c543887 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/jspx/textRotate.jspx @@ -0,0 +1,53 @@ + + + + + + JSP 2.0 JSPX + + + + + JSP 2.0 XML Syntax (.jspx) Demo + + Try changing the name parameter! + + + + <g opacity="0.95" transform="scale(1.05) rotate(15)"> + + ${name} + + + </g> + + ${name} + + + diff --git a/tomcat/examples/jsp/jsp2/jspx/textRotate.jspx.html b/tomcat/examples/jsp/jsp2/jspx/textRotate.jspx.html new file mode 100644 index 0000000..0e6c820 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/jspx/textRotate.jspx.html @@ -0,0 +1,54 @@ +Source Code
    <?xml version="1.0" encoding="UTF-8"?>
    +<!--
    +  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.
    +-->
    +<!--
    +  - This example is based off the textRotate.svg example that comes
    +  - with Apache Batik.  The original example was written by Bill Haneman.
    +  - This version by Mark Roth.
    +  -->
    +<svg xmlns="http://www.w3.org/2000/svg"
    +     width="450" height="500" viewBox="0 0 450 500"
    +     xmlns:c="http://java.sun.com/jsp/jstl/core"
    +     xmlns:fn="http://java.sun.com/jsp/jstl/functions"
    +     xmlns:jsp="http://java.sun.com/JSP/Page">
    +  <jsp:directive.page contentType="image/svg+xml" />
    +  <title>JSP 2.0 JSPX</title>
    +  <!-- select name parameter, or default to JSPX -->
    +  <c:set var="name" value='${empty fn:escapeXml(param["name"]) ? "JSPX" : fn:escapeXml(param["name"])}'/>
    +  <g id="testContent">
    +    <text class="title" x="50%" y="10%" font-size="15" text-anchor="middle" >
    +            JSP 2.0 XML Syntax (.jspx) Demo</text>
    +    <text class="title" x="50%" y="15%" font-size="15" text-anchor="middle" >
    +            Try changing the name parameter!</text>
    +    <g opacity="1.0" transform="translate(225, 250)" id="rotatedText">
    +      <c:forEach var="i" begin="1" end="24">
    +        <jsp:text>
    +          <![CDATA[<g opacity="0.95" transform="scale(1.05) rotate(15)">]]>
    +        </jsp:text>
    +        <text x="0" y="0" transform="scale(1.6, 1.6)" fill="DarkSlateBlue"
    +              text-anchor="middle" font-size="40" font-family="Serif"
    +              id="words">${name}</text>
    +      </c:forEach>
    +      <c:forEach var="i" begin="1" end="24">
    +        <jsp:text><![CDATA[</g>]]></jsp:text>
    +      </c:forEach>
    +      <text style="font-size:75;font-family:Serif;fill:white"
    +            text-anchor="middle">${name}</text>
    +    </g>
    +  </g>
    +</svg>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsp2/misc/EchoAttributesTag.java.html b/tomcat/examples/jsp/jsp2/misc/EchoAttributesTag.java.html new file mode 100644 index 0000000..cab826d --- /dev/null +++ b/tomcat/examples/jsp/jsp2/misc/EchoAttributesTag.java.html @@ -0,0 +1,59 @@ +Source Code
    /*
    +* 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.
    +*/
    +
    +
    +package jsp2.examples.simpletag;
    +
    +import java.io.IOException;
    +import java.util.ArrayList;
    +import java.util.List;
    +
    +import javax.servlet.jsp.JspException;
    +import javax.servlet.jsp.JspWriter;
    +import javax.servlet.jsp.tagext.DynamicAttributes;
    +import javax.servlet.jsp.tagext.SimpleTagSupport;
    +
    +/**
    + * SimpleTag handler that echoes all its attributes
    + */
    +public class EchoAttributesTag
    +    extends SimpleTagSupport
    +    implements DynamicAttributes
    +{
    +    private final List<String> keys = new ArrayList<>();
    +    private final List<Object> values = new ArrayList<>();
    +
    +    @Override
    +    public void doTag() throws JspException, IOException {
    +        JspWriter out = getJspContext().getOut();
    +        for( int i = 0; i < keys.size(); i++ ) {
    +            String key = keys.get( i );
    +            Object value = values.get( i );
    +            out.println( "<li>" + key + " = " + value + "</li>" );
    +        }
    +    }
    +
    +    @Override
    +    public void setDynamicAttribute( String uri, String localName,
    +        Object value )
    +        throws JspException
    +    {
    +        keys.add( localName );
    +        values.add( value );
    +    }
    +}
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsp2/misc/coda.jspf b/tomcat/examples/jsp/jsp2/misc/coda.jspf new file mode 100644 index 0000000..d767de5 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/misc/coda.jspf @@ -0,0 +1,21 @@ + +
    +
    +This banner included with <include-coda> +
    +
    diff --git a/tomcat/examples/jsp/jsp2/misc/coda.jspf.html b/tomcat/examples/jsp/jsp2/misc/coda.jspf.html new file mode 100644 index 0000000..3a82576 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/misc/coda.jspf.html @@ -0,0 +1,22 @@ +Source Code
    <!--
    +  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.
    +-->
    +<hr>
    +<center>
    +This banner included with &lt;include-coda&gt;
    +</center>
    +<hr>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsp2/misc/config.html b/tomcat/examples/jsp/jsp2/misc/config.html new file mode 100644 index 0000000..707d68f --- /dev/null +++ b/tomcat/examples/jsp/jsp2/misc/config.html @@ -0,0 +1,35 @@ + + + +View Source Code + + + + +

    +

    + +

    Source Code for config.jsp +

    +

    Source Code for prelude.jspf +

    +

    Source Code for coda.jspf +

    + + + diff --git a/tomcat/examples/jsp/jsp2/misc/config.jsp b/tomcat/examples/jsp/jsp2/misc/config.jsp new file mode 100644 index 0000000..0372889 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/misc/config.jsp @@ -0,0 +1,32 @@ +<%-- + 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. +--%> +<%@ taglib prefix="my" uri="http://tomcat.apache.org/jsp2-example-taglib"%> +

    JSP 2.0 Examples - JSP Configuration

    +
    +

    Using a <jsp-property-group> element in the web.xml + deployment descriptor, this JSP page has been configured in the + following ways:

    +
      +
    • Uses <include-prelude> to include the top banner.
    • +
    • Uses <include-coda> to include the bottom banner.
    • +
    • Uses <scripting-invalid> true to disable + <% scripting %> elements
    • +
    • Uses <el-ignored> true to disable ${EL} elements
    • +
    • Uses <page-encoding> ISO-8859-1 to set the page encoding (though this is the default anyway)
    • +
    + There are various other configuration options that can be used. + diff --git a/tomcat/examples/jsp/jsp2/misc/config.jsp.html b/tomcat/examples/jsp/jsp2/misc/config.jsp.html new file mode 100644 index 0000000..6ce33ff --- /dev/null +++ b/tomcat/examples/jsp/jsp2/misc/config.jsp.html @@ -0,0 +1,33 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<%@ taglib prefix="my" uri="http://tomcat.apache.org/jsp2-example-taglib"%>
    +    <h1>JSP 2.0 Examples - JSP Configuration</h1>
    +    <hr>
    +    <p>Using a &lt;jsp-property-group&gt; element in the web.xml
    +    deployment descriptor, this JSP page has been configured in the
    +    following ways:</p>
    +    <ul>
    +      <li>Uses &lt;include-prelude&gt; to include the top banner.</li>
    +      <li>Uses &lt;include-coda&gt; to include the bottom banner.</li>
    +      <li>Uses &lt;scripting-invalid&gt; true to disable
    +          &lt;% scripting %&gt; elements</li>
    +      <li>Uses &lt;el-ignored&gt; true to disable ${EL} elements</li>
    +      <li>Uses &lt;page-encoding&gt; ISO-8859-1 to set the page encoding (though this is the default anyway)</li>
    +    </ul>
    +    There are various other configuration options that can be used.
    +
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsp2/misc/dynamicattrs.html b/tomcat/examples/jsp/jsp2/misc/dynamicattrs.html new file mode 100644 index 0000000..4fa1bf1 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/misc/dynamicattrs.html @@ -0,0 +1,33 @@ + + + +View Source Code + + + + +

    +

    + +

    Source Code for dynamicattrs.jsp +

    +

    Source Code for EchoAttributesTag.java +

    + + + diff --git a/tomcat/examples/jsp/jsp2/misc/dynamicattrs.jsp b/tomcat/examples/jsp/jsp2/misc/dynamicattrs.jsp new file mode 100644 index 0000000..251c49d --- /dev/null +++ b/tomcat/examples/jsp/jsp2/misc/dynamicattrs.jsp @@ -0,0 +1,44 @@ +<%-- + 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. +--%> +<%@ taglib prefix="my" uri="http://tomcat.apache.org/jsp2-example-taglib"%> + + + JSP 2.0 Examples - Dynamic Attributes + + +

    JSP 2.0 Examples - Dynamic Attributes

    +
    +

    This JSP page invokes a custom tag that accepts a dynamic set + of attributes. The tag echoes the name and value of all attributes + passed to it.

    +
    +

    Invocation 1 (six attributes)

    +
      + +
    +

    Invocation 2 (zero attributes)

    +
      + +
    +

    Invocation 3 (three attributes)

    +
      + +
    + + diff --git a/tomcat/examples/jsp/jsp2/misc/dynamicattrs.jsp.html b/tomcat/examples/jsp/jsp2/misc/dynamicattrs.jsp.html new file mode 100644 index 0000000..8f5ee18 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/misc/dynamicattrs.jsp.html @@ -0,0 +1,45 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<%@ taglib prefix="my" uri="http://tomcat.apache.org/jsp2-example-taglib"%>
    +<html>
    +  <head>
    +    <title>JSP 2.0 Examples - Dynamic Attributes</title>
    +  </head>
    +  <body>
    +    <h1>JSP 2.0 Examples - Dynamic Attributes</h1>
    +    <hr>
    +    <p>This JSP page invokes a custom tag that accepts a dynamic set
    +    of attributes.  The tag echoes the name and value of all attributes
    +    passed to it.</p>
    +    <hr>
    +    <h2>Invocation 1 (six attributes)</h2>
    +    <ul>
    +      <my:echoAttributes x="1" y="2" z="3" r="red" g="green" b="blue"/>
    +    </ul>
    +    <h2>Invocation 2 (zero attributes)</h2>
    +    <ul>
    +      <my:echoAttributes/>
    +    </ul>
    +    <h2>Invocation 3 (three attributes)</h2>
    +    <ul>
    +      <my:echoAttributes dogName="Scruffy"
    +                         catName="Fluffy"
    +                         blowfishName="Puffy"/>
    +    </ul>
    +  </body>
    +</html>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsp2/misc/prelude.jspf b/tomcat/examples/jsp/jsp2/misc/prelude.jspf new file mode 100644 index 0000000..05f7c84 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/misc/prelude.jspf @@ -0,0 +1,21 @@ + +
    +
    +This banner included with <include-prelude> +
    +
    diff --git a/tomcat/examples/jsp/jsp2/misc/prelude.jspf.html b/tomcat/examples/jsp/jsp2/misc/prelude.jspf.html new file mode 100644 index 0000000..8b2bcd0 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/misc/prelude.jspf.html @@ -0,0 +1,22 @@ +Source Code
    <!--
    +  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.
    +-->
    +<hr>
    +<center>
    +This banner included with &lt;include-prelude&gt;
    +</center>
    +<hr>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsp2/simpletag/BookBean.java.html b/tomcat/examples/jsp/jsp2/simpletag/BookBean.java.html new file mode 100644 index 0000000..5c99dad --- /dev/null +++ b/tomcat/examples/jsp/jsp2/simpletag/BookBean.java.html @@ -0,0 +1,45 @@ +Source Code
    /*
    +* 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.
    +*/
    +
    +
    +package jsp2.examples;
    +
    +public class BookBean {
    +    private final String title;
    +    private final String author;
    +    private final String isbn;
    +
    +    public BookBean( String title, String author, String isbn ) {
    +        this.title = title;
    +        this.author = author;
    +        this.isbn = isbn;
    +    }
    +
    +    public String getTitle() {
    +        return this.title;
    +    }
    +
    +    public String getAuthor() {
    +        return this.author;
    +    }
    +
    +    public String getIsbn() {
    +        return this.isbn;
    +    }
    +
    +}
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsp2/simpletag/FindBookSimpleTag.java.html b/tomcat/examples/jsp/jsp2/simpletag/FindBookSimpleTag.java.html new file mode 100644 index 0000000..17bcddd --- /dev/null +++ b/tomcat/examples/jsp/jsp2/simpletag/FindBookSimpleTag.java.html @@ -0,0 +1,47 @@ +Source Code
    /*
    +* 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.
    +*/
    +
    +
    +package jsp2.examples.simpletag;
    +
    +import javax.servlet.jsp.JspException;
    +import javax.servlet.jsp.tagext.SimpleTagSupport;
    +
    +import jsp2.examples.BookBean;
    +
    +/**
    + * SimpleTag handler that pretends to search for a book, and stores
    + * the result in a scoped variable.
    + */
    +public class FindBookSimpleTag extends SimpleTagSupport {
    +    private String var;
    +
    +    private static final String BOOK_TITLE = "The Lord of the Rings";
    +    private static final String BOOK_AUTHOR = "J. R. R. Tolkien";
    +    private static final String BOOK_ISBN = "0618002251";
    +
    +    @Override
    +    public void doTag() throws JspException {
    +        BookBean book = new BookBean( BOOK_TITLE, BOOK_AUTHOR, BOOK_ISBN );
    +        getJspContext().setAttribute( this.var, book );
    +    }
    +
    +    public void setVar( String var ) {
    +        this.var = var;
    +    }
    +}
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsp2/simpletag/Functions.java.html b/tomcat/examples/jsp/jsp2/simpletag/Functions.java.html new file mode 100644 index 0000000..aa84ccc --- /dev/null +++ b/tomcat/examples/jsp/jsp2/simpletag/Functions.java.html @@ -0,0 +1,46 @@ +Source Code
    /*
    +* 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.
    +*/
    +package jsp2.examples.el;
    +
    +import java.util.Locale;
    +
    +/**
    + * Defines the functions for the jsp2 example tag library.
    + *
    + * <p>Each function is defined as a static method.</p>
    + */
    +public class Functions {
    +    public static String reverse( String text ) {
    +        return new StringBuilder( text ).reverse().toString();
    +    }
    +
    +    public static int numVowels( String text ) {
    +        String vowels = "aeiouAEIOU";
    +        int result = 0;
    +        for( int i = 0; i < text.length(); i++ ) {
    +            if( vowels.indexOf( text.charAt( i ) ) != -1 ) {
    +                result++;
    +            }
    +        }
    +        return result;
    +    }
    +
    +    public static String caps( String text ) {
    +        return text.toUpperCase(Locale.ENGLISH);
    +    }
    +}
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsp2/simpletag/HelloWorldSimpleTag.java.html b/tomcat/examples/jsp/jsp2/simpletag/HelloWorldSimpleTag.java.html new file mode 100644 index 0000000..8c0bd4d --- /dev/null +++ b/tomcat/examples/jsp/jsp2/simpletag/HelloWorldSimpleTag.java.html @@ -0,0 +1,35 @@ +Source Code
    /*
    +* 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.
    +*/
    +
    +
    +package jsp2.examples.simpletag;
    +
    +import java.io.IOException;
    +
    +import javax.servlet.jsp.JspException;
    +import javax.servlet.jsp.tagext.SimpleTagSupport;
    +
    +/**
    + * SimpleTag handler that prints "Hello, world!"
    + */
    +public class HelloWorldSimpleTag extends SimpleTagSupport {
    +    @Override
    +    public void doTag() throws JspException, IOException {
    +        getJspContext().getOut().write( "Hello, world!" );
    +    }
    +}
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsp2/simpletag/RepeatSimpleTag.java.html b/tomcat/examples/jsp/jsp2/simpletag/RepeatSimpleTag.java.html new file mode 100644 index 0000000..12913fc --- /dev/null +++ b/tomcat/examples/jsp/jsp2/simpletag/RepeatSimpleTag.java.html @@ -0,0 +1,45 @@ +Source Code
    /*
    +* 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.
    +*/
    +
    +
    +package jsp2.examples.simpletag;
    +
    +import java.io.IOException;
    +
    +import javax.servlet.jsp.JspException;
    +import javax.servlet.jsp.tagext.SimpleTagSupport;
    +
    +/**
    + * SimpleTag handler that accepts a num attribute and
    + * invokes its body 'num' times.
    + */
    +public class RepeatSimpleTag extends SimpleTagSupport {
    +    private int num;
    +
    +    @Override
    +    public void doTag() throws JspException, IOException {
    +        for (int i=0; i<num; i++) {
    +            getJspContext().setAttribute("count", String.valueOf( i + 1 ) );
    +            getJspBody().invoke(null);
    +        }
    +    }
    +
    +    public void setNum(int num) {
    +        this.num = num;
    +    }
    +}
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsp2/simpletag/book.html b/tomcat/examples/jsp/jsp2/simpletag/book.html new file mode 100644 index 0000000..2841acf --- /dev/null +++ b/tomcat/examples/jsp/jsp2/simpletag/book.html @@ -0,0 +1,37 @@ + + + +View Source Code + + + + +

    +

    + +

    Source Code for the Book Example JSP +

    +

    Source Code for the FindBook SimpleTag Handler +

    +

    Source Code for BookBean +

    +

    Source Code for the EL Functions +

    + + + diff --git a/tomcat/examples/jsp/jsp2/simpletag/book.jsp b/tomcat/examples/jsp/jsp2/simpletag/book.jsp new file mode 100644 index 0000000..ba07cfb --- /dev/null +++ b/tomcat/examples/jsp/jsp2/simpletag/book.jsp @@ -0,0 +1,55 @@ +<%-- + 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. +--%> +<%@ taglib prefix="my" uri="/WEB-INF/jsp2/jsp2-example-taglib.tld" %> + + + JSP 2.0 Examples - Book SimpleTag Handler + + +

    JSP 2.0 Examples - Book SimpleTag Handler

    +
    +

    Illustrates a semi-realistic use of SimpleTag and the Expression + Language. First, a <my:findBook> tag is invoked to populate + the page context with a BookBean. Then, the books fields are printed + in all caps.

    +
    + Result:
    + + + + + + + + + + + + + + + + + + + + + + +
    FieldValueCapitalized
    Title${book.title}${my:caps(book.title)}
    Author${book.author}${my:caps(book.author)}
    ISBN${book.isbn}${my:caps(book.isbn)}
    + + diff --git a/tomcat/examples/jsp/jsp2/simpletag/book.jsp.html b/tomcat/examples/jsp/jsp2/simpletag/book.jsp.html new file mode 100644 index 0000000..51c27a0 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/simpletag/book.jsp.html @@ -0,0 +1,56 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<%@ taglib prefix="my" uri="/WEB-INF/jsp2/jsp2-example-taglib.tld" %>
    +<html>
    +  <head>
    +    <title>JSP 2.0 Examples - Book SimpleTag Handler</title>
    +  </head>
    +  <body>
    +    <h1>JSP 2.0 Examples - Book SimpleTag Handler</h1>
    +    <hr>
    +    <p>Illustrates a semi-realistic use of SimpleTag and the Expression
    +    Language.  First, a &lt;my:findBook&gt; tag is invoked to populate
    +    the page context with a BookBean.  Then, the books fields are printed
    +    in all caps.</p>
    +    <br>
    +    <b><u>Result:</u></b><br>
    +    <my:findBook var="book"/>
    +    <table border="1">
    +        <thead>
    +        <td><b>Field</b></td>
    +        <td><b>Value</b></td>
    +        <td><b>Capitalized</b></td>
    +    </thead>
    +    <tr>
    +        <td>Title</td>
    +        <td>${book.title}</td>
    +        <td>${my:caps(book.title)}</td>
    +    </tr>
    +    <tr>
    +        <td>Author</td>
    +        <td>${book.author}</td>
    +        <td>${my:caps(book.author)}</td>
    +    </tr>
    +    <tr>
    +        <td>ISBN</td>
    +        <td>${book.isbn}</td>
    +        <td>${my:caps(book.isbn)}</td>
    +    </tr>
    +    </table>
    +  </body>
    +</html>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsp2/simpletag/hello.html b/tomcat/examples/jsp/jsp2/simpletag/hello.html new file mode 100644 index 0000000..20cadf8 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/simpletag/hello.html @@ -0,0 +1,33 @@ + + + +View Source Code + + + + +

    +

    + +

    Source Code for the Hello World Tag Example JSP +

    +

    Source Code for the Hello World SimpleTag Handler +

    + + + diff --git a/tomcat/examples/jsp/jsp2/simpletag/hello.jsp b/tomcat/examples/jsp/jsp2/simpletag/hello.jsp new file mode 100644 index 0000000..d9f22a2 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/simpletag/hello.jsp @@ -0,0 +1,31 @@ +<%-- + 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. +--%> +<%@ taglib prefix="mytag" uri="/WEB-INF/jsp2/jsp2-example-taglib.tld" %> + + + JSP 2.0 Examples - Hello World SimpleTag Handler + + +

    JSP 2.0 Examples - Hello World SimpleTag Handler

    +
    +

    This tag handler simply echos "Hello, World!" It's an example of + a very basic SimpleTag handler with no body.

    +
    + Result: + + + diff --git a/tomcat/examples/jsp/jsp2/simpletag/hello.jsp.html b/tomcat/examples/jsp/jsp2/simpletag/hello.jsp.html new file mode 100644 index 0000000..76f3973 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/simpletag/hello.jsp.html @@ -0,0 +1,32 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<%@ taglib prefix="mytag" uri="/WEB-INF/jsp2/jsp2-example-taglib.tld" %>
    +<html>
    +  <head>
    +    <title>JSP 2.0 Examples - Hello World SimpleTag Handler</title>
    +  </head>
    +  <body>
    +    <h1>JSP 2.0 Examples - Hello World SimpleTag Handler</h1>
    +    <hr>
    +    <p>This tag handler simply echos "Hello, World!"  It's an example of
    +    a very basic SimpleTag handler with no body.</p>
    +    <br>
    +    <b><u>Result:</u></b>
    +    <mytag:helloWorld/>
    +  </body>
    +</html>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsp2/simpletag/repeat.html b/tomcat/examples/jsp/jsp2/simpletag/repeat.html new file mode 100644 index 0000000..a56bfcd --- /dev/null +++ b/tomcat/examples/jsp/jsp2/simpletag/repeat.html @@ -0,0 +1,33 @@ + + + +View Source Code + + + + +

    +

    + +

    Source Code for the Repeat Tag Example JSP +

    +

    Source Code for the Repeat SimpleTag Handler +

    + + + diff --git a/tomcat/examples/jsp/jsp2/simpletag/repeat.jsp b/tomcat/examples/jsp/jsp2/simpletag/repeat.jsp new file mode 100644 index 0000000..b12d0a9 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/simpletag/repeat.jsp @@ -0,0 +1,39 @@ +<%-- + 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. +--%> +<%@ taglib prefix="mytag" uri="/WEB-INF/jsp2/jsp2-example-taglib.tld" %> + + + JSP 2.0 Examples - Repeat SimpleTag Handler + + +

    JSP 2.0 Examples - Repeat SimpleTag Handler

    +
    +

    This tag handler accepts a "num" parameter and repeats the body of the + tag "num" times. It's a simple example, but the implementation of + such a tag in JSP 2.0 is substantially simpler than the equivalent + JSP 1.2-style classic tag handler.

    +

    The body of the tag is encapsulated in a "JSP Fragment" and passed + to the tag handler, which then executes it five times, inside a + for loop. The tag handler passes in the current invocation in a + scoped variable called count, which can be accessed using the EL.

    +
    + Result:
    + + Invocation ${count} of 5
    +
    + + diff --git a/tomcat/examples/jsp/jsp2/simpletag/repeat.jsp.html b/tomcat/examples/jsp/jsp2/simpletag/repeat.jsp.html new file mode 100644 index 0000000..bd40cab --- /dev/null +++ b/tomcat/examples/jsp/jsp2/simpletag/repeat.jsp.html @@ -0,0 +1,40 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<%@ taglib prefix="mytag" uri="/WEB-INF/jsp2/jsp2-example-taglib.tld" %>
    +<html>
    +  <head>
    +    <title>JSP 2.0 Examples - Repeat SimpleTag Handler</title>
    +  </head>
    +  <body>
    +    <h1>JSP 2.0 Examples - Repeat SimpleTag Handler</h1>
    +    <hr>
    +    <p>This tag handler accepts a "num" parameter and repeats the body of the
    +    tag "num" times.  It's a simple example, but the implementation of
    +    such a tag in JSP 2.0 is substantially simpler than the equivalent
    +    JSP 1.2-style classic tag handler.</p>
    +    <p>The body of the tag is encapsulated in a "JSP Fragment" and passed
    +    to the tag handler, which then executes it five times, inside a
    +    for loop.  The tag handler passes in the current invocation in a
    +    scoped variable called count, which can be accessed using the EL.</p>
    +    <br>
    +    <b><u>Result:</u></b><br>
    +    <mytag:repeat num="5">
    +      Invocation ${count} of 5<br>
    +    </mytag:repeat>
    +  </body>
    +</html>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsp2/tagfiles/displayProducts.tag.html b/tomcat/examples/jsp/jsp2/tagfiles/displayProducts.tag.html new file mode 100644 index 0000000..dd488f2 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/tagfiles/displayProducts.tag.html @@ -0,0 +1,56 @@ +Source Code
    <!--
    + 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.
    +-->
    +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    +<%@ attribute name="normalPrice" fragment="true" %>
    +<%@ attribute name="onSale" fragment="true" %>
    +<%@ variable name-given="name" %>
    +<%@ variable name-given="price" %>
    +<%@ variable name-given="origPrice" %>
    +<%@ variable name-given="salePrice" %>
    +
    +<table border="1">
    +  <tr>
    +    <td>
    +      <c:set var="name" value="Hand-held Color PDA"/>
    +      <c:set var="price" value="$298.86"/>
    +      <jsp:invoke fragment="normalPrice"/>
    +    </td>
    +    <td>
    +      <c:set var="name" value="4-Pack 150 Watt Light Bulbs"/>
    +      <c:set var="origPrice" value="$2.98"/>
    +      <c:set var="salePrice" value="$2.32"/>
    +      <jsp:invoke fragment="onSale"/>
    +    </td>
    +    <td>
    +      <c:set var="name" value="Digital Cellular Phone"/>
    +      <c:set var="price" value="$68.74"/>
    +      <jsp:invoke fragment="normalPrice"/>
    +    </td>
    +    <td>
    +      <c:set var="name" value="Baby Grand Piano"/>
    +      <c:set var="price" value="$10,800.00"/>
    +      <jsp:invoke fragment="normalPrice"/>
    +    </td>
    +    <td>
    +      <c:set var="name" value="Luxury Car w/ Leather Seats"/>
    +      <c:set var="origPrice" value="$23,980.00"/>
    +      <c:set var="salePrice" value="$21,070.00"/>
    +      <jsp:invoke fragment="onSale"/>
    +    </td>
    +  </tr>
    +</table>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsp2/tagfiles/hello.html b/tomcat/examples/jsp/jsp2/tagfiles/hello.html new file mode 100644 index 0000000..f29a379 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/tagfiles/hello.html @@ -0,0 +1,33 @@ + + + +View Source Code + + + + +

    +

    + +

    Source Code for hello.jsp +

    +

    Source Code for helloWorld.tag +

    + + + diff --git a/tomcat/examples/jsp/jsp2/tagfiles/hello.jsp b/tomcat/examples/jsp/jsp2/tagfiles/hello.jsp new file mode 100644 index 0000000..9b260f5 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/tagfiles/hello.jsp @@ -0,0 +1,35 @@ +<%-- + 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. +--%> +<%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %> + + + JSP 2.0 Examples - Hello World Using a Tag File + + +

    JSP 2.0 Examples - Hello World Using a Tag File

    +
    +

    This JSP page invokes a custom tag that simply echos "Hello, World!" + The custom tag is generated from a tag file in the /WEB-INF/tags + directory.

    +

    Notice that we did not need to write a TLD for this tag. We just + created /WEB-INF/tags/helloWorld.tag, imported it using the taglib + directive, and used it!

    +
    + Result: + + + diff --git a/tomcat/examples/jsp/jsp2/tagfiles/hello.jsp.html b/tomcat/examples/jsp/jsp2/tagfiles/hello.jsp.html new file mode 100644 index 0000000..b431f30 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/tagfiles/hello.jsp.html @@ -0,0 +1,36 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %>
    +<html>
    +  <head>
    +    <title>JSP 2.0 Examples - Hello World Using a Tag File</title>
    +  </head>
    +  <body>
    +    <h1>JSP 2.0 Examples - Hello World Using a Tag File</h1>
    +    <hr>
    +    <p>This JSP page invokes a custom tag that simply echos "Hello, World!"
    +    The custom tag is generated from a tag file in the /WEB-INF/tags
    +    directory.</p>
    +    <p>Notice that we did not need to write a TLD for this tag.  We just
    +    created /WEB-INF/tags/helloWorld.tag, imported it using the taglib
    +    directive, and used it!</p>
    +    <br>
    +    <b><u>Result:</u></b>
    +    <tags:helloWorld/>
    +  </body>
    +</html>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsp2/tagfiles/helloWorld.tag.html b/tomcat/examples/jsp/jsp2/tagfiles/helloWorld.tag.html new file mode 100644 index 0000000..f29726f --- /dev/null +++ b/tomcat/examples/jsp/jsp2/tagfiles/helloWorld.tag.html @@ -0,0 +1,18 @@ +Source Code
    <!--
    + 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.
    +-->
    +Hello, world!
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsp2/tagfiles/panel.html b/tomcat/examples/jsp/jsp2/tagfiles/panel.html new file mode 100644 index 0000000..1f03b9c --- /dev/null +++ b/tomcat/examples/jsp/jsp2/tagfiles/panel.html @@ -0,0 +1,33 @@ + + + +View Source Code + + + + +

    +

    + +

    Source Code for panel.jsp +

    +

    Source Code for panel.tag +

    + + + diff --git a/tomcat/examples/jsp/jsp2/tagfiles/panel.jsp b/tomcat/examples/jsp/jsp2/tagfiles/panel.jsp new file mode 100644 index 0000000..d963877 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/tagfiles/panel.jsp @@ -0,0 +1,58 @@ +<%-- + 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. +--%> +<%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %> + + + JSP 2.0 Examples - Panels using Tag Files + + +

    JSP 2.0 Examples - Panels using Tag Files

    +
    +

    This JSP page invokes a custom tag that draws a + panel around the contents of the tag body. Normally, such a tag + implementation would require a Java class with many println() statements, + outputting HTML. Instead, we can use a .tag file as a template, + and we don't need to write a single line of Java or even a TLD!

    +
    + + + + + + +
    + + First panel.
    +
    +
    + + Second panel.
    + Second panel.
    + Second panel.
    + Second panel.
    +
    +
    + + Third panel.
    + + A panel in a panel. + + Third panel.
    +
    +
    + + diff --git a/tomcat/examples/jsp/jsp2/tagfiles/panel.jsp.html b/tomcat/examples/jsp/jsp2/tagfiles/panel.jsp.html new file mode 100644 index 0000000..584393d --- /dev/null +++ b/tomcat/examples/jsp/jsp2/tagfiles/panel.jsp.html @@ -0,0 +1,59 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %>
    +<html>
    +  <head>
    +    <title>JSP 2.0 Examples - Panels using Tag Files</title>
    +  </head>
    +  <body>
    +    <h1>JSP 2.0 Examples - Panels using Tag Files</h1>
    +    <hr>
    +    <p>This JSP page invokes a custom tag that draws a
    +    panel around the contents of the tag body.  Normally, such a tag
    +    implementation would require a Java class with many println() statements,
    +    outputting HTML.  Instead, we can use a .tag file as a template,
    +    and we don't need to write a single line of Java or even a TLD!</p>
    +    <hr>
    +    <table border="0">
    +      <tr valign="top">
    +        <td>
    +          <tags:panel color="#ff8080" bgcolor="#ffc0c0" title="Panel 1">
    +            First panel.<br/>
    +          </tags:panel>
    +        </td>
    +        <td>
    +          <tags:panel color="#80ff80" bgcolor="#c0ffc0" title="Panel 2">
    +            Second panel.<br/>
    +            Second panel.<br/>
    +            Second panel.<br/>
    +            Second panel.<br/>
    +          </tags:panel>
    +        </td>
    +        <td>
    +          <tags:panel color="#8080ff" bgcolor="#c0c0ff" title="Panel 3">
    +            Third panel.<br/>
    +            <tags:panel color="#ff80ff" bgcolor="#ffc0ff" title="Inner">
    +              A panel in a panel.
    +            </tags:panel>
    +            Third panel.<br/>
    +          </tags:panel>
    +        </td>
    +      </tr>
    +    </table>
    +  </body>
    +</html>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsp2/tagfiles/panel.tag.html b/tomcat/examples/jsp/jsp2/tagfiles/panel.tag.html new file mode 100644 index 0000000..aec91c3 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/tagfiles/panel.tag.html @@ -0,0 +1,30 @@ +Source Code
    <!--
    + 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.
    +-->
    +<%@ attribute name="color" %>
    +<%@ attribute name="bgcolor" %>
    +<%@ attribute name="title" %>
    +<table border="1" bgcolor="${color}">
    +  <tr>
    +    <td><b>${title}</b></td>
    +  </tr>
    +  <tr>
    +    <td bgcolor="${bgcolor}">
    +      <jsp:doBody/>
    +    </td>
    +  </tr>
    +</table>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsp2/tagfiles/products.html b/tomcat/examples/jsp/jsp2/tagfiles/products.html new file mode 100644 index 0000000..72ae49f --- /dev/null +++ b/tomcat/examples/jsp/jsp2/tagfiles/products.html @@ -0,0 +1,33 @@ + + + +View Source Code + + + + +

    +

    + +

    Source Code for products.jsp +

    +

    Source Code for displayProducts.tag +

    + + + diff --git a/tomcat/examples/jsp/jsp2/tagfiles/products.jsp b/tomcat/examples/jsp/jsp2/tagfiles/products.jsp new file mode 100644 index 0000000..7f32ffb --- /dev/null +++ b/tomcat/examples/jsp/jsp2/tagfiles/products.jsp @@ -0,0 +1,54 @@ +<%-- + 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. +--%> +<%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %> + + + JSP 2.0 Examples - Display Products Tag File + + +

    JSP 2.0 Examples - Display Products Tag File

    +
    +

    This JSP page invokes a tag file that displays a listing of + products. The custom tag accepts two fragments that enable + customization of appearance. One for when the product is on sale + and one for normal price.

    +

    The tag is invoked twice, using different styles

    +
    +

    Products

    + + + Item: ${name}
    + Price: ${price} +
    + + Item: ${name}
    + Was: ${origPrice}
    + Now: ${salePrice} +
    +
    +
    +

    Products (Same tag, alternate style)

    + + + ${name} @ ${price} ea. + + + ${name} @ ${salePrice} ea. (was: ${origPrice}) + + + + diff --git a/tomcat/examples/jsp/jsp2/tagfiles/products.jsp.html b/tomcat/examples/jsp/jsp2/tagfiles/products.jsp.html new file mode 100644 index 0000000..6d6fc10 --- /dev/null +++ b/tomcat/examples/jsp/jsp2/tagfiles/products.jsp.html @@ -0,0 +1,55 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %>
    +<html>
    +  <head>
    +    <title>JSP 2.0 Examples - Display Products Tag File</title>
    +  </head>
    +  <body>
    +    <h1>JSP 2.0 Examples - Display Products Tag File</h1>
    +    <hr>
    +    <p>This JSP page invokes a tag file that displays a listing of
    +    products.  The custom tag accepts two fragments that enable
    +    customization of appearance.  One for when the product is on sale
    +    and one for normal price.</p>
    +    <p>The tag is invoked twice, using different styles</p>
    +    <hr>
    +    <h2>Products</h2>
    +    <tags:displayProducts>
    +      <jsp:attribute name="normalPrice">
    +        Item: ${name}<br/>
    +        Price: ${price}
    +      </jsp:attribute>
    +      <jsp:attribute name="onSale">
    +        Item: ${name}<br/>
    +        <font color="red"><strike>Was: ${origPrice}</strike></font><br/>
    +        <b>Now: ${salePrice}</b>
    +      </jsp:attribute>
    +    </tags:displayProducts>
    +    <hr>
    +    <h2>Products (Same tag, alternate style)</h2>
    +    <tags:displayProducts>
    +      <jsp:attribute name="normalPrice">
    +        <b>${name}</b> @ ${price} ea.
    +      </jsp:attribute>
    +      <jsp:attribute name="onSale">
    +        <b>${name}</b> @ ${salePrice} ea. (was: ${origPrice})
    +      </jsp:attribute>
    +    </tags:displayProducts>
    +  </body>
    +</html>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsptoserv/ServletToJsp.java.html b/tomcat/examples/jsp/jsptoserv/ServletToJsp.java.html new file mode 100644 index 0000000..0a38037 --- /dev/null +++ b/tomcat/examples/jsp/jsptoserv/ServletToJsp.java.html @@ -0,0 +1,40 @@ +Source Code
    /*
    +* 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.
    +*/
    +
    +import javax.servlet.http.HttpServlet;
    +import javax.servlet.http.HttpServletRequest;
    +import javax.servlet.http.HttpServletResponse;
    +
    +public class ServletToJsp extends HttpServlet {
    +
    +    private static final long serialVersionUID = 1L;
    +
    +    @Override
    +    public void doGet (HttpServletRequest request,
    +            HttpServletResponse response) {
    +
    +       try {
    +           // Set the attribute and Forward to hello.jsp
    +           request.setAttribute ("servletName", "servletToJsp");
    +           getServletConfig().getServletContext().getRequestDispatcher(
    +                   "/jsp/jsptoserv/hello.jsp").forward(request, response);
    +       } catch (Exception ex) {
    +           ex.printStackTrace ();
    +       }
    +    }
    +}
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsptoserv/hello.jsp b/tomcat/examples/jsp/jsptoserv/hello.jsp new file mode 100644 index 0000000..8b2a43f --- /dev/null +++ b/tomcat/examples/jsp/jsptoserv/hello.jsp @@ -0,0 +1,26 @@ +<%-- + 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. +--%> + + + +

    +I have been invoked by +<% out.print (request.getAttribute("servletName").toString()); %> +Servlet. +

    + + \ No newline at end of file diff --git a/tomcat/examples/jsp/jsptoserv/hello.jsp.html b/tomcat/examples/jsp/jsptoserv/hello.jsp.html new file mode 100644 index 0000000..6ed7176 --- /dev/null +++ b/tomcat/examples/jsp/jsptoserv/hello.jsp.html @@ -0,0 +1,27 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<html>
    +<body bgcolor="white">
    +
    +<h1>
    +I have been invoked by
    +<% out.print (request.getAttribute("servletName").toString()); %>
    +Servlet.
    +</h1>
    +
    +</html>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsptoserv/jsptoservlet.jsp b/tomcat/examples/jsp/jsptoserv/jsptoservlet.jsp new file mode 100644 index 0000000..db68a6f --- /dev/null +++ b/tomcat/examples/jsp/jsptoserv/jsptoservlet.jsp @@ -0,0 +1,23 @@ +<%-- + 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. +--%> + + + + + + + \ No newline at end of file diff --git a/tomcat/examples/jsp/jsptoserv/jsptoservlet.jsp.html b/tomcat/examples/jsp/jsptoserv/jsptoservlet.jsp.html new file mode 100644 index 0000000..a5dc22c --- /dev/null +++ b/tomcat/examples/jsp/jsptoserv/jsptoservlet.jsp.html @@ -0,0 +1,24 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<html>
    +<body bgcolor="white">
    +
    +<!-- Forward to a servlet -->
    +<jsp:forward page="/servletToJsp" />
    +
    +</html>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/jsptoserv/jts.html b/tomcat/examples/jsp/jsptoserv/jts.html new file mode 100644 index 0000000..a4e1679 --- /dev/null +++ b/tomcat/examples/jsp/jsptoserv/jts.html @@ -0,0 +1,36 @@ + + + + + +Untitled Document + + + + +

    Execute
    + Return

    + +

    Source Code for JSP calling servlet

    + +

    Source Code for Servlet calling JSP

    + + + diff --git a/tomcat/examples/jsp/num/numguess.html b/tomcat/examples/jsp/num/numguess.html new file mode 100644 index 0000000..1c5a484 --- /dev/null +++ b/tomcat/examples/jsp/num/numguess.html @@ -0,0 +1,34 @@ + + + +Untitled Document + + + + +

    + +

    Source Code for Numguess Example +

    + + + diff --git a/tomcat/examples/jsp/num/numguess.jsp b/tomcat/examples/jsp/num/numguess.jsp new file mode 100644 index 0000000..d9c61b9 --- /dev/null +++ b/tomcat/examples/jsp/num/numguess.jsp @@ -0,0 +1,69 @@ +<%-- + 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. + + Number Guess Game + Written by Jason Hunter, CTO, K&A Software + http://www.servlets.com +--%> + +<%@ page import = "num.NumberGuessBean" %> + + + + + +Number Guess + + + +<% if (numguess.getSuccess()) { %> + + Congratulations! You got it. + And after just <%= numguess.getNumGuesses() %> tries.

    + + <% numguess.reset(); %> + + Care to try again? + +<% } else if (numguess.getNumGuesses() == 0) { %> + + Welcome to the Number Guess game.

    + + I'm thinking of a number between 1 and 100.

    + +

    + What's your guess? + +
    + +<% } else { %> + + Good guess, but nope. Try <%= numguess.getHint() %>. + + You have made <%= numguess.getNumGuesses() %> guesses.

    + + I'm thinking of a number between 1 and 100.

    + +

    + What's your guess? + +
    + +<% } %> + +
    + + diff --git a/tomcat/examples/jsp/num/numguess.jsp.html b/tomcat/examples/jsp/num/numguess.jsp.html new file mode 100644 index 0000000..e764041 --- /dev/null +++ b/tomcat/examples/jsp/num/numguess.jsp.html @@ -0,0 +1,70 @@ +Source Code
    <%--
    + 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.
    +
    +  Number Guess Game
    +  Written by Jason Hunter, CTO, K&A Software
    +  http://www.servlets.com
    +--%>
    +
    +<%@ page import = "num.NumberGuessBean" %>
    +
    +<jsp:useBean id="numguess" class="num.NumberGuessBean" scope="session"/>
    +<jsp:setProperty name="numguess" property="*"/>
    +
    +<html>
    +<head><title>Number Guess</title></head>
    +<body bgcolor="white">
    +<font size=4>
    +
    +<% if (numguess.getSuccess()) { %>
    +
    +  Congratulations!  You got it.
    +  And after just <%= numguess.getNumGuesses() %> tries.<p>
    +
    +  <% numguess.reset(); %>
    +
    +  Care to <a href="numguess.jsp">try again</a>?
    +
    +<% } else if (numguess.getNumGuesses() == 0) { %>
    +
    +  Welcome to the Number Guess game.<p>
    +
    +  I'm thinking of a number between 1 and 100.<p>
    +
    +  <form method=get>
    +  What's your guess? <input type=text name=guess>
    +  <input type=submit value="Submit">
    +  </form>
    +
    +<% } else { %>
    +
    +  Good guess, but nope.  Try <b><%= numguess.getHint() %></b>.
    +
    +  You have made <%= numguess.getNumGuesses() %> guesses.<p>
    +
    +  I'm thinking of a number between 1 and 100.<p>
    +
    +  <form method=get>
    +  What's your guess? <input type=text name=guess>
    +  <input type=submit value="Submit">
    +  </form>
    +
    +<% } %>
    +
    +</font>
    +</body>
    +</html>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/plugin/applet/Clock2.class b/tomcat/examples/jsp/plugin/applet/Clock2.class new file mode 100644 index 0000000..2fd4a4d Binary files /dev/null and b/tomcat/examples/jsp/plugin/applet/Clock2.class differ diff --git a/tomcat/examples/jsp/plugin/applet/Clock2.java b/tomcat/examples/jsp/plugin/applet/Clock2.java new file mode 100644 index 0000000..4ea737a --- /dev/null +++ b/tomcat/examples/jsp/plugin/applet/Clock2.java @@ -0,0 +1,230 @@ +/* +* 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. +*/ + +import java.applet.Applet; +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; + +/** + * Time! + * + * @author Rachel Gollub + */ + +public class Clock2 extends Applet implements Runnable { + private static final long serialVersionUID = 1L; + Thread timer; // The thread that displays clock + int lastxs, lastys, lastxm, + lastym, lastxh, lastyh; // Dimensions used to draw hands + SimpleDateFormat formatter; // Formats the date displayed + String lastdate; // String to hold date displayed + Font clockFaceFont; // Font for number display on clock + Date currentDate; // Used to get date to display + Color handColor; // Color of main hands and dial + Color numberColor; // Color of second hand and numbers + + @Override + public void init() { + lastxs = lastys = lastxm = lastym = lastxh = lastyh = 0; + formatter = new SimpleDateFormat ("EEE MMM dd hh:mm:ss yyyy", Locale.getDefault()); + currentDate = new Date(); + lastdate = formatter.format(currentDate); + clockFaceFont = new Font("Serif", Font.PLAIN, 14); + handColor = Color.blue; + numberColor = Color.darkGray; + + try { + setBackground(new Color(Integer.parseInt(getParameter("bgcolor"),16))); + } catch (Exception e) { + // Ignored + } + try { + handColor = new Color(Integer.parseInt(getParameter("fgcolor1"),16)); + } catch (Exception e) { + // Ignored + } + try { + numberColor = new Color(Integer.parseInt(getParameter("fgcolor2"),16)); + } catch (Exception e) { + // Ignored + } + resize(300,300); // Set clock window size + } + + // Plotpoints allows calculation to only cover 45 degrees of the circle, + // and then mirror + public void plotpoints(int x0, int y0, int x, int y, Graphics g) { + g.drawLine(x0+x,y0+y,x0+x,y0+y); + g.drawLine(x0+y,y0+x,x0+y,y0+x); + g.drawLine(x0+y,y0-x,x0+y,y0-x); + g.drawLine(x0+x,y0-y,x0+x,y0-y); + g.drawLine(x0-x,y0-y,x0-x,y0-y); + g.drawLine(x0-y,y0-x,x0-y,y0-x); + g.drawLine(x0-y,y0+x,x0-y,y0+x); + g.drawLine(x0-x,y0+y,x0-x,y0+y); + } + + // Circle is just Bresenham's algorithm for a scan converted circle + public void circle(int x0, int y0, int r, Graphics g) { + int x,y; + float d; + x=0; + y=r; + d=5/4-r; + plotpoints(x0,y0,x,y,g); + + while (y>x){ + if (d<0) { + d=d+2*x+3; + x++; + } + else { + d=d+2*(x-y)+5; + x++; + y--; + } + plotpoints(x0,y0,x,y,g); + } + } + + // Paint is the main part of the program + @Override + public void paint(Graphics g) { + int xh, yh, xm, ym, xs, ys, s = 0, m = 10, h = 10, xcenter, ycenter; + String today; + + currentDate = new Date(); + SimpleDateFormat formatter = new SimpleDateFormat("s",Locale.getDefault()); + try { + s = Integer.parseInt(formatter.format(currentDate)); + } catch (NumberFormatException n) { + s = 0; + } + formatter.applyPattern("m"); + try { + m = Integer.parseInt(formatter.format(currentDate)); + } catch (NumberFormatException n) { + m = 10; + } + formatter.applyPattern("h"); + try { + h = Integer.parseInt(formatter.format(currentDate)); + } catch (NumberFormatException n) { + h = 10; + } + formatter.applyPattern("EEE MMM dd HH:mm:ss yyyy"); + today = formatter.format(currentDate); + xcenter=80; + ycenter=55; + + // a= s* pi/2 - pi/2 (to switch 0,0 from 3:00 to 12:00) + // x = r(cos a) + xcenter, y = r(sin a) + ycenter + + xs = (int)(Math.cos(s * 3.14f/30 - 3.14f/2) * 45 + xcenter); + ys = (int)(Math.sin(s * 3.14f/30 - 3.14f/2) * 45 + ycenter); + xm = (int)(Math.cos(m * 3.14f/30 - 3.14f/2) * 40 + xcenter); + ym = (int)(Math.sin(m * 3.14f/30 - 3.14f/2) * 40 + ycenter); + xh = (int)(Math.cos((h*30 + m/2) * 3.14f/180 - 3.14f/2) * 30 + xcenter); + yh = (int)(Math.sin((h*30 + m/2) * 3.14f/180 - 3.14f/2) * 30 + ycenter); + + // Draw the circle and numbers + + g.setFont(clockFaceFont); + g.setColor(handColor); + circle(xcenter,ycenter,50,g); + g.setColor(numberColor); + g.drawString("9",xcenter-45,ycenter+3); + g.drawString("3",xcenter+40,ycenter+3); + g.drawString("12",xcenter-5,ycenter-37); + g.drawString("6",xcenter-3,ycenter+45); + + // Erase if necessary, and redraw + + g.setColor(getBackground()); + if (xs != lastxs || ys != lastys) { + g.drawLine(xcenter, ycenter, lastxs, lastys); + g.drawString(lastdate, 5, 125); + } + if (xm != lastxm || ym != lastym) { + g.drawLine(xcenter, ycenter-1, lastxm, lastym); + g.drawLine(xcenter-1, ycenter, lastxm, lastym); } + if (xh != lastxh || yh != lastyh) { + g.drawLine(xcenter, ycenter-1, lastxh, lastyh); + g.drawLine(xcenter-1, ycenter, lastxh, lastyh); } + g.setColor(numberColor); + g.drawString("", 5, 125); + g.drawString(today, 5, 125); + g.drawLine(xcenter, ycenter, xs, ys); + g.setColor(handColor); + g.drawLine(xcenter, ycenter-1, xm, ym); + g.drawLine(xcenter-1, ycenter, xm, ym); + g.drawLine(xcenter, ycenter-1, xh, yh); + g.drawLine(xcenter-1, ycenter, xh, yh); + lastxs=xs; lastys=ys; + lastxm=xm; lastym=ym; + lastxh=xh; lastyh=yh; + lastdate = today; + currentDate=null; + } + + @Override + public void start() { + timer = new Thread(this); + timer.start(); + } + + @Override + public void stop() { + timer = null; + } + + @Override + public void run() { + Thread me = Thread.currentThread(); + while (timer == me) { + try { + Thread.sleep(100); + } catch (InterruptedException e) { + } + repaint(); + } + } + + @Override + public void update(Graphics g) { + paint(g); + } + + @Override + public String getAppletInfo() { + return "Title: A Clock \nAuthor: Rachel Gollub, 1995 \nAn analog clock."; + } + + @Override + public String[][] getParameterInfo() { + String[][] info = { + {"bgcolor", "hexadecimal RGB number", "The background color. Default is the color of your browser."}, + {"fgcolor1", "hexadecimal RGB number", "The color of the hands and dial. Default is blue."}, + {"fgcolor2", "hexadecimal RGB number", "The color of the seconds hand and numbers. Default is dark gray."} + }; + return info; + } +} diff --git a/tomcat/examples/jsp/plugin/plugin.html b/tomcat/examples/jsp/plugin/plugin.html new file mode 100644 index 0000000..27bc51b --- /dev/null +++ b/tomcat/examples/jsp/plugin/plugin.html @@ -0,0 +1,30 @@ + + + +Untitled Document + + + + +

    + +

    Source Code for Plugin Example +

    + + + diff --git a/tomcat/examples/jsp/plugin/plugin.jsp b/tomcat/examples/jsp/plugin/plugin.jsp new file mode 100644 index 0000000..a07dda3 --- /dev/null +++ b/tomcat/examples/jsp/plugin/plugin.jsp @@ -0,0 +1,34 @@ +<%-- + 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. +--%> + + Plugin example + +

    Current time is :

    + + + Plugin tag OBJECT or EMBED not supported by browser. + + +

    +

    + +The above applet is loaded using the Java Plugin from a jsp page using the +plugin tag. + +

    + + diff --git a/tomcat/examples/jsp/plugin/plugin.jsp.html b/tomcat/examples/jsp/plugin/plugin.jsp.html new file mode 100644 index 0000000..710bda7 --- /dev/null +++ b/tomcat/examples/jsp/plugin/plugin.jsp.html @@ -0,0 +1,35 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<html>
    +<title> Plugin example </title>
    +<body bgcolor="white">
    +<h3> Current time is : </h3>
    +<jsp:plugin type="applet" code="Clock2.class" codebase="applet" jreversion="1.2" width="160" height="150" >
    +    <jsp:fallback>
    +        Plugin tag OBJECT or EMBED not supported by browser.
    +    </jsp:fallback>
    +</jsp:plugin>
    +<p>
    +<h4>
    +<font color=red>
    +The above applet is loaded using the Java Plugin from a jsp page using the
    +plugin tag.
    +</font>
    +</h4>
    +</body>
    +</html>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/security/protected/error.jsp b/tomcat/examples/jsp/security/protected/error.jsp new file mode 100644 index 0000000..3ef5743 --- /dev/null +++ b/tomcat/examples/jsp/security/protected/error.jsp @@ -0,0 +1,25 @@ +<%-- + 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. +--%> + + +Error Page For Examples + + +Invalid username and/or password, please try +again. + + diff --git a/tomcat/examples/jsp/security/protected/error.jsp.html b/tomcat/examples/jsp/security/protected/error.jsp.html new file mode 100644 index 0000000..50ec895 --- /dev/null +++ b/tomcat/examples/jsp/security/protected/error.jsp.html @@ -0,0 +1,26 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<html>
    +<head>
    +<title>Error Page For Examples</title>
    +</head>
    +<body bgcolor="white">
    +Invalid username and/or password, please try
    +<a href='<%= response.encodeURL("index.jsp") %>'>again</a>.
    +</body>
    +</html>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/security/protected/index.jsp b/tomcat/examples/jsp/security/protected/index.jsp new file mode 100644 index 0000000..eacf27a --- /dev/null +++ b/tomcat/examples/jsp/security/protected/index.jsp @@ -0,0 +1,82 @@ +<%-- + 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. +--%> +<% + if (request.getParameter("logoff") != null) { + session.invalidate(); + response.sendRedirect("index.jsp"); + return; + } +%> + + +Protected Page for Examples + + + +You are logged in as remote user +<%= util.HTMLFilter.filter(request.getRemoteUser()) %> +in session <%= session.getId() %>

    + +<% + if (request.getUserPrincipal() != null) { +%> + Your user principal name is + <%= util.HTMLFilter.filter(request.getUserPrincipal().getName()) %> +

    +<% + } else { +%> + No user principal could be identified.

    +<% + } +%> + +<% + String role = request.getParameter("role"); + if (role == null) + role = ""; + if (role.length() > 0) { + if (request.isUserInRole(role)) { +%> + You have been granted role + <%= util.HTMLFilter.filter(role) %>

    +<% + } else { +%> + You have not been granted role + <%= util.HTMLFilter.filter(role) %>

    +<% + } + } +%> + +To check whether your user name has been granted a particular role, +enter it here: +
    + + +
    +

    + +If you have configured this application for form-based authentication, you can +log off by clicking +here. +This should cause you to be returned to the login page after the redirect +that is performed. + + + diff --git a/tomcat/examples/jsp/security/protected/index.jsp.html b/tomcat/examples/jsp/security/protected/index.jsp.html new file mode 100644 index 0000000..cadf810 --- /dev/null +++ b/tomcat/examples/jsp/security/protected/index.jsp.html @@ -0,0 +1,83 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<%
    +  if (request.getParameter("logoff") != null) {
    +    session.invalidate();
    +    response.sendRedirect("index.jsp");
    +    return;
    +  }
    +%>
    +<html>
    +<head>
    +<title>Protected Page for Examples</title>
    +</head>
    +<body bgcolor="white">
    +
    +You are logged in as remote user
    +<b><%= util.HTMLFilter.filter(request.getRemoteUser()) %></b>
    +in session <b><%= session.getId() %></b><br><br>
    +
    +<%
    +  if (request.getUserPrincipal() != null) {
    +%>
    +    Your user principal name is
    +    <b><%= util.HTMLFilter.filter(request.getUserPrincipal().getName()) %></b>
    +    <br><br>
    +<%
    +  } else {
    +%>
    +    No user principal could be identified.<br><br>
    +<%
    +  }
    +%>
    +
    +<%
    +  String role = request.getParameter("role");
    +  if (role == null)
    +    role = "";
    +  if (role.length() > 0) {
    +    if (request.isUserInRole(role)) {
    +%>
    +      You have been granted role
    +      <b><%= util.HTMLFilter.filter(role) %></b><br><br>
    +<%
    +    } else {
    +%>
    +      You have <i>not</i> been granted role
    +      <b><%= util.HTMLFilter.filter(role) %></b><br><br>
    +<%
    +    }
    +  }
    +%>
    +
    +To check whether your user name has been granted a particular role,
    +enter it here:
    +<form method="GET" action='<%= response.encodeURL("index.jsp") %>'>
    +<input type="text" name="role" value="<%= util.HTMLFilter.filter(role) %>">
    +<input type="submit" >
    +</form>
    +<br><br>
    +
    +If you have configured this application for form-based authentication, you can
    +log off by clicking
    +<a href='<%= response.encodeURL("index.jsp?logoff=true") %>'>here</a>.
    +This should cause you to be returned to the login page after the redirect
    +that is performed.
    +
    +</body>
    +</html>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/security/protected/login.jsp b/tomcat/examples/jsp/security/protected/login.jsp new file mode 100644 index 0000000..e11a898 --- /dev/null +++ b/tomcat/examples/jsp/security/protected/login.jsp @@ -0,0 +1,38 @@ +<%-- + 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. +--%> + + +Login Page for Examples + +
    + + + + + + + + + + + + + +
    Username:
    Password:
    +
    + + diff --git a/tomcat/examples/jsp/security/protected/login.jsp.html b/tomcat/examples/jsp/security/protected/login.jsp.html new file mode 100644 index 0000000..5726e32 --- /dev/null +++ b/tomcat/examples/jsp/security/protected/login.jsp.html @@ -0,0 +1,39 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<html>
    +<head>
    +<title>Login Page for Examples</title>
    +<body bgcolor="white">
    +<form method="POST" action='<%= response.encodeURL("j_security_check") %>' >
    +  <table border="0" cellspacing="5">
    +    <tr>
    +      <th align="right">Username:</th>
    +      <td align="left"><input type="text" name="j_username"></td>
    +    </tr>
    +    <tr>
    +      <th align="right">Password:</th>
    +      <td align="left"><input type="password" name="j_password"></td>
    +    </tr>
    +    <tr>
    +      <td align="right"><input type="submit" value="Log In"></td>
    +      <td align="left"><input type="reset"></td>
    +    </tr>
    +  </table>
    +</form>
    +</body>
    +</html>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/sessions/DummyCart.html b/tomcat/examples/jsp/sessions/DummyCart.html new file mode 100644 index 0000000..d953fa9 --- /dev/null +++ b/tomcat/examples/jsp/sessions/DummyCart.html @@ -0,0 +1,56 @@ + + + + + +sessions.DummyCart Bean Properties + + +

    +sessions.DummyCart Bean Properties +

    +
    +
    +
    public class DummyCart
    extends Object
    + +

    +


    + +

    + + + + + + + + + +
    +Properties Summary
    + +String +DummyCart:items +
    +
    + +Multi +
    +


    + + diff --git a/tomcat/examples/jsp/sessions/carts.html b/tomcat/examples/jsp/sessions/carts.html new file mode 100644 index 0000000..834ee0a --- /dev/null +++ b/tomcat/examples/jsp/sessions/carts.html @@ -0,0 +1,53 @@ + + + + + carts + + + + + +
    +
    +Please enter item to add or remove: +
    +Add Item: + + + + +

    + + + +
    + +
    + + diff --git a/tomcat/examples/jsp/sessions/carts.jsp b/tomcat/examples/jsp/sessions/carts.jsp new file mode 100644 index 0000000..6fba47d --- /dev/null +++ b/tomcat/examples/jsp/sessions/carts.jsp @@ -0,0 +1,43 @@ +<%-- + 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. +--%> + + + + +<% + cart.processRequest(); +%> + + + +
    You have the following items in your cart: +
      +<% + String[] items = cart.getItems(); + for (int i=0; i +
    1. <% out.print(util.HTMLFilter.filter(items[i])); %> +<% + } +%> +
    + +
    + +
    +<%@ include file ="carts.html" %> + diff --git a/tomcat/examples/jsp/sessions/carts.jsp.html b/tomcat/examples/jsp/sessions/carts.jsp.html new file mode 100644 index 0000000..cb2325f --- /dev/null +++ b/tomcat/examples/jsp/sessions/carts.jsp.html @@ -0,0 +1,44 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<html>
    +<jsp:useBean id="cart" scope="session" class="sessions.DummyCart" />
    +
    +<jsp:setProperty name="cart" property="*" />
    +<%
    +    cart.processRequest();
    +%>
    +
    +
    +<FONT size = 5 COLOR="#CC0000">
    +<br> You have the following items in your cart:
    +<ol>
    +<%
    +    String[] items = cart.getItems();
    +    for (int i=0; i<items.length; i++) {
    +%>
    +<li> <% out.print(util.HTMLFilter.filter(items[i])); %>
    +<%
    +    }
    +%>
    +</ol>
    +
    +</FONT>
    +
    +<hr>
    +<%@ include file ="carts.html" %>
    +</html>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/sessions/crt.html b/tomcat/examples/jsp/sessions/crt.html new file mode 100644 index 0000000..11e6eda --- /dev/null +++ b/tomcat/examples/jsp/sessions/crt.html @@ -0,0 +1,34 @@ + + + + +Untitled Document + + + + +

    + +

    Source Code for Cart Example +

    + +

    Property Sheet for DummyCart +

    + + + diff --git a/tomcat/examples/jsp/simpletag/foo.html b/tomcat/examples/jsp/simpletag/foo.html new file mode 100644 index 0000000..e20f840 --- /dev/null +++ b/tomcat/examples/jsp/simpletag/foo.html @@ -0,0 +1,30 @@ + + + +Untitled Document + + + + +

    + +

    Source Code for the Simple Tag Example +

    + + + diff --git a/tomcat/examples/jsp/simpletag/foo.jsp b/tomcat/examples/jsp/simpletag/foo.jsp new file mode 100644 index 0000000..2489146 --- /dev/null +++ b/tomcat/examples/jsp/simpletag/foo.jsp @@ -0,0 +1,38 @@ +<%-- + 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. +--%> + + +<%@ taglib uri="http://tomcat.apache.org/example-taglib" prefix="eg"%> + +Radio stations that rock: + +
      + +
    • <%= member %>
    • +
      +
    + + +Did you see me on the stderr window? + + + +Did you see me on the browser window as well? + + + + diff --git a/tomcat/examples/jsp/simpletag/foo.jsp.html b/tomcat/examples/jsp/simpletag/foo.jsp.html new file mode 100644 index 0000000..02693c8 --- /dev/null +++ b/tomcat/examples/jsp/simpletag/foo.jsp.html @@ -0,0 +1,39 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<html>
    +<body>
    +<%@ taglib uri="http://tomcat.apache.org/example-taglib" prefix="eg"%>
    +
    +Radio stations that rock:
    +
    +<ul>
    +<eg:foo att1="98.5" att2="92.3" att3="107.7">
    +<li><%= member %></li>
    +</eg:foo>
    +</ul>
    +
    +<eg:log>
    +Did you see me on the stderr window?
    +</eg:log>
    +
    +<eg:log toBrowser="true">
    +Did you see me on the browser window as well?
    +</eg:log>
    +
    +</body>
    +</html>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/snp/snoop.html b/tomcat/examples/jsp/snp/snoop.html new file mode 100644 index 0000000..e48355b --- /dev/null +++ b/tomcat/examples/jsp/snp/snoop.html @@ -0,0 +1,31 @@ + + + + +Untitled Document + + + + +

    + +

    Source Code for Request Parameters Example +

    + + + diff --git a/tomcat/examples/jsp/snp/snoop.jsp b/tomcat/examples/jsp/snp/snoop.jsp new file mode 100644 index 0000000..9bb57a8 --- /dev/null +++ b/tomcat/examples/jsp/snp/snoop.jsp @@ -0,0 +1,56 @@ +<%-- + 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. +--%> + + +

    Request Information

    + +JSP Request Method: <%= util.HTMLFilter.filter(request.getMethod()) %> +
    +Request URI: <%= util.HTMLFilter.filter(request.getRequestURI()) %> +
    +Request Protocol: <%= util.HTMLFilter.filter(request.getProtocol()) %> +
    +Servlet path: <%= util.HTMLFilter.filter(request.getServletPath()) %> +
    +Path info: <%= util.HTMLFilter.filter(request.getPathInfo()) %> +
    +Query string: <%= util.HTMLFilter.filter(request.getQueryString()) %> +
    +Content length: <%= request.getContentLength() %> +
    +Content type: <%= util.HTMLFilter.filter(request.getContentType()) %> +
    +Server name: <%= util.HTMLFilter.filter(request.getServerName()) %> +
    +Server port: <%= request.getServerPort() %> +
    +Remote user: <%= util.HTMLFilter.filter(request.getRemoteUser()) %> +
    +Remote address: <%= util.HTMLFilter.filter(request.getRemoteAddr()) %> +
    +Remote host: <%= util.HTMLFilter.filter(request.getRemoteHost()) %> +
    +Authorization scheme: <%= util.HTMLFilter.filter(request.getAuthType()) %> +
    +Locale: <%= request.getLocale() %> +
    +The browser you are using is +<%= util.HTMLFilter.filter(request.getHeader("User-Agent")) %> +
    +
    + + diff --git a/tomcat/examples/jsp/snp/snoop.jsp.html b/tomcat/examples/jsp/snp/snoop.jsp.html new file mode 100644 index 0000000..00bf89b --- /dev/null +++ b/tomcat/examples/jsp/snp/snoop.jsp.html @@ -0,0 +1,57 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<html>
    +<body bgcolor="white">
    +<h1> Request Information </h1>
    +<font size="4">
    +JSP Request Method: <%= util.HTMLFilter.filter(request.getMethod()) %>
    +<br>
    +Request URI: <%= util.HTMLFilter.filter(request.getRequestURI()) %>
    +<br>
    +Request Protocol: <%= util.HTMLFilter.filter(request.getProtocol()) %>
    +<br>
    +Servlet path: <%= util.HTMLFilter.filter(request.getServletPath()) %>
    +<br>
    +Path info: <%= util.HTMLFilter.filter(request.getPathInfo()) %>
    +<br>
    +Query string: <%= util.HTMLFilter.filter(request.getQueryString()) %>
    +<br>
    +Content length: <%= request.getContentLength() %>
    +<br>
    +Content type: <%= util.HTMLFilter.filter(request.getContentType()) %>
    +<br>
    +Server name: <%= util.HTMLFilter.filter(request.getServerName()) %>
    +<br>
    +Server port: <%= request.getServerPort() %>
    +<br>
    +Remote user: <%= util.HTMLFilter.filter(request.getRemoteUser()) %>
    +<br>
    +Remote address: <%= util.HTMLFilter.filter(request.getRemoteAddr()) %>
    +<br>
    +Remote host: <%= util.HTMLFilter.filter(request.getRemoteHost()) %>
    +<br>
    +Authorization scheme: <%= util.HTMLFilter.filter(request.getAuthType()) %>
    +<br>
    +Locale: <%= request.getLocale() %>
    +<hr>
    +The browser you are using is
    +<%= util.HTMLFilter.filter(request.getHeader("User-Agent")) %>
    +<hr>
    +</font>
    +</body>
    +</html>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/tagplugin/choose.html b/tomcat/examples/jsp/tagplugin/choose.html new file mode 100644 index 0000000..afe90b2 --- /dev/null +++ b/tomcat/examples/jsp/tagplugin/choose.html @@ -0,0 +1,36 @@ + + + +View Source Code + + + +

    + + + + + +

    + +

    + Source Code for choose.jsp +

    + + + diff --git a/tomcat/examples/jsp/tagplugin/choose.jsp b/tomcat/examples/jsp/tagplugin/choose.jsp new file mode 100644 index 0000000..745e5f5 --- /dev/null +++ b/tomcat/examples/jsp/tagplugin/choose.jsp @@ -0,0 +1,54 @@ +<%-- + 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. +--%> + + + Tag Examples - choose + + +

    Tag Plugin Examples - <c:choose>

    + +
    +
    + Plugin Introductory Notes +
    + Brief Instructions for Writing Plugins +

    +
    + +
    + + <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> + + + # ${index}: + + + One!
    +
    + + Four!
    +
    + + Three!
    +
    + + Huh?
    +
    +
    +
    + + diff --git a/tomcat/examples/jsp/tagplugin/choose.jsp.html b/tomcat/examples/jsp/tagplugin/choose.jsp.html new file mode 100644 index 0000000..3f3b7e4 --- /dev/null +++ b/tomcat/examples/jsp/tagplugin/choose.jsp.html @@ -0,0 +1,55 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<html>
    +  <head>
    +    <title>Tag Examples - choose</title>
    +  </head>
    +  <body>
    +    <h1>Tag Plugin Examples - &lt;c:choose></h1>
    +
    +    <hr/>
    +    <br/>
    +    <a href="notes.html">Plugin Introductory Notes</a>
    +    <br/>
    +    <a href="howto.html">Brief Instructions for Writing Plugins</a>
    +    <br/> <br/>
    +    <hr/>
    +
    +    <br/>
    +
    +    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    +
    +    <c:forEach var="index" begin="0" end="4">
    +      # ${index}:
    +      <c:choose>
    +        <c:when test="${index == 1}">
    +          One!<br/>
    +        </c:when>
    +        <c:when test="${index == 4}">
    +          Four!<br/>
    +        </c:when>
    +        <c:when test="${index == 3}">
    +          Three!<br/>
    +        </c:when>
    +        <c:otherwise>
    +          Huh?<br/>
    +        </c:otherwise>
    +      </c:choose>
    +    </c:forEach>
    +  </body>
    +</html>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/tagplugin/foreach.html b/tomcat/examples/jsp/tagplugin/foreach.html new file mode 100644 index 0000000..3d2e608 --- /dev/null +++ b/tomcat/examples/jsp/tagplugin/foreach.html @@ -0,0 +1,36 @@ + + + +View Source Code + + + +

    + + + + + +

    + +

    + Source Code for foreach.jsp +

    + + + diff --git a/tomcat/examples/jsp/tagplugin/foreach.jsp b/tomcat/examples/jsp/tagplugin/foreach.jsp new file mode 100644 index 0000000..81621cc --- /dev/null +++ b/tomcat/examples/jsp/tagplugin/foreach.jsp @@ -0,0 +1,54 @@ +<%-- + 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. +--%> + + + Tag Plugin Examples: forEach + + +

    Tag Plugin Examples - <c:forEach>

    + +
    +
    + Plugin Introductory Notes +
    + Brief Instructions for Writing Plugins +

    +
    + +
    + + <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> + <%@ page import="java.util.Vector" %> + +

    Iterating over a range

    + + ${item} + + + <% Vector v = new Vector(); + v.add("One"); v.add("Two"); v.add("Three"); v.add("Four"); + + pageContext.setAttribute("vector", v); + %> + +

    Iterating over a Vector

    + + + ${item} + + + diff --git a/tomcat/examples/jsp/tagplugin/foreach.jsp.html b/tomcat/examples/jsp/tagplugin/foreach.jsp.html new file mode 100644 index 0000000..de4eca9 --- /dev/null +++ b/tomcat/examples/jsp/tagplugin/foreach.jsp.html @@ -0,0 +1,55 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<html>
    +  <head>
    +    <title>Tag Plugin Examples: forEach</title>
    +  </head>
    +  <body>
    +    <h1>Tag Plugin Examples - &lt;c:forEach></h1>
    +
    +    <hr/>
    +    <br/>
    +    <a href="notes.html">Plugin Introductory Notes</a>
    +    <br/>
    +    <a href="howto.html">Brief Instructions for Writing Plugins</a>
    +    <br/> <br/>
    +    <hr/>
    +
    +    <br/>
    +
    +    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    +    <%@ page import="java.util.Vector" %>
    +
    +    <h3>Iterating over a range</h3>
    +    <c:forEach var="item" begin="1" end="10">
    +        ${item}
    +    </c:forEach>
    +
    +    <% Vector v = new Vector();
    +        v.add("One"); v.add("Two"); v.add("Three"); v.add("Four");
    +
    +        pageContext.setAttribute("vector", v);
    +    %>
    +
    +    <h3>Iterating over a Vector</h3>
    +
    +    <c:forEach items="${vector}" var="item" >
    +        ${item}
    +    </c:forEach>
    +  </body>
    +</html>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/tagplugin/howto.html b/tomcat/examples/jsp/tagplugin/howto.html new file mode 100644 index 0000000..5f1d223 --- /dev/null +++ b/tomcat/examples/jsp/tagplugin/howto.html @@ -0,0 +1,45 @@ + + + + Tag Plugin Implementation + + +

    How to write tag plugins

    +

    + To write a plugin, you'll need to download the source for Tomcat. + There are two steps: +

      +
    1. + Implement the plugin class.

      + This class, which implements + org.apache.jasper.compiler.tagplugin.TagPlugin + instructs Jasper what Java codes to generate in place of the tag + handler calls. + See Javadoc for org.apache.jasper.compiler.tagplugin.TagPlugin + for details. +

    2. + +
    3. + Create the plugin descriptor file WEB-INF/tagPlugins.xml

      + This file + specifies the plugin classes and their corresponding tag handler + classes. +

    4. +
    + + diff --git a/tomcat/examples/jsp/tagplugin/if.html b/tomcat/examples/jsp/tagplugin/if.html new file mode 100644 index 0000000..b04ac59 --- /dev/null +++ b/tomcat/examples/jsp/tagplugin/if.html @@ -0,0 +1,36 @@ + + + +View Source Code + + + +

    + + + + + +

    + +

    + Source Code for if.jsp +

    + + + diff --git a/tomcat/examples/jsp/tagplugin/if.jsp b/tomcat/examples/jsp/tagplugin/if.jsp new file mode 100644 index 0000000..af627bf --- /dev/null +++ b/tomcat/examples/jsp/tagplugin/if.jsp @@ -0,0 +1,47 @@ +<%-- + 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. +--%> + + + Tag Plugin Examples: if + + +

    Tag Plugin Examples - <c:if>

    + +
    +
    + Plugin Introductory Notes +
    + Brief Instructions for Writing Plugins +

    +
    + +
    + <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> + +

    Set the test result to a variable

    + + The result of testing for (1==1) is: ${theTruth} + +

    Conditionally execute the body

    + +

    It's true that (2>0)! Working.

    +
    + +

    It's not true that (0>2)! Failed.

    +
    + + diff --git a/tomcat/examples/jsp/tagplugin/if.jsp.html b/tomcat/examples/jsp/tagplugin/if.jsp.html new file mode 100644 index 0000000..ee126c3 --- /dev/null +++ b/tomcat/examples/jsp/tagplugin/if.jsp.html @@ -0,0 +1,48 @@ +Source Code
    <%--
    + 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.
    +--%>
    +<html>
    +  <head>
    +    <title>Tag Plugin Examples: if</title>
    +  </head>
    +  <body>
    +    <h1>Tag Plugin Examples - &lt;c:if></h1>
    +
    +    <hr/>
    +    <br/>
    +    <a href="notes.html">Plugin Introductory Notes</a>
    +    <br/>
    +    <a href="howto.html">Brief Instructions for Writing Plugins</a>
    +    <br/> <br/>
    +    <hr/>
    +
    +    <br/>
    +    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    +
    +    <h3>Set the test result to a variable</h3>
    +    <c:if test="${1==1}" var="theTruth" scope="page"/>
    +    The result of testing for (1==1) is: ${theTruth}
    +
    +    <h3>Conditionally execute the body</h3>
    +    <c:if test="${2>0}">
    +        <p>It's true that (2>0)! Working.</p>
    +    </c:if>
    +    <c:if test="${0>2}">
    +        <p>It's not true that (0>2)! Failed.</p>
    +    </c:if>
    +  </body>
    +</html>
    +
    \ No newline at end of file diff --git a/tomcat/examples/jsp/tagplugin/notes.html b/tomcat/examples/jsp/tagplugin/notes.html new file mode 100644 index 0000000..cd326fc --- /dev/null +++ b/tomcat/examples/jsp/tagplugin/notes.html @@ -0,0 +1,41 @@ + + + + Tag Plugin Introduction + + +

    Tag Plugins: Introductory Notes

    +

    + Tomcat provides a framework for implementing tag plugins. The + plugins instruct Jasper, at translation time, to replace tag handler + calls with Java scriptlets. + The framework allows tag library authors to implement plugins for + their tags. +

    +

    + Tomcat is released with plugins for several JSTL tags. Note + that these plugins work with JSTL 1.1 as well as JSTL 1.0, though + the examples uses JSTL 1.1 and JSP 2.0. + These plugins are not complete (for instance, some item types are not + handled in <c:if>). + They do serve as examples to show plugins in action (just + examine the generated Java files), and how they can be implemented. +

    + + + diff --git a/tomcat/examples/jsp/xml/xml.html b/tomcat/examples/jsp/xml/xml.html new file mode 100644 index 0000000..0012142 --- /dev/null +++ b/tomcat/examples/jsp/xml/xml.html @@ -0,0 +1,31 @@ + + + + +Untitled Document + + + + +

    + +

    Source Code for XML syntax Example +

    + + + diff --git a/tomcat/examples/jsp/xml/xml.jsp b/tomcat/examples/jsp/xml/xml.jsp new file mode 100644 index 0000000..840b21f --- /dev/null +++ b/tomcat/examples/jsp/xml/xml.jsp @@ -0,0 +1,70 @@ + + + + + + + + + String getDateTimeStr(Locale l) { + DateFormat df = SimpleDateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, l); + return df.format(new Date()); + } + + + + + Example JSP in XML format + + + +This is the output of a simple JSP using XML format. +
    + +
    Use a jsp:scriptlet to loop from 1 to 10:
    + +// Note we need to declare CDATA because we don't escape the less than symbol + + + + +
    +]]> + +
    + Use a jsp:expression to write the date and time in the browser's locale: + getDateTimeStr(request.getLocale()) +
    + + + + <p>This sentence is enclosed in a jsp:text element.</p> + + + + +
    diff --git a/tomcat/examples/jsp/xml/xml.jsp.html b/tomcat/examples/jsp/xml/xml.jsp.html new file mode 100644 index 0000000..b146a97 --- /dev/null +++ b/tomcat/examples/jsp/xml/xml.jsp.html @@ -0,0 +1,71 @@ +Source Code
    <?xml version="1.0" encoding="UTF-8"?>
    +<!--
    + 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.
    +-->
    +<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page"
    +  version="1.2">
    +<jsp:directive.page contentType="text/html"/>
    +<jsp:directive.page import="java.util.Date, java.util.Locale"/>
    +<jsp:directive.page import="java.text.*"/>
    +
    +<jsp:declaration>
    +  String getDateTimeStr(Locale l) {
    +    DateFormat df = SimpleDateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, l);
    +    return df.format(new Date());
    +  }
    +</jsp:declaration>
    +
    +<html>
    +<head>
    +  <title>Example JSP in XML format</title>
    +</head>
    +
    +<body>
    +This is the output of a simple JSP using XML format.
    +<br />
    +
    +<div>Use a jsp:scriptlet to loop from 1 to 10: </div>
    +<jsp:scriptlet>
    +// Note we need to declare CDATA because we don't escape the less than symbol
    +<![CDATA[
    +  for (int i = 1; i<=10; i++) {
    +    out.println(i);
    +    if (i < 10) {
    +      out.println(", ");
    +    }
    +  }
    +]]>
    +</jsp:scriptlet>
    +
    +<!-- Because I omit br's end tag, declare it as CDATA -->
    +<![CDATA[
    +  <br><br>
    +]]>
    +
    +<div align="left">
    +  Use a jsp:expression to write the date and time in the browser's locale:
    +  <jsp:expression>getDateTimeStr(request.getLocale())</jsp:expression>
    +</div>
    +
    +
    +<jsp:text>
    +  &lt;p&gt;This sentence is enclosed in a jsp:text element.&lt;/p&gt;
    +</jsp:text>
    +
    +</body>
    +</html>
    +</jsp:root>
    +
    \ No newline at end of file diff --git a/tomcat/examples/servlets/cookies.html b/tomcat/examples/servlets/cookies.html new file mode 100644 index 0000000..bacee44 --- /dev/null +++ b/tomcat/examples/servlets/cookies.html @@ -0,0 +1,61 @@ + + + +Untitled Document + + + + +

    +

    Source Code for Cookie Example
    +

    + +
    import java.io.*;
    +import javax.servlet.*;
    +import javax.servlet.http.*;
    +
    +public class CookieExample extends HttpServlet {
    +
    +    public void doGet(HttpServletRequest request, HttpServletResponse response)
    +    throws IOException, ServletException
    +    {
    +        response.setContentType("text/html");
    +        PrintWriter out = response.getWriter();
    +
    +        // print out cookies
    +
    +        Cookie[] cookies = request.getCookies();
    +        for (int i = 0; i < cookies.length; i++) {
    +            Cookie c = cookies[i];
    +            String name = c.getName();
    +            String value = c.getValue();
    +            out.println(name + " = " + value);
    +        }
    +
    +        // set a cookie
    +
    +        String name = request.getParameter("cookieName");
    +        if (name != null && name.length() > 0) {
    +            String value = request.getParameter("cookieValue");
    +            Cookie c = new Cookie(name, value);
    +            response.addCookie(c);
    +        }
    +    }
    +}
    + + diff --git a/tomcat/examples/servlets/helloworld.html b/tomcat/examples/servlets/helloworld.html new file mode 100644 index 0000000..c223446 --- /dev/null +++ b/tomcat/examples/servlets/helloworld.html @@ -0,0 +1,50 @@ + + + +Untitled Document + + + + +

    +

    Source Code for HelloWorld Example
    +

    + +
    import java.io.*;
    +import javax.servlet.*;
    +import javax.servlet.http.*;
    +
    +public class HelloWorld extends HttpServlet {
    +
    +    public void doGet(HttpServletRequest request, HttpServletResponse response)
    +    throws IOException, ServletException
    +    {
    +        response.setContentType("text/html");
    +        PrintWriter out = response.getWriter();
    +        out.println("<html>");
    +        out.println("<head>");
    +        out.println("<title>Hello World!</title>");
    +        out.println("</head>");
    +        out.println("<body>");
    +        out.println("<h1>Hello World!</h1>");
    +        out.println("</body>");
    +        out.println("</html>");
    +    }
    +}
    + + diff --git a/tomcat/examples/servlets/images/code.gif b/tomcat/examples/servlets/images/code.gif new file mode 100644 index 0000000..93af2cd Binary files /dev/null and b/tomcat/examples/servlets/images/code.gif differ diff --git a/tomcat/examples/servlets/images/execute.gif b/tomcat/examples/servlets/images/execute.gif new file mode 100644 index 0000000..f64d70f Binary files /dev/null and b/tomcat/examples/servlets/images/execute.gif differ diff --git a/tomcat/examples/servlets/images/return.gif b/tomcat/examples/servlets/images/return.gif new file mode 100644 index 0000000..af4f68f Binary files /dev/null and b/tomcat/examples/servlets/images/return.gif differ diff --git a/tomcat/examples/servlets/index.html b/tomcat/examples/servlets/index.html new file mode 100644 index 0000000..94931d4 --- /dev/null +++ b/tomcat/examples/servlets/index.html @@ -0,0 +1,171 @@ + + + + + + Servlet Examples + + + +

    Servlet +Examples with Code

    +

    This is a collection of examples which demonstrate some of the more +frequently used parts of the Servlet API. Familiarity with the Java(tm) +Programming Language is assumed. +

    These examples will only work when viewed via an http URL. They will +not work if you are viewing these pages via a "file://..." URL. Please +refer to the README file provide with this Tomcat release regarding +how to configure and start the provided web server. +

    Wherever you see a form, enter some data and see how the servlet reacts. +When playing with the Cookie and Session Examples, jump back to the Headers +Example to see exactly what your browser is sending the server. +

    To navigate your way through the examples, the following icons will +help:

    +
      +
    • Execute the example
    • +
    • Look at the source code for the example
    • +
    • Return to this screen
    • +
    + +

    Tip: To see the cookie interactions with your browser, try turning on +the "notify when setting a cookie" option in your browser preferences. +This will let you see when a session is created and give some feedback +when looking at the cookie demo.

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Hello WorldExecuteSource
    Request InfoExecuteSource
    Request HeadersExecuteSource
    Request ParametersExecuteSource
    CookiesExecuteSource
    SessionsExecuteSource
    + +

    Note: The source code for these examples does not contain all of the +source code that is actually in the example, only the important sections +of code. Code not important to understand the example has been removed +for clarity.

    + +

    Other Examples

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Servlet 3.0 Asynchronous processing examples:
    async0 + Execute +
    async1 + Execute +
    async2 + Execute +
    async3 + Execute +
    stockticker + Execute +
    Servlet 3.1 Non-blocking IO examples
    Byte counter + Execute +
    Number Writer + Execute +
    + + + diff --git a/tomcat/examples/servlets/nonblocking/bytecounter.html b/tomcat/examples/servlets/nonblocking/bytecounter.html new file mode 100644 index 0000000..55d31a2 --- /dev/null +++ b/tomcat/examples/servlets/nonblocking/bytecounter.html @@ -0,0 +1,32 @@ + + + + Servlet 3.1 non-blocking IO examples: Byte counter + + +

    Byte counter

    +

    Select a file and/or enter some data using the form below and then submit + it. The server will read the request body using non-blocking IO and then + respond with the total length of the request body in bytes.

    +
    +

    +

    +

    +
    + + \ No newline at end of file diff --git a/tomcat/examples/servlets/reqheaders.html b/tomcat/examples/servlets/reqheaders.html new file mode 100644 index 0000000..adda30c --- /dev/null +++ b/tomcat/examples/servlets/reqheaders.html @@ -0,0 +1,49 @@ + + + +Untitled Document + + + + +

    +

    Source Code for RequestHeader Example
    +

    + +
    import java.io.*;
    +import java.util.*;
    +import javax.servlet.*;
    +import javax.servlet.http.*;
    +
    +public class RequestHeaderExample extends HttpServlet {
    +
    +    public void doGet(HttpServletRequest request, HttpServletResponse response)
    +    throws IOException, ServletException
    +    {
    +        response.setContentType("text/html");
    +        PrintWriter out = response.getWriter();
    +        Enumeration e = request.getHeaderNames();
    +        while (e.hasMoreElements()) {
    +            String name = (String)e.nextElement();
    +            String value = request.getHeader(name);
    +            out.println(name + " = " + value);
    +        }
    +    }
    +}
    + + diff --git a/tomcat/examples/servlets/reqinfo.html b/tomcat/examples/servlets/reqinfo.html new file mode 100644 index 0000000..daf239c --- /dev/null +++ b/tomcat/examples/servlets/reqinfo.html @@ -0,0 +1,68 @@ + + + +Untitled Document + + + + +

    +

    Source Code for Request Info Example
    +

    + +
    import java.io.*;
    +import javax.servlet.*;
    +import javax.servlet.http.*;
    +
    +public class RequestInfo extends HttpServlet {
    +
    +    public void doGet(HttpServletRequest request, HttpServletResponse response)
    +    throws IOException, ServletException
    +    {
    +        response.setContentType("text/html");
    +        PrintWriter out = response.getWriter();
    +        out.println("<html>");
    +        out.println("<body>");
    +        out.println("<head>");
    +        out.println("<title>Request Information Example</title>");
    +        out.println("</head>");
    +        out.println("<body>");
    +        out.println("<h3>Request Information Example</h3>");
    +        out.println("Method: " + request.getMethod());
    +        out.println("Request URI: " + request.getRequestURI());
    +        out.println("Protocol: " + request.getProtocol());
    +        out.println("PathInfo: " + request.getPathInfo());
    +        out.println("Remote Address: " + request.getRemoteAddr());
    +        out.println("</body>");
    +        out.println("</html>");
    +    }
    +
    +    /**
    +     * We are going to perform the same operations for POST requests
    +     * as for GET methods, so this method just sends the request to
    +     * the doGet method.
    +     */
    +
    +    public void doPost(HttpServletRequest request, HttpServletResponse response)
    +    throws IOException, ServletException
    +    {
    +        doGet(request, response);
    +    }
    +}
    + + diff --git a/tomcat/examples/servlets/reqparams.html b/tomcat/examples/servlets/reqparams.html new file mode 100644 index 0000000..7128e39 --- /dev/null +++ b/tomcat/examples/servlets/reqparams.html @@ -0,0 +1,78 @@ + + + +Untitled Document + + + + +

    +

    Source Code for Request Parameter Example
    +

    + +
    import java.io.*;
    +import java.util.*;
    +import javax.servlet.*;
    +import javax.servlet.http.*;
    +
    +public class RequestParamExample extends HttpServlet {
    +
    +    public void doGet(HttpServletRequest request, HttpServletResponse response)
    +    throws IOException, ServletException
    +    {
    +        response.setContentType("text/html");
    +        PrintWriter out = response.getWriter();
    +        out.println("<html>");
    +        out.println("<head>");
    +        out.println("<title>Request Parameters Example</title>");
    +        out.println("</head>");
    +        out.println("<body>");
    +        out.println("<h3>Request Parameters Example</h3>");
    +        out.println("Parameters in this request:<br>");
    +        if (firstName != null || lastName != null) {
    +            out.println("First Name:");
    +            out.println(" = " + HTMLFilter.filter(firstName) + "<br>");
    +            out.println("Last Name:");
    +            out.println(" = " + HTMLFilter.filter(lastName));
    +        } else {
    +            out.println("No Parameters, Please enter some");
    +        }
    +        out.println("<P>");
    +        out.print("<form action=\"");
    +        out.print("RequestParamExample\" ");
    +        out.println("method=POST>");
    +        out.println("First Name:");
    +        out.println("<input type=text size=20 name=firstname>");
    +        out.println("<br>");
    +        out.println("Last Name:");
    +        out.println("<input type=text size=20 name=lastname>");
    +        out.println("<br>");
    +        out.println("<input type=submit>");
    +        out.println("</form>");
    +        out.println("</body>");
    +        out.println("</html>");
    +    }
    +
    +    public void doPost(HttpServletRequest request, HttpServletResponse res)
    +    throws IOException, ServletException
    +    {
    +        doGet(request, response);
    +    }
    +}
    + + diff --git a/tomcat/examples/servlets/sessions.html b/tomcat/examples/servlets/sessions.html new file mode 100644 index 0000000..99816c2 --- /dev/null +++ b/tomcat/examples/servlets/sessions.html @@ -0,0 +1,70 @@ + + + +Untitled Document + + + + +

    +

    Source Code for Session Example
    +

    + +
    import java.io.*;
    +import java.util.*;
    +import javax.servlet.*;
    +import javax.servlet.http.*;
    +
    +public class SessionExample extends HttpServlet {
    +
    +    public void doGet(HttpServletRequest request, HttpServletResponse response)
    +    throws IOException, ServletException
    +    {
    +        response.setContentType("text/html");
    +        PrintWriter out = response.getWriter();
    +
    +        HttpSession session = request.getSession(true);
    +
    +        // print session info
    +
    +        Date created = new Date(session.getCreationTime());
    +        Date accessed = new Date(session.getLastAccessedTime());
    +        out.println("ID " + session.getId());
    +        out.println("Created: " + created);
    +        out.println("Last Accessed: " + accessed);
    +
    +        // set session info if needed
    +
    +        String dataName = request.getParameter("dataName");
    +        if (dataName != null && dataName.length() > 0) {
    +            String dataValue = request.getParameter("dataValue");
    +            session.setAttribute(dataName, dataValue);
    +        }
    +
    +        // print session contents
    +
    +        Enumeration e = session.getAttributeNames();
    +        while (e.hasMoreElements()) {
    +            String name = (String)e.nextElement();
    +            String value = session.getAttribute(name).toString();
    +            out.println(name + " = " + value);
    +        }
    +    }
    +}
    + + diff --git a/tomcat/examples/websocket/chat.xhtml b/tomcat/examples/websocket/chat.xhtml new file mode 100644 index 0000000..fca748c --- /dev/null +++ b/tomcat/examples/websocket/chat.xhtml @@ -0,0 +1,136 @@ + + + + + Apache Tomcat WebSocket Examples: Chat + + + + +

    Seems your browser doesn't support Javascript! Websockets rely on Javascript being enabled. Please enable + Javascript and reload this page!

    +
    +

    + +

    +
    +
    +
    +
    + + \ No newline at end of file diff --git a/tomcat/examples/websocket/drawboard.xhtml b/tomcat/examples/websocket/drawboard.xhtml new file mode 100644 index 0000000..ff63366 --- /dev/null +++ b/tomcat/examples/websocket/drawboard.xhtml @@ -0,0 +1,899 @@ + + + + + Apache Tomcat WebSocket Examples: Drawboard + + + + +
    Seems your browser doesn't support Javascript! Websockets rely on Javascript being enabled. Please enable + Javascript and reload this page!
    +
    +
    +
    +
    + +

    About Drawboard WebSocket Example

    +
    +

    + This drawboard is a page where you can draw with your mouse or touch input + (using different colors) and everybody else which has the page open will + immediately see what you are drawing.
    + If someone opens the page later, they will get the current room image (so they + can see what was already drawn by other people). +

    +

    + It uses asynchronous sending of messages so that it doesn't need separate threads + for each client to send messages.
    + Each "Room" (where the drawing happens) uses a ReentrantLock to synchronize access + (currently, only a single Room is implemented). +

    +

    + When you open the page, first you will receive a binary websocket message containing + the current room image as PNG image. After that, you will receive string messages + that contain the drawing actions (line from x1,y1 to x2,y2).
    + Note that it currently only uses simple string messages instead of JSON because + I did not want to introduce a dependency on a JSON lib. +

    +

    + It uses synchronization mechanisms to ensure that the final image will look the same + for every user, regardless of what their network latency/speed is – e.g. if two user + draw at the same time on the same place, the server will decide which line was the + first one, and that will be reflected on every client. +

    +
    + + \ No newline at end of file diff --git a/tomcat/examples/websocket/echo.xhtml b/tomcat/examples/websocket/echo.xhtml new file mode 100644 index 0000000..89347bb --- /dev/null +++ b/tomcat/examples/websocket/echo.xhtml @@ -0,0 +1,184 @@ + + + + + Apache Tomcat WebSocket Examples: Echo + + + + +

    Seems your browser doesn't support Javascript! Websockets rely on Javascript being enabled. Please enable + Javascript and reload this page!

    +
    +
    +
    + Connect to service implemented using: +
    + + +
    + + +
    + + +
    + + + +
    +
    + +
    +
    + + +
    +
    + +
    +
    + +
    +
    +
    +
    +
    +
    + + \ No newline at end of file diff --git a/tomcat/examples/websocket/index.xhtml b/tomcat/examples/websocket/index.xhtml new file mode 100644 index 0000000..97ee945 --- /dev/null +++ b/tomcat/examples/websocket/index.xhtml @@ -0,0 +1,32 @@ + + + + + Apache Tomcat WebSocket Examples + + +

    Apache Tomcat WebSocket Examples

    + + + \ No newline at end of file diff --git a/tomcat/examples/websocket/snake.xhtml b/tomcat/examples/websocket/snake.xhtml new file mode 100644 index 0000000..b71077c --- /dev/null +++ b/tomcat/examples/websocket/snake.xhtml @@ -0,0 +1,266 @@ + + + + + Apache Tomcat WebSocket Examples: Multiplayer Snake + + + +

    Seems your browser doesn't support Javascript! Websockets rely on Javascript being enabled. Please enable + Javascript and reload this page!

    +
    + +
    +
    +
    +
    + + + \ No newline at end of file diff --git a/tomcat/giit.war b/tomcat/giit.war new file mode 100644 index 0000000..6e6e492 Binary files /dev/null and b/tomcat/giit.war differ diff --git a/tomcat/host-manager/META-INF/context.xml b/tomcat/host-manager/META-INF/context.xml new file mode 100644 index 0000000..8d1f61d --- /dev/null +++ b/tomcat/host-manager/META-INF/context.xml @@ -0,0 +1,22 @@ + + + + + + \ No newline at end of file diff --git a/tomcat/host-manager/WEB-INF/jsp/401.jsp b/tomcat/host-manager/WEB-INF/jsp/401.jsp new file mode 100644 index 0000000..047766b --- /dev/null +++ b/tomcat/host-manager/WEB-INF/jsp/401.jsp @@ -0,0 +1,71 @@ +<%-- + 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. +--%> +<%@ page session="false" trimDirectiveWhitespaces="true" %> + + + + 401 Unauthorized + + + +

    401 Unauthorized

    +

    + You are not authorized to view this page. If you have not changed + any configuration files, please examine the file + conf/tomcat-users.xml in your installation. That + file must contain the credentials to let you use this webapp. +

    +

    + For example, to add the admin-gui role to a user named + tomcat with a password of s3cret, add the following to the + config file listed above. +

    +
    +<role rolename="admin-gui"/>
    +<user username="tomcat" password="s3cret" roles="admin-gui"/>
    +
    +

    + Note that for Tomcat 7 onwards, the roles required to use the host manager + application were changed from the single admin role to the + following two roles. You will need to assign the role(s) required for + the functionality you wish to access. +

    +
      +
    • admin-gui - allows access to the HTML GUI
    • +
    • admin-script - allows access to the text interface
    • +
    +

    + The HTML interface is protected against CSRF but the text interface is not. + To maintain the CSRF protection: +

    +
      +
    • Users with the admin-gui role should not be granted the + admin-script role.
    • +
    • If the text interface is accessed through a browser (e.g. for testing + since this interface is intended for tools not humans) then the browser + must be closed afterwards to terminate the session.
    • +
    + + + diff --git a/tomcat/host-manager/WEB-INF/jsp/403.jsp b/tomcat/host-manager/WEB-INF/jsp/403.jsp new file mode 100644 index 0000000..74e1e2d --- /dev/null +++ b/tomcat/host-manager/WEB-INF/jsp/403.jsp @@ -0,0 +1,90 @@ +<%-- + 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. +--%> +<%@ page session="false" trimDirectiveWhitespaces="true" %> + + + + 403 Access Denied + + + +

    403 Access Denied

    +

    + You are not authorized to view this page. +

    +

    + By default the Host Manager is only accessible from a browser running on the + same machine as Tomcat. If you wish to modify this restriction, you'll need + to edit the Host Manager's context.xml file. +

    +

    + If you have already configured the Host Manager application to allow access + and you have used your browsers back button, used a saved book-mark or + similar then you may have triggered the cross-site request forgery (CSRF) + protection that has been enabled for the HTML interface of the Host Manager + application. You will need to reset this protection by returning to the + main Host Manager page. + Once you return to this page, you will be able to continue using the Host + Manager application's HTML interface normally. If you continue to see this + access denied message, check that you have the necessary permissions to + access this application. +

    +

    If you have not changed + any configuration files, please examine the file + conf/tomcat-users.xml in your installation. That + file must contain the credentials to let you use this webapp. +

    +

    + For example, to add the admin-gui role to a user named + tomcat with a password of s3cret, add the following to the + config file listed above. +

    +
    +<role rolename="admin-gui"/>
    +<user username="tomcat" password="s3cret" roles="admin-gui"/>
    +
    +

    + Note that for Tomcat 7 onwards, the roles required to use the host manager + application were changed from the single admin role to the + following two roles. You will need to assign the role(s) required for + the functionality you wish to access. +

    +
      +
    • admin-gui - allows access to the HTML GUI
    • +
    • admin-script - allows access to the text interface
    • +
    +

    + The HTML interface is protected against CSRF but the text interface is not. + To maintain the CSRF protection: +

    +
      +
    • Users with the admin-gui role should not be granted the + admin-script role.
    • +
    • If the text interface is accessed through a browser (e.g. for testing + since this interface is intended for tools not humans) then the browser + must be closed afterwards to terminate the session.
    • +
    + + + diff --git a/tomcat/host-manager/WEB-INF/jsp/404.jsp b/tomcat/host-manager/WEB-INF/jsp/404.jsp new file mode 100644 index 0000000..9816df5 --- /dev/null +++ b/tomcat/host-manager/WEB-INF/jsp/404.jsp @@ -0,0 +1,62 @@ +<%-- + 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. +--%> +<%@ page import="org.apache.catalina.util.RequestUtil" session="false" + trimDirectiveWhitespaces="true" %> + + + + 404 Not found + + + +

    404 Not found

    +

    + The page you tried to access + (<%=RequestUtil.filter((String) request.getAttribute( + "javax.servlet.error.request_uri"))%>) + does not exist. +

    +

    + The Host Manager application has been re-structured for Tomcat 7 onwards and + some URLs have changed. All URLs used to access the Manager application + should now start with one of the following options: +

    +
      +
    • <%=request.getContextPath()%>/html for the HTML GUI
    • +
    • <%=request.getContextPath()%>/text for the text interface
    • +
    +

    + Note that the URL for the text interface has changed from + "<%=request.getContextPath()%>" to + "<%=request.getContextPath()%>/text". +

    +

    + You probably need to adjust the URL you are using to access the Host Manager + application. However, there is always a chance you have found a bug in the + Host Manager application. If you are sure you have found a bug, and that the + bug has not already been reported, please report it to the Apache Tomcat + team. +

    + + diff --git a/tomcat/host-manager/WEB-INF/web.xml b/tomcat/host-manager/WEB-INF/web.xml new file mode 100644 index 0000000..c315546 --- /dev/null +++ b/tomcat/host-manager/WEB-INF/web.xml @@ -0,0 +1,143 @@ + + + + + Tomcat Host Manager Application + + A scriptable host management web application for the Tomcat Web Server; + Manager lets you view, create and remove virtual hosts. + + + + HostManager + org.apache.catalina.manager.host.HostManagerServlet + + debug + 2 + + + + HTMLHostManager + org.apache.catalina.manager.host.HTMLHostManagerServlet + + debug + 2 + + + + + SetCharacterEncoding + org.apache.catalina.filters.SetCharacterEncodingFilter + + encoding + UTF-8 + + + + + SetCharacterEncoding + /* + + + + CSRF + org.apache.catalina.filters.CsrfPreventionFilter + + entryPoints + /html,/html/,/html/list,/index.jsp + + + + + CSRF + HTMLHostManager + + + + + HostManager + /text/* + + + HTMLHostManager + /html/* + + + + + + HostManager commands + /text/* + + + + admin-script + + + + + HTMLHostManager commands + /html/* + + + + admin-gui + + + + + + BASIC + Tomcat Host Manager Application + + + + + + The role that is required to log in to the Host Manager Application HTML + interface + + admin-gui + + + + The role that is required to log in to the Host Manager Application text + interface + + admin-script + + + + 401 + /WEB-INF/jsp/401.jsp + + + 403 + /WEB-INF/jsp/403.jsp + + + 404 + /WEB-INF/jsp/404.jsp + + + diff --git a/tomcat/host-manager/images/asf-logo.svg b/tomcat/host-manager/images/asf-logo.svg new file mode 100644 index 0000000..e24cbe5 --- /dev/null +++ b/tomcat/host-manager/images/asf-logo.svg @@ -0,0 +1,226 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tomcat/host-manager/images/tomcat.gif b/tomcat/host-manager/images/tomcat.gif new file mode 100644 index 0000000..f2aa6f8 Binary files /dev/null and b/tomcat/host-manager/images/tomcat.gif differ diff --git a/tomcat/host-manager/index.jsp b/tomcat/host-manager/index.jsp new file mode 100644 index 0000000..2806b76 --- /dev/null +++ b/tomcat/host-manager/index.jsp @@ -0,0 +1,18 @@ +<%-- + 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. +--%> +<%@ page session="false" trimDirectiveWhitespaces="true" %> +<% response.sendRedirect(request.getContextPath() + "/html"); %> \ No newline at end of file diff --git a/tomcat/host-manager/manager.xml b/tomcat/host-manager/manager.xml new file mode 100644 index 0000000..2510acb --- /dev/null +++ b/tomcat/host-manager/manager.xml @@ -0,0 +1,26 @@ + + + + + + diff --git a/tomcat/manager/META-INF/context.xml b/tomcat/manager/META-INF/context.xml new file mode 100644 index 0000000..0217745 --- /dev/null +++ b/tomcat/manager/META-INF/context.xml @@ -0,0 +1,22 @@ + + + + + + diff --git a/tomcat/manager/WEB-INF/jsp/401.jsp b/tomcat/manager/WEB-INF/jsp/401.jsp new file mode 100644 index 0000000..84c9a97 --- /dev/null +++ b/tomcat/manager/WEB-INF/jsp/401.jsp @@ -0,0 +1,80 @@ +<%-- + 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. +--%> +<%@ page session="false" trimDirectiveWhitespaces="true" %> + + + + 401 Unauthorized + + + +

    401 Unauthorized

    +

    + You are not authorized to view this page. If you have not changed + any configuration files, please examine the file + conf/tomcat-users.xml in your installation. That + file must contain the credentials to let you use this webapp. +

    +

    + For example, to add the manager-gui role to a user named + tomcat with a password of s3cret, add the following to the + config file listed above. +

    +
    +<role rolename="manager-gui"/>
    +<user username="tomcat" password="s3cret" roles="manager-gui"/>
    +
    +

    + Note that for Tomcat 7 onwards, the roles required to use the manager + application were changed from the single manager role to the + following four roles. You will need to assign the role(s) required for + the functionality you wish to access. +

    +
      +
    • manager-gui - allows access to the HTML GUI and the status + pages
    • +
    • manager-script - allows access to the text interface and the + status pages
    • +
    • manager-jmx - allows access to the JMX proxy and the status + pages
    • +
    • manager-status - allows access to the status pages only
    • +
    +

    + The HTML interface is protected against CSRF but the text and JMX interfaces + are not. To maintain the CSRF protection: +

    +
      +
    • Users with the manager-gui role should not be granted either + the manager-script or manager-jmx roles.
    • +
    • If the text or jmx interfaces are accessed through a browser (e.g. for + testing since these interfaces are intended for tools not humans) then + the browser must be closed afterwards to terminate the session.
    • +
    +

    + For more information - please see the + Manager App How-To. +

    + + + diff --git a/tomcat/manager/WEB-INF/jsp/403.jsp b/tomcat/manager/WEB-INF/jsp/403.jsp new file mode 100644 index 0000000..4baa2f4 --- /dev/null +++ b/tomcat/manager/WEB-INF/jsp/403.jsp @@ -0,0 +1,100 @@ +<%-- + 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. +--%> +<%@ page session="false" trimDirectiveWhitespaces="true" %> + + + + 403 Access Denied + + + +

    403 Access Denied

    +

    + You are not authorized to view this page. +

    +

    + By default the Manager is only accessible from a browser running on the + same machine as Tomcat. If you wish to modify this restriction, you'll need + to edit the Manager's context.xml file. +

    +

    + If you have already configured the Manager application to allow access and + you have used your browsers back button, used a saved book-mark or similar + then you may have triggered the cross-site request forgery (CSRF) protection + that has been enabled for the HTML interface of the Manager application. You + will need to reset this protection by returning to the + main Manager page. Once you + return to this page, you will be able to continue using the Manager + application's HTML interface normally. If you continue to see this access + denied message, check that you have the necessary permissions to access this + application. +

    +

    + If you have not changed + any configuration files, please examine the file + conf/tomcat-users.xml in your installation. That + file must contain the credentials to let you use this webapp. +

    +

    + For example, to add the manager-gui role to a user named + tomcat with a password of s3cret, add the following to the + config file listed above. +

    +
    +<role rolename="manager-gui"/>
    +<user username="tomcat" password="s3cret" roles="manager-gui"/>
    +
    +

    + Note that for Tomcat 7 onwards, the roles required to use the manager + application were changed from the single manager role to the + following four roles. You will need to assign the role(s) required for + the functionality you wish to access. +

    +
      +
    • manager-gui - allows access to the HTML GUI and the status + pages
    • +
    • manager-script - allows access to the text interface and the + status pages
    • +
    • manager-jmx - allows access to the JMX proxy and the status + pages
    • +
    • manager-status - allows access to the status pages only
    • +
    +

    + The HTML interface is protected against CSRF but the text and JMX interfaces + are not. To maintain the CSRF protection: +

    +
      +
    • Users with the manager-gui role should not be granted either + the manager-script or manager-jmx roles.
    • +
    • If the text or jmx interfaces are accessed through a browser (e.g. for + testing since these interfaces are intended for tools not humans) then + the browser must be closed afterwards to terminate the session.
    • +
    +

    + For more information - please see the + Manager App How-To. +

    + + + diff --git a/tomcat/manager/WEB-INF/jsp/404.jsp b/tomcat/manager/WEB-INF/jsp/404.jsp new file mode 100644 index 0000000..111a800 --- /dev/null +++ b/tomcat/manager/WEB-INF/jsp/404.jsp @@ -0,0 +1,63 @@ +<%-- + 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. +--%> +<%@ page import="org.apache.tomcat.util.security.Escape" session="false" + trimDirectiveWhitespaces="true" %> + + + + 404 Not found + + + +

    404 Not found

    +

    + The page you tried to access + (<%=Escape.htmlElementContent((String) request.getAttribute( + "javax.servlet.error.request_uri"))%>) + does not exist. +

    +

    + The Manager application has been re-structured for Tomcat 7 onwards and some + of URLs have changed. All URLs used to access the Manager application should + now start with one of the following options: +

    +
      +
    • <%=request.getContextPath()%>/html for the HTML GUI
    • +
    • <%=request.getContextPath()%>/text for the text interface
    • +
    • <%=request.getContextPath()%>/jmxproxy for the JMX proxy
    • +
    • <%=request.getContextPath()%>/status for the status pages
    • +
    +

    + Note that the URL for the text interface has changed from + "<%=request.getContextPath()%>" to + "<%=request.getContextPath()%>/text". +

    +

    + You probably need to adjust the URL you are using to access the Manager + application. However, there is always a chance you have found a bug in the + Manager application. If you are sure you have found a bug, and that the bug + has not already been reported, please report it to the Apache Tomcat team. +

    + + diff --git a/tomcat/manager/WEB-INF/jsp/connectorCerts.jsp b/tomcat/manager/WEB-INF/jsp/connectorCerts.jsp new file mode 100644 index 0000000..a2f5de7 --- /dev/null +++ b/tomcat/manager/WEB-INF/jsp/connectorCerts.jsp @@ -0,0 +1,92 @@ + +<%-- + 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. +--%> +<%@page session="false" contentType="text/html; charset=ISO-8859-1" %> +<%@page import="java.util.Map" %> +<%@page import="java.util.Map.Entry" %> +<%@page import="java.util.List" %> + + + +<% Map> certList = (Map>) request.getAttribute("certList"); +%> + + + + + + + + + Configured certificate chains per Connector + + +

    Configured certificate chains per Connector

    + + + + + + + + + + <% + for (Map.Entry> entry : certList.entrySet()) { + %> + + + + + <% + } + %> + +
    Connector / TLS Virtual Host / Certificate typeCertificate chain
    <%=entry.getKey()%> + <% + for (String cert : entry.getValue()) { + %> +
    <%=cert%>
    + <% + } + %> +
    + +
    +

    + +

    +
    + +<%--div style="display: none;"> +

    + Valid HTML 4.01! + Valid XHTML 1.0! + Valid XHTML 1.1! +

    + + + + diff --git a/tomcat/manager/WEB-INF/jsp/connectorCiphers.jsp b/tomcat/manager/WEB-INF/jsp/connectorCiphers.jsp new file mode 100644 index 0000000..915508e --- /dev/null +++ b/tomcat/manager/WEB-INF/jsp/connectorCiphers.jsp @@ -0,0 +1,92 @@ + +<%-- + 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. +--%> +<%@page session="false" contentType="text/html; charset=ISO-8859-1" %> +<%@page import="java.util.Map" %> +<%@page import="java.util.Map.Entry" %> +<%@page import="java.util.List" %> + + + +<% Map> cipherList = (Map>) request.getAttribute("cipherList"); +%> + + + + + + + + + Configured ciphers per Connector + + +

    Configured ciphers per Connector

    + + + + + + + + + + <% + for (Map.Entry> entry : cipherList.entrySet()) { + %> + + + + + <% + } + %> + +
    Connector / TLS Virtual HostEnabled Ciphers
    <%=entry.getKey()%> + <% + for (String cipher : entry.getValue()) { + %> +

    <%=cipher%>

    + <% + } + %> +
    + +
    +

    + +

    +
    + +<%--div style="display: none;"> +

    + Valid HTML 4.01! + Valid XHTML 1.0! + Valid XHTML 1.1! +

    + + + + diff --git a/tomcat/manager/WEB-INF/jsp/connectorTrustedCerts.jsp b/tomcat/manager/WEB-INF/jsp/connectorTrustedCerts.jsp new file mode 100644 index 0000000..bdf7ac4 --- /dev/null +++ b/tomcat/manager/WEB-INF/jsp/connectorTrustedCerts.jsp @@ -0,0 +1,92 @@ + +<%-- + 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. +--%> +<%@page session="false" contentType="text/html; charset=ISO-8859-1" %> +<%@page import="java.util.Map" %> +<%@page import="java.util.Map.Entry" %> +<%@page import="java.util.List" %> + + + +<% Map> trustedCertList = (Map>) request.getAttribute("trustedCertList"); +%> + + + + + + + + + Trusted certificates per Connector + + +

    Trusted certificates per Connector

    + + + + + + + + + + <% + for (Map.Entry> entry : trustedCertList.entrySet()) { + %> + + + + + <% + } + %> + +
    Connector / TLS Virtual HostTrusted Certificates
    <%=entry.getKey()%> + <% + for (String cert : entry.getValue()) { + %> +
    <%=cert%>
    + <% + } + %> +
    + +
    +

    + +

    +
    + +<%--div style="display: none;"> +

    + Valid HTML 4.01! + Valid XHTML 1.0! + Valid XHTML 1.1! +

    + + + + diff --git a/tomcat/manager/WEB-INF/jsp/sessionDetail.jsp b/tomcat/manager/WEB-INF/jsp/sessionDetail.jsp new file mode 100644 index 0000000..1d25de9 --- /dev/null +++ b/tomcat/manager/WEB-INF/jsp/sessionDetail.jsp @@ -0,0 +1,197 @@ + +<%-- + 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. +--%> +<%@page session="false" contentType="text/html; charset=ISO-8859-1" %> +<%@page import="java.util.Enumeration" %> +<%@page import="javax.servlet.http.HttpSession" %> +<%@page import="org.apache.catalina.Session" %> +<%@page import="org.apache.catalina.manager.JspHelper" %> +<%@page import="org.apache.catalina.util.ContextName" %> + +<%--!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" + "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"--%> + + +<% String path = (String) request.getAttribute("path"); + String version = (String) request.getAttribute("version"); + ContextName cn = new ContextName(path, version); + Session currentSession = (Session)request.getAttribute("currentSession"); + String currentSessionId = null; + HttpSession currentHttpSession = null; + if (currentSession != null) { + currentHttpSession = currentSession.getSession(); + currentSessionId = JspHelper.escapeXml(currentSession.getId()); + } else { + currentSessionId = "Session invalidated"; + } + String submitUrl = JspHelper.escapeXml(response.encodeURL( + ((HttpServletRequest) pageContext.getRequest()).getRequestURI() + + "?path=" + path + "&version=" + version)); +%> + + + + + + + + + + Sessions Administration: details for <%= currentSessionId %> + + +<% if (currentHttpSession == null) { %> +

    <%=currentSessionId%>

    +<% } else { %> +

    Details for Session <%= currentSessionId %>

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Session Id<%= currentSessionId %>
    Guessed Locale<%= JspHelper.guessDisplayLocaleFromSession(currentSession) %>
    Guessed User<%= JspHelper.guessDisplayUserFromSession(currentSession) %>
    Creation Time<%= JspHelper.getDisplayCreationTimeForSession(currentSession) %>
    Last Accessed Time<%= JspHelper.getDisplayLastAccessedTimeForSession(currentSession) %>
    Session Max Inactive Interval<%= JspHelper.secondsToTimeString(currentSession.getMaxInactiveInterval()) %>
    Used Time<%= JspHelper.getDisplayUsedTimeForSession(currentSession) %>
    Inactive Time<%= JspHelper.getDisplayInactiveTimeForSession(currentSession) %>
    TTL<%= JspHelper.getDisplayTTLForSession(currentSession) %>
    + +
    +
    + + + <% + if ("Primary".equals(request.getParameter("sessionType"))) { + %> + + <% + } + %> +
    +
    + +
    <%= JspHelper.escapeXml(request.getAttribute("error")) %>
    +
    <%= JspHelper.escapeXml(request.getAttribute("message")) %>
    + + + <% int nAttributes = 0; + Enumeration attributeNamesEnumeration = currentHttpSession.getAttributeNames(); + while (attributeNamesEnumeration.hasMoreElements()) { + attributeNamesEnumeration.nextElement(); + ++nAttributes; + } + %> + + + + + + + + + <%--tfoot> + + + + + + <% attributeNamesEnumeration = currentHttpSession.getAttributeNames(); + while (attributeNamesEnumeration.hasMoreElements()) { + String attributeName = (String) attributeNamesEnumeration.nextElement(); + %> + + + + + + <% } // end while %> + +
    <%= JspHelper.formatNumber(nAttributes) %> attributes
    Remove AttributeAttribute nameAttribute value
    + TODO: set Max Inactive Interval on sessions +
    +
    +
    + + + + <% + if ("Primary".equals(request.getParameter("sessionType"))) { + %> + + + <% + } else { + out.print("Primary sessions only"); + } + %> +
    +
    +
    <%= JspHelper.escapeXml(attributeName) %><% Object attributeValue = currentHttpSession.getAttribute(attributeName); %>"><%= JspHelper.escapeXml(attributeValue) %>
    +<% } // endif%> + +
    +

    + +

    +
    + +<%--div style="display: none;"> +

    + Valid HTML 4.01! + Valid XHTML 1.0! + Valid XHTML 1.1! +

    + + + + diff --git a/tomcat/manager/WEB-INF/jsp/sessionsList.jsp b/tomcat/manager/WEB-INF/jsp/sessionsList.jsp new file mode 100644 index 0000000..b61d07c --- /dev/null +++ b/tomcat/manager/WEB-INF/jsp/sessionsList.jsp @@ -0,0 +1,170 @@ + +<%-- + 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. +--%> +<%@page session="false" contentType="text/html; charset=ISO-8859-1" %> +<%@page import="java.util.Collection" %> +<%@page import="org.apache.catalina.manager.JspHelper" %> +<%@page import="org.apache.catalina.Session" %> +<%@page import="org.apache.catalina.ha.session.DeltaSession" %> +<%@page import="org.apache.catalina.util.ContextName" %> + + + +<%@page import="org.apache.catalina.manager.DummyProxySession"%> +<% String path = (String) request.getAttribute("path"); + String version = (String) request.getAttribute("version"); + ContextName cn = new ContextName(path, version); + String submitUrl = JspHelper.escapeXml(response.encodeURL( + ((HttpServletRequest) pageContext.getRequest()).getRequestURI() + + "?path=" + path + "&version=" + version)); + Collection activeSessions = (Collection) request.getAttribute("activeSessions"); +%> + + + + + + + + + + Sessions Administration for <%= JspHelper.escapeXml(cn.getDisplayName()) %> + + +

    Sessions Administration for <%= JspHelper.escapeXml(cn.getDisplayName()) %>

    + +

    Tips:

    +
      +
    • Click on a column to sort.
    • +
    • To view a session details and/or remove a session attributes, click on its id.
    • +
    + +
    <%= JspHelper.escapeXml(request.getAttribute("error")) %>
    +
    <%= JspHelper.escapeXml(request.getAttribute("message")) %>
    + +
    +
    Active HttpSessions informations + + "/> + <% String order = (String) request.getAttribute("order"); + if (order == null || "".equals(order)) { + order = "ASC"; + } + %> + + + <%= JspHelper.formatNumber(activeSessions.size()) %> active Sessions
    + + + + + + + + + + + + + + + <% if (activeSessions.size() > 10) { %> + <%-- is the same as --%> + + + + + + + + + + + + + <% } // end if %> + +<% + for (Session currentSession : activeSessions) { + String currentSessionId = JspHelper.escapeXml(currentSession.getId()); + String type; + if (currentSession instanceof DeltaSession) { + if (((DeltaSession) currentSession).isPrimarySession()) { + type = "Primary"; + } else { + type = "Backup"; + } + } else if (currentSession instanceof DummyProxySession) { + type = "Proxy"; + } else { + type = "Primary"; + } +%> + + + + + + + + + + + +<% } // end while %> + +
    Session IdTypeGuessed LocaleGuessed User nameCreation TimeLast Accessed TimeUsed TimeInactive TimeTTL
    Session IdTypeGuessed LocaleGuessed User nameCreation TimeLast Accessed TimeUsed TimeInactive TimeTTL
    + <% + if ("Proxy".equals(type)) { + out.print(currentSessionId); + } else { + %> + <%= currentSessionId %> + <% + } + %> + <%= type %><%= JspHelper.guessDisplayLocaleFromSession(currentSession) %><%= JspHelper.guessDisplayUserFromSession(currentSession) %><%= JspHelper.getDisplayCreationTimeForSession(currentSession) %><%= JspHelper.getDisplayLastAccessedTimeForSession(currentSession) %><%= JspHelper.getDisplayUsedTimeForSession(currentSession) %><%= JspHelper.getDisplayInactiveTimeForSession(currentSession) %><%= JspHelper.getDisplayTTLForSession(currentSession) %>
    +

    + +

    +
    +
    + +
    +

    + +

    +
    + +<%--div style="display: none;"> +

    + Valid HTML 4.01! + Valid XHTML 1.0! + Valid XHTML 1.1! +

    + + + + diff --git a/tomcat/manager/WEB-INF/web.xml b/tomcat/manager/WEB-INF/web.xml new file mode 100644 index 0000000..d91728e --- /dev/null +++ b/tomcat/manager/WEB-INF/web.xml @@ -0,0 +1,207 @@ + + + + + Tomcat Manager Application + + A scriptable management web application for the Tomcat Web Server; + Manager lets you view, load/unload/etc particular web applications. + + + + Manager + org.apache.catalina.manager.ManagerServlet + + debug + 2 + + + + HTMLManager + org.apache.catalina.manager.HTMLManagerServlet + + debug + 2 + + + + + 52428800 + 52428800 + 0 + + + + Status + org.apache.catalina.manager.StatusManagerServlet + + debug + 0 + + + + + JMXProxy + org.apache.catalina.manager.JMXProxyServlet + + + + + Manager + /text/* + + + Status + /status/* + + + JMXProxy + /jmxproxy/* + + + HTMLManager + /html/* + + + + SetCharacterEncoding + org.apache.catalina.filters.SetCharacterEncodingFilter + + encoding + UTF-8 + + + + + SetCharacterEncoding + /* + + + + CSRF + org.apache.catalina.filters.CsrfPreventionFilter + + entryPoints + /html,/html/,/html/list,/index.jsp + + + + + CSRF + HTMLManager + + + + + + + HTML Manager interface (for humans) + /html/* + + + manager-gui + + + + + Text Manager interface (for scripts) + /text/* + + + manager-script + + + + + JMX Proxy interface + /jmxproxy/* + + + manager-jmx + + + + + Status interface + /status/* + + + manager-gui + manager-script + manager-jmx + manager-status + + + + + + BASIC + Tomcat Manager Application + + + + + + The role that is required to access the HTML Manager pages + + manager-gui + + + + The role that is required to access the text Manager pages + + manager-script + + + + The role that is required to access the HTML JMX Proxy + + manager-jmx + + + + The role that is required to access to the Manager Status pages + + manager-status + + + + 401 + /WEB-INF/jsp/401.jsp + + + 403 + /WEB-INF/jsp/403.jsp + + + 404 + /WEB-INF/jsp/404.jsp + + + diff --git a/tomcat/manager/images/asf-logo.svg b/tomcat/manager/images/asf-logo.svg new file mode 100644 index 0000000..e24cbe5 --- /dev/null +++ b/tomcat/manager/images/asf-logo.svg @@ -0,0 +1,226 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tomcat/manager/images/tomcat.gif b/tomcat/manager/images/tomcat.gif new file mode 100644 index 0000000..f2aa6f8 Binary files /dev/null and b/tomcat/manager/images/tomcat.gif differ diff --git a/tomcat/manager/index.jsp b/tomcat/manager/index.jsp new file mode 100644 index 0000000..2806b76 --- /dev/null +++ b/tomcat/manager/index.jsp @@ -0,0 +1,18 @@ +<%-- + 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. +--%> +<%@ page session="false" trimDirectiveWhitespaces="true" %> +<% response.sendRedirect(request.getContextPath() + "/html"); %> \ No newline at end of file diff --git a/tomcat/manager/status.xsd b/tomcat/manager/status.xsd new file mode 100644 index 0000000..5af979d --- /dev/null +++ b/tomcat/manager/status.xsd @@ -0,0 +1,84 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tomcat/manager/xform.xsl b/tomcat/manager/xform.xsl new file mode 100644 index 0000000..06ced01 --- /dev/null +++ b/tomcat/manager/xform.xsl @@ -0,0 +1,125 @@ + + + + + + + + + + + + Tomcat Status + + + +
    Tomcat Status
    + + + + + +
    + + + + Memory Pools
    + +
    +
    + + + + + + + + +
    JVM:free: total: max:

    +
    + + + + + + + + + + +
    Name: Type: Initial: Committed: Maximum: Used:
    +
    + + + Connector --
    + + + + +
    + + + + + + + + +
    threadInfomaxThreads: currentThreadCount: currentThreadsBusy:

    +
    + + + + + + + + + + + +
    requestInfo maxTime: processingTime: requestCount: errorCount: bytesReceived: bytesSent:

    +
    + + + + + + +
    StageTimeB SentB RecvClientVHostRequest

    +
    + + + + + + + + + + ? + + + +