Merge remote-tracking branch 'eclipse/jetty-9.4.x' into jetty-9.4.x-300-CompressionPool

Signed-off-by: Lachlan Roberts <lachlan@webtide.com>
This commit is contained in:
Lachlan Roberts 2019-07-04 10:19:37 +10:00
commit 50c18798ba
159 changed files with 2080 additions and 781 deletions

24
Jenkinsfile vendored
View File

@ -64,7 +64,7 @@ pipeline {
agent { node { label 'linux' } }
options { timeout(time: 30, unit: 'MINUTES') }
steps {
mavenBuild("jdk11", "install javadoc:javadoc -DskipTests", "maven3", true)
mavenBuild("jdk11", "install javadoc:javadoc javadoc:aggregate-jar -DskipTests", "maven3", true)
warnings consoleParsers: [[parserName: 'Maven'], [parserName: 'JavaDoc'], [parserName: 'Java']]
}
}
@ -73,7 +73,7 @@ pipeline {
agent { node { label 'linux' } }
options { timeout(time: 30, unit: 'MINUTES') }
steps {
mavenBuild("jdk11", "install checkstyle:checkstyle -DskipTests", "maven3", true)
mavenBuild("jdk11", "install checkstyle:check -DskipTests", "maven3", true)
recordIssues(
enabledForFailure: true, aggregatingResults: true,
tools: [java(), checkStyle(pattern: '**/target/checkstyle-result.xml', reportEncoding: 'UTF-8')]
@ -92,7 +92,6 @@ pipeline {
}
}
}
/*
post {
failure {
slackNotif()
@ -104,24 +103,29 @@ pipeline {
slackNotif()
}
}
*/
}
/*
def slackNotif() {
script {
if (env.BRANCH_NAME=='jetty-10.0.x' ||
env.BRANCH_NAME=='jetty-9.4.x') {
try
{
if ( env.BRANCH_NAME == 'jetty-10.0.x' || env.BRANCH_NAME == 'jetty-9.4.x' )
{
//BUILD_USER = currentBuild.rawBuild.getCause(Cause.UserIdCause).getUserId()
// by ${BUILD_USER}
COLOR_MAP = ['SUCCESS': 'good', 'FAILURE': 'danger', 'UNSTABLE': 'danger', 'ABORTED': 'danger']
slackSend channel: '#jenkins',
color: COLOR_MAP[currentBuild.currentResult],
message: "*${currentBuild.currentResult}:* Job ${env.JOB_NAME} build ${env.BUILD_NUMBER} - ${env.BUILD_URL}"
color: COLOR_MAP[currentBuild.currentResult],
message: "*${currentBuild.currentResult}:* Job ${env.JOB_NAME} build ${env.BUILD_NUMBER} - ${env.BUILD_URL}"
}
} catch (Exception e) {
e.printStackTrace()
echo "skip failure slack notification: " + e.getMessage()
}
}
}
*/
/**
* To other developers, if you are using this method above, please use the following syntax.

View File

@ -25,11 +25,13 @@
<setting id="org.eclipse.jdt.core.formatter.parentheses_positions_in_enum_constant_declaration" value="common_lines"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_arrow_in_switch_default" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.align_with_spaces" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.disabling_tag" value="@formatter:off"/>
<setting id="org.eclipse.jdt.core.formatter.continuation_indentation" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_switch_case_expressions" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_enum_constants" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_imports" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_after_package" value="1"/>
@ -45,13 +47,14 @@
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_arrow_in_switch_case" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_before_multiplicative_operator" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments" value="do not insert"/>
@ -106,6 +109,7 @@
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_relational_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_multiplicative_operator" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.keep_anonymous_type_declaration_on_one_line" value="one_line_never"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_switch_case_expressions" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_before_shift_operator" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces" value="insert"/>
@ -120,7 +124,7 @@
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_bitwise_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration" value="18"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_type_parameters" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation" value="16"/>
@ -135,7 +139,7 @@
<setting id="org.eclipse.jdt.core.formatter.alignment_for_relational_operator" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_unary_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer" value="32"/>
<setting id="org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.parentheses_positions_in_annotation" value="common_lines"/>
@ -152,7 +156,7 @@
<setting id="org.eclipse.jdt.core.formatter.comment.format_line_comments" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.align_type_members_on_columns" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_assignment" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_assignment" value="80"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_module_statements" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration" value="do not insert"/>
@ -162,7 +166,7 @@
<setting id="org.eclipse.jdt.core.formatter.keep_if_then_body_block_on_one_line" value="one_line_never"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_conditional_expression" value="80"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if" value="insert"/>
@ -171,8 +175,9 @@
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration" value="next_line"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_block_in_case" value="next_line"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_arrow_in_switch_default" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_conditional_expression_chain" value="0"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_conditional_expression_chain" value="48"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_header" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_additive_operator" value="insert"/>
@ -192,7 +197,7 @@
<setting id="org.eclipse.jdt.core.formatter.alignment_for_bitwise_operator" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration" value="next_line"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_resources_in_try" value="80"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_resources_in_try" value="83"/>
<setting id="org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.parentheses_positions_in_try_clause" value="common_lines"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation" value="16"/>
@ -206,7 +211,7 @@
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_source_code" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_field" value="0"/>
@ -223,7 +228,7 @@
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_type_annotation" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.comment.format_html" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration" value="do not insert"/>
@ -244,7 +249,7 @@
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_label" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_label" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration" value="do not insert"/>
@ -253,6 +258,7 @@
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_arrow_in_switch_case" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_member_type" value="1"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement" value="insert"/>
@ -260,7 +266,7 @@
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_before_bitwise_operator" value="false"/>
@ -277,7 +283,7 @@
<setting id="org.eclipse.jdt.core.formatter.comment.indent_tag_description" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration" value="16"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration" value="18"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.alignment_for_string_concatenation" value="16"/>
@ -289,7 +295,7 @@
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.keep_simple_while_body_on_same_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator" value="do not insert"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_array_initializer" value="next_line"/>
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_array_initializer" value="next_line_on_wrap"/>
<setting id="org.eclipse.jdt.core.formatter.wrap_before_logical_operator" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_shift_operator" value="insert"/>
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration" value="insert"/>

View File

@ -14,6 +14,12 @@
<property name="fileExtensions" value="java"/>
<!-- reference to suppressions filter for both eclipse and intellij checkstyle plugins -->
<module name="SuppressionFilter">
<property name="file" value="${checkstyle.suppressions.file}"/>
<property name="optional" value="true"/>
</module>
<!-- Excludes all 'module-info.java' files -->
<!-- See https://checkstyle.org/config_filefilters.html -->
<module name="BeforeExecutionExclusionFileFilter">

View File

@ -0,0 +1,35 @@
<?xml version="1.0"?>
<!DOCTYPE suppressions PUBLIC
"-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN"
"https://checkstyle.org/dtds/suppressions_1_2.dtd">
<suppressions>
<!-- all /target/ directories -->
<suppress checks=".*" files="[/\\]target[/\\]generated-sources[/\\]" />
<!-- General JUnit Test Cases -->
<suppress checks="AbbreviationAsWordInNameCheck"
files="[/\\]src[/\\]test[/\\]java[/\\]" />
<suppress checks="AvoidEscapedUnicodeCharactersCheck"
files="[/\\]src[/\\]test[/\\]java[/\\]" />
<suppress checks="LocalVariableNameCheck"
files="[/\\]src[/\\]test[/\\]java[/\\]" />
<suppress checks="MethodNameCheck"
files="[/\\]src[/\\]test[/\\]java[/\\]" />
<suppress checks="TypeNameCheck"
files="[/\\]src[/\\]test[/\\]java[/\\]" />
<!-- jetty-jmh specific -->
<suppress checks="AbbreviationAsWordInNameCheck"
files="[/\\]jetty-jmh[/\\]src[/\\]main[/\\]java[/\\]" />
<suppress checks="AvoidEscapedUnicodeCharactersCheck"
files="[/\\]jetty-jmh[/\\]src[/\\]main[/\\]java[/\\]" />
<suppress checks="LocalVariableNameCheck"
files="[/\\]jetty-jmh[/\\]src[/\\]main[/\\]java[/\\]" />
<suppress checks="MethodNameCheck"
files="[/\\]jetty-jmh[/\\]src[/\\]main[/\\]java[/\\]" />
<suppress checks="TypeNameCheck"
files="[/\\]jetty-jmh[/\\]src[/\\]main[/\\]java[/\\]" />
</suppressions>

View File

@ -1153,5 +1153,3 @@ public class AnnotationConfiguration extends AbstractConfiguration
}
}
}

View File

@ -19,14 +19,19 @@
package org.eclipse.jetty.annotations;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* AnnotationIntrospector
* Introspects a class to find various types of
* annotations as defined by the servlet specification.
*/
public class AnnotationIntrospector
{
protected List<IntrospectableAnnotationHandler> _handlers = new ArrayList<IntrospectableAnnotationHandler>();
private final Set<Class<?>> _introspectedClasses = new HashSet<>();
private final List<IntrospectableAnnotationHandler> _handlers = new ArrayList<IntrospectableAnnotationHandler>();
/**
* IntrospectableAnnotationHandler
@ -84,19 +89,31 @@ public class AnnotationIntrospector
if (clazz == null)
return;
for (IntrospectableAnnotationHandler handler : _handlers)
synchronized (_introspectedClasses)
{
try
//Synchronize on the set of already introspected classes.
//This ensures that only 1 thread can be introspecting, and that
//thread must have fully finished generating the products of
//introspection before another thread is allowed in.
//We remember the classes that we have introspected to avoid
//reprocessing the same class.
if (_introspectedClasses.add(clazz))
{
handler.handle(clazz);
}
catch (RuntimeException e)
{
throw e;
}
catch (Exception e)
{
throw new RuntimeException(e);
for (IntrospectableAnnotationHandler handler : _handlers)
{
try
{
handler.handle(clazz);
}
catch (RuntimeException e)
{
throw e;
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
}
}
}

View File

@ -70,8 +70,7 @@ public class PostConstructAnnotationHandler extends AbstractIntrospectableAnnota
origin == Origin.WebOverride))
return;
PostConstructCallback callback = new PostConstructCallback();
callback.setTarget(clazz.getName(), m.getName());
PostConstructCallback callback = new PostConstructCallback(clazz, m.getName());
LifeCycleCallbackCollection lifecycles = (LifeCycleCallbackCollection)_context.getAttribute(LifeCycleCallbackCollection.LIFECYCLE_CALLBACK_COLLECTION);
if (lifecycles == null)
{

View File

@ -70,8 +70,7 @@ public class PreDestroyAnnotationHandler extends AbstractIntrospectableAnnotatio
origin == Origin.WebOverride))
return;
PreDestroyCallback callback = new PreDestroyCallback();
callback.setTarget(clazz.getName(), m.getName());
PreDestroyCallback callback = new PreDestroyCallback(clazz, m.getName());
LifeCycleCallbackCollection lifecycles = (LifeCycleCallbackCollection)_context.getAttribute(LifeCycleCallbackCollection.LIFECYCLE_CALLBACK_COLLECTION);
if (lifecycles == null)

View File

@ -42,7 +42,8 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH
private static final Logger LOG = Log.getLogger(ResourceAnnotationHandler.class);
protected static final List<Class<?>> ENV_ENTRY_TYPES =
Arrays.asList(new Class[]{
Arrays.asList(new Class[]
{
String.class, Character.class, Integer.class, Boolean.class, Double.class, Byte.class, Short.class, Long.class,
Float.class
});
@ -125,7 +126,7 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH
}
//work out default name
String name = clazz.getCanonicalName() + "/" + field.getName();
String name = clazz.getName() + "/" + field.getName();
//allow @Resource name= to override the field name
name = (resource.name() != null && !resource.name().trim().equals("") ? resource.name() : name);
@ -183,10 +184,7 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH
{
LOG.debug("Bound " + (mappedName == null ? name : mappedName) + " as " + name);
// Make the Injection for it if the binding succeeded
injection = new Injection();
injection.setTarget(clazz, field, type);
injection.setJndiName(name);
injection.setMappingName(mappedName);
injection = new Injection(clazz, field, type, name, mappedName);
injections.add(injection);
//TODO - an @Resource is equivalent to a resource-ref, resource-env-ref, message-destination
@ -275,7 +273,7 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH
//default name is the javabean property name
String name = method.getName().substring(3);
name = name.substring(0, 1).toLowerCase(Locale.ENGLISH) + name.substring(1);
name = clazz.getCanonicalName() + "/" + name;
name = clazz.getName() + "/" + name;
name = (resource.name() != null && !resource.name().trim().equals("") ? resource.name() : name);
String mappedName = (resource.mappedName() != null && !resource.mappedName().trim().equals("") ? resource.mappedName() : null);
@ -339,10 +337,7 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH
{
LOG.debug("Bound " + (mappedName == null ? name : mappedName) + " as " + name);
// Make the Injection for it
injection = new Injection();
injection.setTarget(clazz, method, paramType, resourceType);
injection.setJndiName(name);
injection.setMappingName(mappedName);
injection = new Injection(clazz, method, paramType, resourceType, name, mappedName);
injections.add(injection);
//TODO - an @Resource is equivalent to a resource-ref, resource-env-ref, message-destination
metaData.setOrigin("resource-ref." + name + ".injection", resource, clazz);

View File

@ -64,9 +64,7 @@ public class RunAsAnnotationHandler extends AbstractIntrospectableAnnotationHand
if (d == null)
{
metaData.setOrigin(holder.getName() + ".servlet.run-as", runAs, clazz);
org.eclipse.jetty.plus.annotation.RunAs ra = new org.eclipse.jetty.plus.annotation.RunAs();
ra.setTargetClassName(clazz.getCanonicalName());
ra.setRoleName(role);
org.eclipse.jetty.plus.annotation.RunAs ra = new org.eclipse.jetty.plus.annotation.RunAs(clazz.getName(), role);
RunAsCollection raCollection = (RunAsCollection)_context.getAttribute(RunAsCollection.RUNAS_COLLECTION);
if (raCollection == null)
{

View File

@ -20,4 +20,3 @@
* Jetty Annotations : Support for Servlet Annotations
*/
package org.eclipse.jetty.annotations;

View File

@ -1,4 +1,3 @@
package org.acme;
//
// ========================================================================
// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
@ -17,6 +16,8 @@ package org.acme;
// ========================================================================
//
package org.acme;
/**
* ClassOne
*/

View File

@ -29,5 +29,3 @@ public @interface Multi
{
String[] value();
}

View File

@ -29,4 +29,3 @@ public @interface Sample
{
int value();
}

View File

@ -42,7 +42,8 @@ import javax.servlet.http.HttpServletResponse;
@MultipartConfig(fileSizeThreshold = 1000, maxFileSize = 2000, maxRequestSize = 3000)
@RunAs("admin")
@ServletSecurity(value = @HttpConstraint(rolesAllowed = {"fred", "bill", "dorothy"}), httpMethodConstraints = {
@HttpMethodConstraint(value = "GET", rolesAllowed = {"bob", "carol", "ted"})
@HttpMethodConstraint(value = "GET", rolesAllowed =
{"bob", "carol", "ted"})
})
public class ServletC extends HttpServlet
{

View File

@ -110,8 +110,7 @@ public class TestAnnotationParser
@Test
public void testSampleAnnotation() throws Exception
{
String[] classNames = new String[]
{"org.eclipse.jetty.annotations.ClassA"};
String[] classNames = new String[]{"org.eclipse.jetty.annotations.ClassA"};
AnnotationParser parser = new AnnotationParser();
class SampleAnnotationHandler extends AnnotationParser.AbstractHandler
@ -157,8 +156,7 @@ public class TestAnnotationParser
@Test
public void testMultiAnnotation() throws Exception
{
String[] classNames = new String[]
{"org.eclipse.jetty.annotations.ClassB"};
String[] classNames = new String[]{"org.eclipse.jetty.annotations.ClassB"};
AnnotationParser parser = new AnnotationParser();
class MultiAnnotationHandler extends AnnotationParser.AbstractHandler

View File

@ -46,31 +46,36 @@ public class TestSecurityAnnotationConversions
{
@ServletSecurity(value = @HttpConstraint(value = EmptyRoleSemantic.DENY))
public static class DenyServlet extends HttpServlet
{}
{
}
@ServletSecurity
public static class PermitServlet extends HttpServlet
{}
{
}
@ServletSecurity(value = @HttpConstraint(value = EmptyRoleSemantic.PERMIT, transportGuarantee = TransportGuarantee.CONFIDENTIAL, rolesAllowed = {
"tom", "dick", "harry"
}))
public static class RolesServlet extends HttpServlet
{}
{
}
@ServletSecurity(value = @HttpConstraint(value = EmptyRoleSemantic.PERMIT, transportGuarantee = TransportGuarantee.CONFIDENTIAL, rolesAllowed = {
"tom", "dick", "harry"
}),
httpMethodConstraints = {@HttpMethodConstraint(value = "GET")})
}), httpMethodConstraints =
{@HttpMethodConstraint(value = "GET")})
public static class Method1Servlet extends HttpServlet
{}
{
}
@ServletSecurity(value = @HttpConstraint(value = EmptyRoleSemantic.PERMIT, transportGuarantee = TransportGuarantee.CONFIDENTIAL, rolesAllowed = {
"tom", "dick", "harry"
}),
httpMethodConstraints = {@HttpMethodConstraint(value = "GET", transportGuarantee = TransportGuarantee.CONFIDENTIAL)})
}), httpMethodConstraints =
{@HttpMethodConstraint(value = "GET", transportGuarantee = TransportGuarantee.CONFIDENTIAL)})
public static class Method2Servlet extends HttpServlet
{}
{
}
public void setUp()
{

View File

@ -20,6 +20,7 @@ package org.eclipse.jetty.annotations.resources;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Set;
import javax.naming.Context;
import javax.naming.InitialContext;
@ -99,16 +100,16 @@ public class TestResourceAnnotations
//we should have Injections
assertNotNull(injections);
List<Injection> resBInjections = injections.getInjections(ResourceB.class.getCanonicalName());
Set<Injection> resBInjections = injections.getInjections(ResourceB.class.getName());
assertNotNull(resBInjections);
//only 1 field injection because the other has no Resource mapping
assertEquals(1, resBInjections.size());
Injection fi = resBInjections.get(0);
Injection fi = resBInjections.iterator().next();
assertEquals("f", fi.getTarget().getName());
//3 method injections on class ResourceA, 4 field injections
List<Injection> resAInjections = injections.getInjections(ResourceA.class.getCanonicalName());
Set<Injection> resAInjections = injections.getInjections(ResourceA.class.getName());
assertNotNull(resAInjections);
assertEquals(7, resAInjections.size());
int fieldCount = 0;

View File

@ -89,8 +89,8 @@ public class GlobalWebappConfigBindingTest
WebAppContext context = contexts.get(0);
assertNotNull(context, "Context should not be null");
String defaultClasses[] = context.getDefaultServerClasses();
String currentClasses[] = context.getServerClasses();
String[] defaultClasses = context.getDefaultServerClasses();
String[] currentClasses = context.getServerClasses();
String addedClass = "org.eclipse.foo."; // What was added by the binding
assertThat("Default Server Classes", addedClass, not(is(in(defaultClasses))));

View File

@ -309,7 +309,7 @@ public class XmlConfiguredJetty
{
List<WebAppContext> contexts = new ArrayList<>();
HandlerCollection handlers = (HandlerCollection)_server.getHandler();
Handler children[] = handlers.getChildHandlers();
Handler[] children = handlers.getChildHandlers();
for (Handler handler : children)
{
@ -396,7 +396,7 @@ public class XmlConfiguredJetty
// Find the active server port.
_serverPort = -1;
Connector connectors[] = _server.getConnectors();
Connector[] connectors = _server.getConnectors();
for (int i = 0; _serverPort < 0 && i < connectors.length; i++)
{
if (connectors[i] instanceof NetworkConnector)

View File

@ -1285,8 +1285,8 @@ public class HttpParser
_string.setLength(0);
_string.append(t.getChar());
_length = 1;
break;
}
break;
default:
throw new IllegalCharacterException(_state, t, buffer);

View File

@ -90,7 +90,7 @@ public class HttpCookieTest
httpCookie = new HttpCookie("everything", "value", "domain", "path", 0, true, true, null, -1);
assertEquals("everything=value; Path=path; Domain=domain; Expires=Thu, 01-Jan-1970 00:00:00 GMT; Max-Age=0; Secure; HttpOnly", httpCookie.getRFC6265SetCookie());
String badNameExamples[] = {
String[] badNameExamples = {
"\"name\"",
"name\t",
"na me",
@ -118,7 +118,7 @@ public class HttpCookieTest
}
}
String badValueExamples[] = {
String[] badValueExamples = {
"va\tlue",
"\t",
"value\u0000",
@ -147,7 +147,7 @@ public class HttpCookieTest
}
}
String goodNameExamples[] = {
String[] goodNameExamples = {
"name",
"n.a.m.e",
"na-me",
@ -163,7 +163,7 @@ public class HttpCookieTest
// should not throw an exception
}
String goodValueExamples[] = {
String[] goodValueExamples = {
"value",
"",
null,

View File

@ -245,7 +245,7 @@ public class MultiPartCaptureTest
continue;
}
String split[] = line.split("\\|");
String[] split = line.split("\\|");
switch (split[0])
{
case "Request-Header":

View File

@ -30,7 +30,7 @@ public class SyntaxTest
@Test
public void testRequireValidRFC2616Token_Good()
{
String tokens[] = {
String[] tokens = {
"name",
"",
null,
@ -52,7 +52,7 @@ public class SyntaxTest
@Test
public void testRequireValidRFC2616Token_Bad()
{
String tokens[] = {
String[] tokens = {
"\"name\"",
"name\t",
"na me",
@ -83,7 +83,7 @@ public class SyntaxTest
@Test
public void testRequireValidRFC6265CookieValue_Good()
{
String values[] = {
String[] values = {
"value",
"",
null,
@ -104,7 +104,7 @@ public class SyntaxTest
@Test
public void testRequireValidRFC6265CookieValue_Bad()
{
String values[] = {
String[] values = {
"va\tlue",
"\t",
"value\u0000",

View File

@ -33,7 +33,7 @@ public class UriTemplatePathSpecBadSpecsTest
{
public static Stream<Arguments> data()
{
String badSpecs[] = new String[]{
String[] badSpecs = new String[]{
"/a/b{var}", // bad syntax - variable does not encompass whole path segment
"a/{var}", // bad syntax - no start slash
"/a/{var/b}", // path segment separator in variable name

View File

@ -18,15 +18,16 @@
package org.eclipse.jetty.jaas.spi;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import org.eclipse.jetty.security.AbstractLoginService;
import org.eclipse.jetty.security.PropertyUserStore;
import org.eclipse.jetty.server.UserIdentity;
import org.eclipse.jetty.util.log.Log;
@ -116,14 +117,11 @@ public class PropertyFileLoginModule extends AbstractLoginModule
//TODO in future versions change the impl of PropertyUserStore so its not
//storing Subjects etc, just UserInfo
Set<Principal> principals = userIdentity.getSubject().getPrincipals();
Set<AbstractLoginService.RolePrincipal> principals = userIdentity.getSubject().getPrincipals(AbstractLoginService.RolePrincipal.class);
List<String> roles = new ArrayList<String>();
for (Principal principal : principals)
{
roles.add(principal.getName());
}
List<String> roles = principals.stream()
.map(AbstractLoginService.RolePrincipal::getName)
.collect(Collectors.toList());
Credential credential = (Credential)userIdentity.getSubject().getPrivateCredentials().iterator().next();
LOG.debug("Found: " + userName + " in PropertyUserStore " + _filename);

View File

@ -0,0 +1,53 @@
//
// ========================================================================
// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.jaas.spi;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.File;
import java.util.HashMap;
import javax.security.auth.Subject;
import org.eclipse.jetty.jaas.callback.DefaultCallbackHandler;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.junit.jupiter.api.Test;
public class PropertyFileLoginModuleTest
{
@Test
public void testRoles()
throws Exception
{
File file = MavenTestingUtils.getTestResourceFile("login.properties");
PropertyFileLoginModule module = new PropertyFileLoginModule();
Subject subject = new Subject();
HashMap<String, String> options = new HashMap<>();
options.put("file", file.getCanonicalPath());
module.initialize(subject, new DefaultCallbackHandler(), new HashMap<String, String>(), options);
UserInfo fred = module.getUserInfo("fred");
assertEquals("fred", fred.getUserName());
assertThat(fred.getRoleNames(), containsInAnyOrder("role1", "role2", "role3"));
assertThat(fred.getRoleNames(), not(contains("fred")));
}
}

View File

@ -0,0 +1 @@
fred=pwd,role1,role2,role3

View File

@ -25,6 +25,7 @@ import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.thread.ExecutionStrategy.Producer;
import org.eclipse.jetty.util.thread.Invocable;
import org.openjdk.jmh.infra.Blackhole;
@ -124,6 +125,7 @@ public class TestConnection implements Producer
}
catch (InterruptedException e)
{
Log.getLogger(TestConnection.class).ignore(e);
}
}
else

View File

@ -81,7 +81,6 @@ public class localContextRoot implements Context
}
}
/*
* Root has to use the localContextRoot's env for all operations.
* So, if createSubcontext in the root, use the env of the localContextRoot.

View File

@ -22,6 +22,7 @@ import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.util.Locale;
import java.util.Objects;
import javax.naming.InitialContext;
import javax.naming.NamingException;
@ -40,15 +41,70 @@ public class Injection
{
private static final Logger LOG = Log.getLogger(Injection.class);
private Class<?> _targetClass;
private String _jndiName;
private String _mappingName;
private Member _target;
private Class<?> _paramClass;
private Class<?> _resourceClass;
private final Class<?> _targetClass;
private final String _jndiName;
private final String _mappingName;
private final Member _target;
private final Class<?> _paramClass;
private final Class<?> _resourceClass;
public Injection()
public Injection(Class<?> clazz, Field field, Class<?> resourceType, String jndiName, String mappingName)
{
_targetClass = Objects.requireNonNull(clazz);
_target = Objects.requireNonNull(field);
_resourceClass = resourceType;
_paramClass = null;
_jndiName = jndiName;
_mappingName = mappingName;
}
public Injection(Class<?> clazz, Method method, Class<?> arg, Class<?> resourceType, String jndiName, String mappingName)
{
_targetClass = Objects.requireNonNull(clazz);
_target = Objects.requireNonNull(method);
_resourceClass = resourceType;
_paramClass = arg;
_jndiName = jndiName;
_mappingName = mappingName;
}
public Injection(Class<?> clazz, String target, Class<?> resourceType, String jndiName, String mappingName)
{
_targetClass = Objects.requireNonNull(clazz);
Objects.requireNonNull(target);
_resourceClass = resourceType;
_jndiName = jndiName;
_mappingName = mappingName;
Member tmpTarget = null;
Class<?> tmpParamClass = null;
//first look for a javabeans style setter matching the targetName
String setter = "set" + target.substring(0, 1).toUpperCase(Locale.ENGLISH) + target.substring(1);
try
{
if (LOG.isDebugEnabled())
LOG.debug("Looking for method for setter: " + setter + " with arg {}", _resourceClass);
tmpTarget = IntrospectionUtil.findMethod(clazz, setter, new Class[]{_resourceClass}, true, false);
tmpParamClass = _resourceClass;
}
catch (NoSuchMethodException nsme)
{
//try as a field
try
{
tmpTarget = IntrospectionUtil.findField(clazz, target, resourceType, true, false);
tmpParamClass = null;
}
catch (NoSuchFieldException nsfe)
{
nsme.addSuppressed(nsfe);
throw new IllegalArgumentException("No such field or method " + target + " on class " + _targetClass, nsme);
}
}
_target = tmpTarget;
_paramClass = tmpParamClass;
}
/**
@ -71,12 +127,12 @@ public class Injection
public boolean isField()
{
return (_target != null && _target instanceof Field);
return (Field.class.isInstance(_target));
}
public boolean isMethod()
{
return (_target != null && _target instanceof Method);
return (Method.class.isInstance(_target));
}
/**
@ -88,14 +144,7 @@ public class Injection
}
/**
* @param jndiName the jndiName to set
*/
public void setJndiName(String jndiName)
{
this._jndiName = jndiName;
}
/**
* @return the mappingName
*/
public String getMappingName()
@ -103,14 +152,6 @@ public class Injection
return _mappingName;
}
/**
* @param mappingName the mappingName to set
*/
public void setMappingName(String mappingName)
{
this._mappingName = mappingName;
}
/**
* @return the target
*/
@ -119,50 +160,6 @@ public class Injection
return _target;
}
public void setTarget(Class<?> clazz, Field field, Class<?> resourceType)
{
_targetClass = clazz;
_target = field;
_resourceClass = resourceType;
}
public void setTarget(Class<?> clazz, Method method, Class<?> arg, Class<?> resourceType)
{
_targetClass = clazz;
_target = method;
_resourceClass = resourceType;
_paramClass = arg;
}
public void setTarget(Class<?> clazz, String target, Class<?> resourceType)
{
_targetClass = clazz;
_resourceClass = resourceType;
//first look for a javabeans style setter matching the targetName
String setter = "set" + target.substring(0, 1).toUpperCase(Locale.ENGLISH) + target.substring(1);
try
{
LOG.debug("Looking for method for setter: " + setter + " with arg " + _resourceClass);
_target = IntrospectionUtil.findMethod(clazz, setter, new Class[]{_resourceClass}, true, false);
_targetClass = clazz;
_paramClass = _resourceClass;
}
catch (NoSuchMethodException ex)
{
//try as a field
try
{
_target = IntrospectionUtil.findField(clazz, target, resourceType, true, false);
_targetClass = clazz;
}
catch (NoSuchFieldException ex2)
{
throw new IllegalArgumentException("No such field or method " + target + " on class " + _targetClass);
}
}
}
/**
* Inject a value for a Resource from JNDI into an object
*
@ -170,15 +167,12 @@ public class Injection
*/
public void inject(Object injectable)
{
if (_target != null)
{
if (_target instanceof Field)
injectField((Field)_target, injectable);
else
injectMethod((Method)_target, injectable);
}
if (isField())
injectField((Field)_target, injectable);
else if (isMethod())
injectMethod((Method)_target, injectable);
else
throw new IllegalStateException("No method or field to inject with " + getJndiName());
throw new IllegalStateException("Neither field nor method injection");
}
/**

View File

@ -20,16 +20,24 @@ package org.eclipse.jetty.plus.annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
/**
* InjectionCollection
* Map of classname to all injections requested on that class,
* whether by declaration in web.xml or via equivalent annotations.
*
* This class is not threadsafe for concurrent modifications, but is
* threadsafe for readers with concurrent modifications.
*/
public class InjectionCollection
{
@ -37,26 +45,34 @@ public class InjectionCollection
public static final String INJECTION_COLLECTION = "org.eclipse.jetty.injectionCollection";
private HashMap<String, List<Injection>> _injectionMap = new HashMap<String, List<Injection>>();//map of classname to injections
private final ConcurrentMap<String, Set<Injection>> _injectionMap = new ConcurrentHashMap<>();//map of classname to injections
public void add(Injection injection)
{
if ((injection == null) || injection.getTargetClass() == null)
if (injection == null)
{
if (LOG.isDebugEnabled())
LOG.debug("Ignoring null Injection");
return;
}
if (LOG.isDebugEnabled())
LOG.debug("Adding injection for class=" + (injection.getTargetClass() + " on a " + (injection.getTarget().getName())));
String name = injection.getTargetClass().getName();
List<Injection> injections = _injectionMap.get(injection.getTargetClass().getCanonicalName());
Set<Injection> injections = _injectionMap.get(name);
if (injections == null)
{
injections = new ArrayList<Injection>();
_injectionMap.put(injection.getTargetClass().getCanonicalName(), injections);
injections = new CopyOnWriteArraySet<>();
Set<Injection> tmp = _injectionMap.putIfAbsent(name, injections);
if (tmp != null)
injections = tmp;
}
injections.add(injection);
boolean added = injections.add(injection);
if (LOG.isDebugEnabled())
LOG.debug("Adding injection for class={} on {} added={}", name, injection.getTarget().getName(), added);
}
public List<Injection> getInjections(String className)
public Set<Injection> getInjections(String className)
{
if (className == null)
return null;
@ -69,7 +85,7 @@ public class InjectionCollection
if (field == null || clazz == null)
return null;
List<Injection> injections = getInjections(clazz.getCanonicalName());
Set<Injection> injections = getInjections(clazz.getName());
if (injections == null)
return null;
Iterator<Injection> itor = injections.iterator();
@ -89,7 +105,7 @@ public class InjectionCollection
if (clazz == null || method == null || paramClass == null)
return null;
List<Injection> injections = getInjections(clazz.getCanonicalName());
Set<Injection> injections = getInjections(clazz.getName());
if (injections == null)
return null;
Iterator<Injection> itor = injections.iterator();
@ -115,7 +131,7 @@ public class InjectionCollection
while (clazz != null)
{
List<Injection> injections = _injectionMap.get(clazz.getCanonicalName());
Set<Injection> injections = _injectionMap.get(clazz.getName());
if (injections != null)
{
for (Injection i : injections)

View File

@ -21,6 +21,7 @@ package org.eclipse.jetty.plus.annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Objects;
import org.eclipse.jetty.util.IntrospectionUtil;
import org.eclipse.jetty.util.Loader;
@ -28,17 +29,40 @@ import org.eclipse.jetty.util.TypeUtil;
/**
* LifeCycleCallback
*
* Holds information about a class and method
* that has either been configured in web.xml to have postconstruct or
* predestroy callbacks, or has the equivalent annotations.
*/
public abstract class LifeCycleCallback
{
public static final Object[] __EMPTY_ARGS = new Object[]{};
private Method _target;
private Class<?> _targetClass;
private String _className;
private String _methodName;
private Class<?> _targetClass; //Not final so we can do lazy load
private final String _className;
private final String _methodName;
public LifeCycleCallback()
public LifeCycleCallback(String className, String methodName)
{
_className = Objects.requireNonNull(className);
_methodName = Objects.requireNonNull(methodName);
}
public LifeCycleCallback(Class<?> clazz, String methodName)
{
_targetClass = Objects.requireNonNull(clazz);
_methodName = Objects.requireNonNull(methodName);
try
{
Method method = IntrospectionUtil.findMethod(clazz, methodName, null, true, true);
validate(clazz, method);
_target = method;
_className = clazz.getName();
}
catch (NoSuchMethodException e)
{
throw new IllegalArgumentException("Method " + methodName + " not found on class " + clazz.getName());
}
}
/**
@ -67,33 +91,10 @@ public abstract class LifeCycleCallback
return _target;
}
public void setTarget(String className, String methodName)
{
_className = className;
_methodName = methodName;
}
public void setTarget(Class<?> clazz, String methodName)
{
try
{
Method method = IntrospectionUtil.findMethod(clazz, methodName, null, true, true);
validate(clazz, method);
_target = method;
_targetClass = clazz;
_className = clazz.getCanonicalName();
_methodName = methodName;
}
catch (NoSuchMethodException e)
{
throw new IllegalArgumentException("Method " + methodName + " not found on class " + clazz.getName());
}
}
public void callback(Object instance)
throws SecurityException, NoSuchMethodException, ClassNotFoundException, IllegalArgumentException, IllegalAccessException, InvocationTargetException
{
if (_target == null)
if (_target == null) //lazy load the target class
{
if (_targetClass == null)
_targetClass = Loader.loadClass(_className);
@ -143,28 +144,30 @@ public abstract class LifeCycleCallback
}
}
@Override
public int hashCode()
{
return Objects.hash(_className, _methodName);
}
@Override
public boolean equals(Object o)
{
if (o == null)
return false;
if (!(o instanceof LifeCycleCallback))
if (this == o)
return true;
if (!LifeCycleCallback.class.isInstance(o))
return false;
LifeCycleCallback callback = (LifeCycleCallback)o;
if (callback.getTargetClass() == null)
{
if (getTargetClass() != null)
return false;
}
else if (!callback.getTargetClass().equals(getTargetClass()))
return false;
if (callback.getTarget() == null)
{
return getTarget() == null;
}
else
return callback.getTarget().equals(getTarget());
if (getTargetClassName().equals(callback.getTargetClassName()) && getMethodName().equals(callback.getMethodName()))
return true;
return false;
}
public abstract void validate(Class<?> clazz, Method m);

View File

@ -21,15 +21,28 @@ package org.eclipse.jetty.plus.annotation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
/**
* LifeCycleCallbackCollection
*
* This class collects the classes and methods that have been configured
* in web.xml with postconstruct/predestroy callbacks, or that contain the
* equivalent annotations. It is also responsible for calling the
* callbacks.
*
* This class is not threadsafe for concurrent modifications, but is
* threadsafe for reading with concurrent modifications.
*/
public class LifeCycleCallbackCollection
{
@ -37,8 +50,8 @@ public class LifeCycleCallbackCollection
public static final String LIFECYCLE_CALLBACK_COLLECTION = "org.eclipse.jetty.lifecyleCallbackCollection";
private HashMap<String, List<LifeCycleCallback>> postConstructCallbacksMap = new HashMap<String, List<LifeCycleCallback>>();
private HashMap<String, List<LifeCycleCallback>> preDestroyCallbacksMap = new HashMap<String, List<LifeCycleCallback>>();
private final ConcurrentMap<String, Set<LifeCycleCallback>> postConstructCallbacksMap = new ConcurrentHashMap<>();
private final ConcurrentMap<String, Set<LifeCycleCallback>> preDestroyCallbacksMap = new ConcurrentHashMap<>();
/**
* Add a Callback to the list of callbacks.
@ -47,33 +60,36 @@ public class LifeCycleCallbackCollection
*/
public void add(LifeCycleCallback callback)
{
if ((callback == null) || (callback.getTargetClassName() == null))
return;
if (LOG.isDebugEnabled())
LOG.debug("Adding callback for class=" + callback.getTargetClass() + " on " + callback.getTarget());
Map<String, List<LifeCycleCallback>> map = null;
if (callback instanceof PreDestroyCallback)
map = preDestroyCallbacksMap;
if (callback instanceof PostConstructCallback)
map = postConstructCallbacksMap;
if (map == null)
throw new IllegalArgumentException("Unsupported lifecycle callback type: " + callback);
List<LifeCycleCallback> callbacks = map.get(callback.getTargetClassName());
if (callbacks == null)
if (callback == null)
{
callbacks = new ArrayList<LifeCycleCallback>();
map.put(callback.getTargetClassName(), callbacks);
if (LOG.isDebugEnabled())
LOG.debug("Ignoring empty LifeCycleCallback");
return;
}
//don't add another callback for exactly the same method
if (!callbacks.contains(callback))
callbacks.add(callback);
Map<String, Set<LifeCycleCallback>> map = null;
if (callback instanceof PreDestroyCallback)
map = preDestroyCallbacksMap;
else if (callback instanceof PostConstructCallback)
map = postConstructCallbacksMap;
else
throw new IllegalArgumentException("Unsupported lifecycle callback type: " + callback);
Set<LifeCycleCallback> callbacks = map.get(callback.getTargetClassName());
if (callbacks == null)
{
callbacks = new CopyOnWriteArraySet<LifeCycleCallback>();
Set<LifeCycleCallback> tmp = map.putIfAbsent(callback.getTargetClassName(), callbacks);
if (tmp != null)
callbacks = tmp;
}
boolean added = callbacks.add(callback);
if (LOG.isDebugEnabled())
LOG.debug("Adding callback for class={} on method={} added={}", callback.getTargetClassName(), callback.getMethodName(), added);
}
public List<LifeCycleCallback> getPreDestroyCallbacks(Object o)
public Set<LifeCycleCallback> getPreDestroyCallbacks(Object o)
{
if (o == null)
return null;
@ -82,7 +98,7 @@ public class LifeCycleCallbackCollection
return preDestroyCallbacksMap.get(clazz.getName());
}
public List<LifeCycleCallback> getPostConstructCallbacks(Object o)
public Set<LifeCycleCallback> getPostConstructCallbacks(Object o)
{
if (o == null)
return null;
@ -105,15 +121,13 @@ public class LifeCycleCallbackCollection
return;
Class<? extends Object> clazz = o.getClass();
List<LifeCycleCallback> callbacks = postConstructCallbacksMap.get(clazz.getName());
Set<LifeCycleCallback> callbacks = postConstructCallbacksMap.get(clazz.getName());
if (callbacks == null)
return;
for (int i = 0; i < callbacks.size(); i++)
{
callbacks.get(i).callback(o);
}
for (LifeCycleCallback l : callbacks)
l.callback(o);
}
/**
@ -130,14 +144,13 @@ public class LifeCycleCallbackCollection
return;
Class<? extends Object> clazz = o.getClass();
List<LifeCycleCallback> callbacks = preDestroyCallbacksMap.get(clazz.getName());
Set<LifeCycleCallback> callbacks = preDestroyCallbacksMap.get(clazz.getName());
if (callbacks == null)
return;
for (int i = 0; i < callbacks.size(); i++)
{
callbacks.get(i).callback(o);
}
for (LifeCycleCallback l : callbacks)
l.callback(o);
}
/**
@ -145,7 +158,7 @@ public class LifeCycleCallbackCollection
*
* @return the map of {@link PostConstructCallback}s
*/
public Map<String, List<LifeCycleCallback>> getPostConstructCallbackMap()
public Map<String, Set<LifeCycleCallback>> getPostConstructCallbackMap()
{
return Collections.unmodifiableMap(postConstructCallbacksMap);
}
@ -155,38 +168,38 @@ public class LifeCycleCallbackCollection
*
* @return the map of {@link PreDestroyCallback}s
*/
public Map<String, List<LifeCycleCallback>> getPreDestroyCallbackMap()
public Map<String, Set<LifeCycleCallback>> getPreDestroyCallbackMap()
{
return Collections.unmodifiableMap(preDestroyCallbacksMap);
}
/**
* Amalgamate all post-construct callbacks and return a read only list
* Amalgamate all post-construct callbacks and return a read only set
*
* @return the collection of {@link PostConstructCallback}s
*/
public Collection<LifeCycleCallback> getPostConstructCallbacks()
{
List<LifeCycleCallback> list = new ArrayList<LifeCycleCallback>();
Set<LifeCycleCallback> set = new HashSet<LifeCycleCallback>();
for (String s : postConstructCallbacksMap.keySet())
{
list.addAll(postConstructCallbacksMap.get(s));
set.addAll(postConstructCallbacksMap.get(s));
}
return Collections.unmodifiableCollection(list);
return Collections.unmodifiableCollection(set);
}
/**
* Amalgamate all pre-destroy callbacks and return a read only list
* Amalgamate all pre-destroy callbacks and return a read only set
*
* @return the collection of {@link PreDestroyCallback}s
*/
public Collection<LifeCycleCallback> getPreDestroyCallbacks()
{
List<LifeCycleCallback> list = new ArrayList<LifeCycleCallback>();
Set<LifeCycleCallback> set = new HashSet<LifeCycleCallback>();
for (String s : preDestroyCallbacksMap.keySet())
{
list.addAll(preDestroyCallbacksMap.get(s));
set.addAll(preDestroyCallbacksMap.get(s));
}
return Collections.unmodifiableCollection(list);
return Collections.unmodifiableCollection(set);
}
}

View File

@ -29,6 +29,24 @@ public class PostConstructCallback extends LifeCycleCallback
{
/**
* @param clazz the class object to be injected
* @param methodName the name of the method to be injected
*/
public PostConstructCallback(Class<?> clazz, String methodName)
{
super(clazz, methodName);
}
/**
* @param className the name of the class to be injected
* @param methodName the name of the method to be injected
*/
public PostConstructCallback(String className, String methodName)
{
super(className, methodName);
}
/**
* Commons Annotation Specification section 2.5
* - no params
* - must be void return

View File

@ -32,6 +32,24 @@ public class PreDestroyCallback extends LifeCycleCallback
private static final Logger LOG = Log.getLogger(PreDestroyCallback.class);
/**
* @param clazz the class object to be injected
* @param methodName the name of the method to inject
*/
public PreDestroyCallback(Class<?> clazz, String methodName)
{
super(clazz, methodName);
}
/**
* @param className the name of the class to inject
* @param methodName the name of the method to inject
*/
public PreDestroyCallback(String className, String methodName)
{
super(className, methodName);
}
/**
* Commons Annotations Specification section 2.6:
* - no params to method
* - returns void

View File

@ -18,6 +18,8 @@
package org.eclipse.jetty.plus.annotation;
import java.util.Objects;
import org.eclipse.jetty.servlet.ServletHolder;
/**
@ -30,13 +32,10 @@ public class RunAs
private String _className;
private String _roleName;
public RunAs()
public RunAs(String className, String roleName)
{
}
public void setTargetClassName(String className)
{
_className = className;
_className = Objects.requireNonNull(className);
_roleName = Objects.requireNonNull(roleName);
}
public String getTargetClassName()
@ -44,11 +43,6 @@ public class RunAs
return _className;
}
public void setRoleName(String roleName)
{
_roleName = roleName;
}
public String getRoleName()
{
return _roleName;

View File

@ -18,7 +18,8 @@
package org.eclipse.jetty.plus.annotation;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.log.Log;
@ -32,7 +33,7 @@ public class RunAsCollection
private static final Logger LOG = Log.getLogger(RunAsCollection.class);
public static final String RUNAS_COLLECTION = "org.eclipse.jetty.runAsCollection";
private HashMap<String, RunAs> _runAsMap = new HashMap<String, RunAs>();//map of classname to run-as
private ConcurrentMap<String, RunAs> _runAsMap = new ConcurrentHashMap<String, RunAs>();//map of classname to run-as
public void add(RunAs runAs)
{
@ -41,7 +42,9 @@ public class RunAsCollection
if (LOG.isDebugEnabled())
LOG.debug("Adding run-as for class=" + runAs.getTargetClassName());
_runAsMap.put(runAs.getTargetClassName(), runAs);
RunAs prev = _runAsMap.putIfAbsent(runAs.getTargetClassName(), runAs);
if (prev != null)
LOG.warn("Run-As {} on class {} ignored, already run-as {}", runAs.getRoleName(), runAs.getTargetClassName(), prev.getRoleName());
}
public RunAs getRunAs(Object o)
@ -49,7 +52,7 @@ public class RunAsCollection
if (o == null)
return null;
return _runAsMap.get(o.getClass().getCanonicalName());
return (RunAs)_runAsMap.get(o.getClass().getName());
}
public void setRunAs(Object o)

View File

@ -20,4 +20,3 @@
* Jetty Plus : Limited JEE Annotation Support
*/
package org.eclipse.jetty.plus.annotation;

View File

@ -20,4 +20,3 @@
* Jetty Plus : Limited JEE Jndi Support
*/
package org.eclipse.jetty.plus.jndi;

View File

@ -20,4 +20,3 @@
* Jetty Plus : Limited JEE Security Support
*/
package org.eclipse.jetty.plus.security;

View File

@ -575,17 +575,8 @@ public class PlusDescriptorProcessor extends IterativeDescriptorProcessor
//No post-constructs have been declared previously.
context.getMetaData().setOrigin("post-construct", descriptor);
try
{
Class<?> clazz = context.loadClass(className);
LifeCycleCallback callback = new PostConstructCallback();
callback.setTarget(clazz, methodName);
((LifeCycleCallbackCollection)context.getAttribute(LifeCycleCallbackCollection.LIFECYCLE_CALLBACK_COLLECTION)).add(callback);
}
catch (ClassNotFoundException e)
{
LOG.warn("Couldn't load post-construct target class " + className);
}
LifeCycleCallback callback = new PostConstructCallback(className, methodName);
((LifeCycleCallbackCollection)context.getAttribute(LifeCycleCallbackCollection.LIFECYCLE_CALLBACK_COLLECTION)).add(callback);
break;
}
case WebXml:
@ -599,8 +590,7 @@ public class PlusDescriptorProcessor extends IterativeDescriptorProcessor
try
{
Class<?> clazz = context.loadClass(className);
LifeCycleCallback callback = new PostConstructCallback();
callback.setTarget(clazz, methodName);
LifeCycleCallback callback = new PostConstructCallback(clazz, methodName);
((LifeCycleCallbackCollection)context.getAttribute(LifeCycleCallbackCollection.LIFECYCLE_CALLBACK_COLLECTION)).add(callback);
}
catch (ClassNotFoundException e)
@ -616,8 +606,7 @@ public class PlusDescriptorProcessor extends IterativeDescriptorProcessor
try
{
Class<?> clazz = context.loadClass(className);
LifeCycleCallback callback = new PostConstructCallback();
callback.setTarget(clazz, methodName);
LifeCycleCallback callback = new PostConstructCallback(clazz, methodName);
((LifeCycleCallbackCollection)context.getAttribute(LifeCycleCallbackCollection.LIFECYCLE_CALLBACK_COLLECTION)).add(callback);
}
catch (ClassNotFoundException e)
@ -660,17 +649,10 @@ public class PlusDescriptorProcessor extends IterativeDescriptorProcessor
//No pre-destroys have been declared previously. Record this descriptor
//as the first declarer.
context.getMetaData().setOrigin("pre-destroy", descriptor);
try
{
Class<?> clazz = context.loadClass(className);
LifeCycleCallback callback = new PreDestroyCallback();
callback.setTarget(clazz, methodName);
((LifeCycleCallbackCollection)context.getAttribute(LifeCycleCallbackCollection.LIFECYCLE_CALLBACK_COLLECTION)).add(callback);
}
catch (ClassNotFoundException e)
{
LOG.warn("Couldn't load pre-destroy target class " + className);
}
LifeCycleCallback callback = new PreDestroyCallback(className, methodName);
((LifeCycleCallbackCollection)context.getAttribute(LifeCycleCallbackCollection.LIFECYCLE_CALLBACK_COLLECTION)).add(callback);
break;
}
case WebXml:
@ -684,8 +666,7 @@ public class PlusDescriptorProcessor extends IterativeDescriptorProcessor
try
{
Class<?> clazz = context.loadClass(className);
LifeCycleCallback callback = new PreDestroyCallback();
callback.setTarget(clazz, methodName);
LifeCycleCallback callback = new PreDestroyCallback(clazz, methodName);
((LifeCycleCallbackCollection)context.getAttribute(LifeCycleCallbackCollection.LIFECYCLE_CALLBACK_COLLECTION)).add(callback);
}
catch (ClassNotFoundException e)
@ -701,8 +682,7 @@ public class PlusDescriptorProcessor extends IterativeDescriptorProcessor
try
{
Class<?> clazz = context.loadClass(className);
LifeCycleCallback callback = new PreDestroyCallback();
callback.setTarget(clazz, methodName);
LifeCycleCallback callback = new PreDestroyCallback(clazz, methodName);
((LifeCycleCallbackCollection)context.getAttribute(LifeCycleCallbackCollection.LIFECYCLE_CALLBACK_COLLECTION)).add(callback);
}
catch (ClassNotFoundException e)
@ -754,9 +734,7 @@ public class PlusDescriptorProcessor extends IterativeDescriptorProcessor
try
{
Class<?> clazz = context.loadClass(targetClassName);
Injection injection = new Injection();
injection.setJndiName(jndiName);
injection.setTarget(clazz, targetName, valueClass);
Injection injection = new Injection(clazz, targetName, valueClass, jndiName, null);
injections.add(injection);
//Record which was the first descriptor to declare an injection for this name

View File

@ -20,4 +20,3 @@
* Jetty Plus : Limited Additional JEE Webapp Support
*/
package org.eclipse.jetty.plus.webapp;

View File

@ -0,0 +1,234 @@
//
// ========================================================================
// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.plus.annotation;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.anEmptyMap;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.fail;
import java.lang.reflect.Method;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
public class LifeCycleCallbackCollectionTest
{
/**
* An unsupported lifecycle callback type
*
*/
public class TestLifeCycleCallback extends LifeCycleCallback
{
public TestLifeCycleCallback(Class<?> clazz, String methodName)
{
super(clazz, methodName);
}
public TestLifeCycleCallback(String className, String methodName)
{
super(className, methodName);
}
@Override
public void validate(Class<?> clazz, Method m)
{
throw new IllegalStateException("TEST!");
}
}
/**
* A class that we can use to simulate having PostConstruct and
* PreDestroy annotations on.
*
*/
public class SomeTestClass
{
public void afterConstruct()
{
//Empty method, we just want to refer to its name
}
}
@Test
public void testAddForPostConstruct() throws Exception
{
//test empty PostConstruct
String nullName = null;
Class<?> clazz = null;
PostConstructCallback pc1 = null;
try
{
pc1 = new PostConstructCallback(nullName, null);
fail("Null class arg should not be allowed");
}
catch (NullPointerException e)
{
//expected
}
try
{
pc1 = new PostConstructCallback(clazz, null);
fail("Null class arg should not be allowed");
}
catch (NullPointerException e)
{
//expected
}
try
{
pc1 = new PostConstructCallback(SomeTestClass.class, null);
fail("Null method arg should not be allowed");
}
catch (NullPointerException e)
{
//expected
}
try
{
pc1 = new PostConstructCallback("foo", null);
fail("Null method arg should not be allowed");
}
catch (NullPointerException e)
{
//expected
}
LifeCycleCallbackCollection collection = new LifeCycleCallbackCollection();
//test ignoring duplicate adds for callbacks for same classname and method
PostConstructCallback pc2 = new PostConstructCallback("foo", "bar");
collection.add(pc2);
assertThat(collection.getPostConstructCallbackMap().get("foo"), Matchers.contains(pc2));
PostConstructCallback pc3 = new PostConstructCallback("foo", "bar");
collection.add(pc3);
assertThat(collection.getPostConstructCallbackMap().get("foo"), Matchers.contains(pc2));
assertThat(collection.getPostConstructCallbackMap().values(), hasSize(1));
//test ignoring duplicate adds by class and method name
collection = new LifeCycleCallbackCollection();
PostConstructCallback pc4 = new PostConstructCallback(SomeTestClass.class, "afterConstruct");
collection.add(pc4);
assertThat(collection.getPostConstructCallbackMap().get(SomeTestClass.class.getName()), Matchers.contains(pc4));
assertThat(collection.getPostConstructCallbackMap().values(), hasSize(1));
PostConstructCallback pc5 = new PostConstructCallback(SomeTestClass.class, "afterConstruct");
collection.add(pc5);
assertThat(collection.getPostConstructCallbackMap().get(SomeTestClass.class.getName()), Matchers.contains(pc4));
assertThat(collection.getPostConstructCallbackMap().values(), hasSize(1));
}
@Test
public void testUnsupportedType() throws Exception
{
//test that we currently only support PostConstruct and PreDestroy
LifeCycleCallbackCollection collection = new LifeCycleCallbackCollection();
try
{
TestLifeCycleCallback tcb = new TestLifeCycleCallback("abc", "def");
collection.add(tcb);
fail("Support only PostConstruct and PreDestroy");
}
catch (IllegalArgumentException e)
{
//expected
}
}
@Test
public void testAddForPreDestroy() throws Exception
{
//test empty PreDestroy
String nullName = null;
Class<?> clazz = null;
PreDestroyCallback pc1 = null;
try
{
pc1 = new PreDestroyCallback(nullName, null);
fail("Null class arg should not be allowed");
}
catch (NullPointerException e)
{
//expected
}
try
{
pc1 = new PreDestroyCallback(clazz, null);
fail("Null class arg should not be allowed");
}
catch (NullPointerException e)
{
//expected
}
try
{
pc1 = new PreDestroyCallback(SomeTestClass.class, null);
fail("Null method arg should not be allowed");
}
catch (NullPointerException e)
{
//expected
}
try
{
pc1 = new PreDestroyCallback("foo", null);
fail("Null method arg should not be allowed");
}
catch (NullPointerException e)
{
//expected
}
LifeCycleCallbackCollection collection = new LifeCycleCallbackCollection();
//test ignoring duplicate adds for callbacks for same classname and method
PreDestroyCallback pc2 = new PreDestroyCallback("foo", "bar");
collection.add(pc2);
assertThat(collection.getPreDestroyCallbackMap().get("foo"), Matchers.contains(pc2));
PreDestroyCallback pc3 = new PreDestroyCallback("foo", "bar");
collection.add(pc3);
assertThat(collection.getPreDestroyCallbackMap().get("foo"), Matchers.contains(pc2));
assertThat(collection.getPreDestroyCallbackMap().values(), hasSize(1));
//test ignoring duplicate adds by class and method name
collection = new LifeCycleCallbackCollection();
PreDestroyCallback pc4 = new PreDestroyCallback(SomeTestClass.class, "afterConstruct");
collection.add(pc4);
assertThat(collection.getPreDestroyCallbackMap().get(SomeTestClass.class.getName()), Matchers.contains(pc4));
assertThat(collection.getPreDestroyCallbackMap().values(), hasSize(1));
PreDestroyCallback pc5 = new PreDestroyCallback(SomeTestClass.class, "afterConstruct");
collection.add(pc5);
assertThat(collection.getPreDestroyCallbackMap().get(SomeTestClass.class.getName()), Matchers.contains(pc4));
assertThat(collection.getPreDestroyCallbackMap().values(), hasSize(1));
}
}

View File

@ -43,4 +43,4 @@ public class NamingEntryUtilTest
{
assertThrows(NamingException.class, () -> NamingEntryUtil.bindToENC(null, null, "@=<9"));
}
}
}

View File

@ -1652,7 +1652,7 @@ public class ConstraintTest
private static String authBase64(String authorization)
{
byte raw[] = authorization.getBytes(ISO_8859_1);
byte[] raw = authorization.getBytes(ISO_8859_1);
return Base64.getEncoder().encodeToString(raw);
}

View File

@ -62,6 +62,9 @@ import javax.servlet.SessionTrackingMode;
import javax.servlet.descriptor.JspConfigDescriptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionIdListener;
import javax.servlet.http.HttpSessionListener;
import org.eclipse.jetty.http.HttpURI;
import org.eclipse.jetty.http.MimeTypes;
@ -110,12 +113,15 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu
public static final int SERVLET_MAJOR_VERSION = 3;
public static final int SERVLET_MINOR_VERSION = 1;
public static final Class<?>[] SERVLET_LISTENER_TYPES =
{
ServletContextListener.class,
ServletContextAttributeListener.class,
ServletRequestListener.class,
ServletRequestAttributeListener.class
};
{
ServletContextListener.class,
ServletContextAttributeListener.class,
ServletRequestListener.class,
ServletRequestAttributeListener.class,
HttpSessionIdListener.class,
HttpSessionListener.class,
HttpSessionAttributeListener.class
};
public static final int DEFAULT_LISTENER_TYPE_INDEX = 1;
public static final int EXTENDED_LISTENER_TYPE_INDEX = 0;
@ -643,7 +649,9 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu
_eventListeners.add(listener);
if (!(isStarted() || isStarting()))
{
_durableListeners.add(listener);
}
if (listener instanceof ContextScopeListener)
{
@ -704,10 +712,15 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu
_programmaticListeners.add(listener);
}
protected boolean isProgrammaticListener(EventListener listener)
public boolean isProgrammaticListener(EventListener listener)
{
return _programmaticListeners.contains(listener);
}
public boolean isDurableListener(EventListener listener)
{
return _durableListeners.contains(listener);
}
/**
* @return true if this context is shutting down

View File

@ -58,7 +58,7 @@ public class CookieCutterTest
{
String rawCookie = "$Version=\"1\"; Customer=\"WILE_E_COYOTE\"; $Path=\"/acme\"";
Cookie cookies[] = parseCookieHeaders(CookieCompliance.RFC2965, rawCookie);
Cookie[] cookies = parseCookieHeaders(CookieCompliance.RFC2965, rawCookie);
assertThat("Cookies.length", cookies.length, is(1));
assertCookie("Cookies[0]", cookies[0], "Customer", "WILE_E_COYOTE", 1, "/acme");
@ -75,7 +75,7 @@ public class CookieCutterTest
{
String rawCookie = "$Version=\"1\";Customer=\"WILE_E_COYOTE\";$Path=\"/acme\"";
Cookie cookies[] = parseCookieHeaders(CookieCompliance.RFC2965, rawCookie);
Cookie[] cookies = parseCookieHeaders(CookieCompliance.RFC2965, rawCookie);
assertThat("Cookies.length", cookies.length, is(1));
assertCookie("Cookies[0]", cookies[0], "Customer", "WILE_E_COYOTE", 1, "/acme");
@ -91,7 +91,7 @@ public class CookieCutterTest
"Customer=\"WILE_E_COYOTE\"; $Path=\"/acme\"; " +
"Part_Number=\"Rocket_Launcher_0001\"; $Path=\"/acme\"";
Cookie cookies[] = parseCookieHeaders(CookieCompliance.RFC2965, rawCookie);
Cookie[] cookies = parseCookieHeaders(CookieCompliance.RFC2965, rawCookie);
assertThat("Cookies.length", cookies.length, is(2));
assertCookie("Cookies[0]", cookies[0], "Customer", "WILE_E_COYOTE", 1, "/acme");
@ -109,7 +109,7 @@ public class CookieCutterTest
"Part_Number=\"Rocket_Launcher_0001\"; $Path=\"/acme\"; " +
"Shipping=\"FedEx\"; $Path=\"/acme\"";
Cookie cookies[] = parseCookieHeaders(CookieCompliance.RFC2965, rawCookie);
Cookie[] cookies = parseCookieHeaders(CookieCompliance.RFC2965, rawCookie);
assertThat("Cookies.length", cookies.length, is(3));
assertCookie("Cookies[0]", cookies[0], "Customer", "WILE_E_COYOTE", 1, "/acme");
@ -127,7 +127,7 @@ public class CookieCutterTest
"Part_Number=\"Riding_Rocket_0023\"; $Path=\"/acme/ammo\"; " +
"Part_Number=\"Rocket_Launcher_0001\"; $Path=\"/acme\"";
Cookie cookies[] = parseCookieHeaders(CookieCompliance.RFC2965, rawCookie);
Cookie[] cookies = parseCookieHeaders(CookieCompliance.RFC2965, rawCookie);
assertThat("Cookies.length", cookies.length, is(2));
assertCookie("Cookies[0]", cookies[0], "Part_Number", "Riding_Rocket_0023", 1, "/acme/ammo");
@ -144,7 +144,7 @@ public class CookieCutterTest
"session_id=\"1234\"; " +
"session_id=\"1111\"; $Domain=\".cracker.edu\"";
Cookie cookies[] = parseCookieHeaders(CookieCompliance.RFC2965, rawCookie);
Cookie[] cookies = parseCookieHeaders(CookieCompliance.RFC2965, rawCookie);
assertThat("Cookies.length", cookies.length, is(2));
assertCookie("Cookies[0]", cookies[0], "session_id", "1234", 1, null);
@ -160,7 +160,7 @@ public class CookieCutterTest
String rawCookie = "$Version=\"1\"; session_id=\"1234\", " +
"$Version=\"1\"; session_id=\"1111\"; $Domain=\".cracker.edu\"";
Cookie cookies[] = parseCookieHeaders(CookieCompliance.RFC2965, rawCookie);
Cookie[] cookies = parseCookieHeaders(CookieCompliance.RFC2965, rawCookie);
assertThat("Cookies.length", cookies.length, is(2));
assertCookie("Cookies[0]", cookies[0], "session_id", "1234", 1, null);
@ -180,7 +180,7 @@ public class CookieCutterTest
{
String rawCookie = "SID=31d4d96e407aad42";
Cookie cookies[] = parseCookieHeaders(CookieCompliance.RFC6265, rawCookie);
Cookie[] cookies = parseCookieHeaders(CookieCompliance.RFC6265, rawCookie);
assertThat("Cookies.length", cookies.length, is(1));
assertCookie("Cookies[0]", cookies[0], "SID", "31d4d96e407aad42", 0, null);
@ -194,7 +194,7 @@ public class CookieCutterTest
{
String rawCookie = "SID=31d4d96e407aad42; lang=en-US";
Cookie cookies[] = parseCookieHeaders(CookieCompliance.RFC6265, rawCookie);
Cookie[] cookies = parseCookieHeaders(CookieCompliance.RFC6265, rawCookie);
assertThat("Cookies.length", cookies.length, is(2));
assertCookie("Cookies[0]", cookies[0], "SID", "31d4d96e407aad42", 0, null);
@ -212,7 +212,7 @@ public class CookieCutterTest
{
String rawCookie = "SID=31d4d96e407aad42;lang=en-US";
Cookie cookies[] = parseCookieHeaders(CookieCompliance.RFC6265, rawCookie);
Cookie[] cookies = parseCookieHeaders(CookieCompliance.RFC6265, rawCookie);
assertThat("Cookies.length", cookies.length, is(2));
assertCookie("Cookies[0]", cookies[0], "SID", "31d4d96e407aad42", 0, null);
@ -227,7 +227,7 @@ public class CookieCutterTest
{
String rawCookie = "key=value";
Cookie cookies[] = parseCookieHeaders(CookieCompliance.RFC6265, rawCookie);
Cookie[] cookies = parseCookieHeaders(CookieCompliance.RFC6265, rawCookie);
assertThat("Cookies.length", cookies.length, is(1));
assertCookie("Cookies[0]", cookies[0], "key", "value", 0, null);
@ -241,7 +241,7 @@ public class CookieCutterTest
{
String rawCookie = "$key=value";
Cookie cookies[] = parseCookieHeaders(CookieCompliance.RFC6265, rawCookie);
Cookie[] cookies = parseCookieHeaders(CookieCompliance.RFC6265, rawCookie);
assertThat("Cookies.length", cookies.length, is(0));
}

View File

@ -246,7 +246,7 @@ public class HttpConnectionTest
StringBuilder request = new StringBuilder();
request.append("POST /?id=").append(Integer.toString(x)).append(" HTTP/1.1\r\n");
request.append("Host: local\r\n");
int clen[] = contentLengths[x];
int[] clen = contentLengths[x];
for (int n = 0; n < clen.length; n++)
{
request.append("Content-Length: ").append(Integer.toString(clen[n])).append("\r\n");
@ -280,7 +280,7 @@ public class HttpConnectionTest
StringBuilder request = new StringBuilder();
request.append("POST /?id=").append(Integer.toString(x)).append(" HTTP/1.1\r\n");
request.append("Host: local\r\n");
int clen[] = contentLengths[x];
int[] clen = contentLengths[x];
for (int n = 0; n < clen.length; n++)
{
if (clen[n] == -1)

View File

@ -442,7 +442,7 @@ public class HttpManyWaysToCommitTest extends AbstractHttpTest
HttpTester.Response response = executeRequest(httpVersion);
assertThat("response code", response.getStatus(), is(200));
assertThat(response, containsHeaderValue("content-length", "6"));
byte content[] = response.getContentBytes();
byte[] content = response.getContentBytes();
assertThat("content bytes", content.length, is(0));
assertTrue(response.isEarlyEOF(), "response eof");
}

View File

@ -30,6 +30,7 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.TypeUtil;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
@ -57,7 +58,7 @@ public class ProxyProtocolTest
}
@Test
public void testProxyProtocol() throws Exception
public void testProxyProtocolV1() throws Exception
{
final String remoteAddr = "192.168.0.0";
final int remotePort = 12345;
@ -111,4 +112,85 @@ public class ProxyProtocolTest
}
}
}
@Test
public void testProxyProtocolV2() throws Exception
{
final String remoteAddr = "192.168.0.1";
final int remotePort = 12345;
start(new AbstractHandler()
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
if (remoteAddr.equals(request.getRemoteAddr()) &&
remotePort == request.getRemotePort())
baseRequest.setHandled(true);
}
});
try (Socket socket = new Socket("localhost", connector.getLocalPort()))
{
String proxy =
// Preamble
"0D0A0D0A000D0A515549540A" +
// V2, PROXY
"21" +
// 0x1 : AF_INET 0x1 : STREAM. Address length is 2*4 + 2*2 = 12 bytes.
"11" +
// length of remaining header (4+4+2+2+6+3 = 21)
"0015" +
// uint32_t src_addr; uint32_t dst_addr; uint16_t src_port; uint16_t dst_port;
"C0A80001" +
"7f000001" +
"3039" +
"1F90" +
// NOOP value 0
"040000" +
// NOOP value ABCDEF
"040003ABCDEF";
String request1 =
"GET /1 HTTP/1.1\r\n" +
"Host: localhost\r\n" +
"\r\n";
OutputStream output = socket.getOutputStream();
output.write(TypeUtil.fromHexString(proxy));
output.write(request1.getBytes(StandardCharsets.UTF_8));
output.flush();
InputStream input = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
String response1 = reader.readLine();
assertTrue(response1.startsWith("HTTP/1.1 200 "));
while (true)
{
if (reader.readLine().isEmpty())
break;
}
// Send a second request to verify that the proxied IP is retained.
String request2 =
"GET /2 HTTP/1.1\r\n" +
"Host: localhost\r\n" +
"Connection: close\r\n" +
"\r\n";
output.write(request2.getBytes(StandardCharsets.UTF_8));
output.flush();
String response2 = reader.readLine();
assertTrue(response2.startsWith("HTTP/1.1 200 "));
while (true)
{
if (reader.readLine() == null)
break;
}
}
}
}

View File

@ -266,8 +266,8 @@ public class StressTest
// System.err.println();
final int quantums = 48;
final int[][] count = new int[_latencies.length][quantums];
final int length[] = new int[_latencies.length];
final int other[] = new int[_latencies.length];
final int[] length = new int[_latencies.length];
final int[] other = new int[_latencies.length];
long total = 0;

View File

@ -317,7 +317,7 @@ public class ThreadStarvationTest
long bodyCount = 0;
long len;
byte buf[] = new byte[1024];
byte[] buf = new byte[1024];
try
{

View File

@ -55,7 +55,7 @@ public class AllowSymLinkAliasCheckerTest
{
List<Arguments> data = new ArrayList<>();
String dirs[] = {
String[] dirs = {
"/workDir/", "/testdirlnk/", "/testdirprefixlnk/", "/testdirsuffixlnk/",
"/testdirwraplnk/"
};

View File

@ -102,7 +102,7 @@ public class ResourceHandlerTest
try (BufferedReader reader = Files.newBufferedReader(big.toPath(), StandardCharsets.UTF_8))
{
// a buffer large enough to capture at least 1 EOL
char cbuf[] = new char[128];
char[] cbuf = new char[128];
reader.read(cbuf);
String sample = new String(cbuf);
if (sample.contains("\r\n"))

View File

@ -100,7 +100,7 @@ public class SecuredRedirectHandlerTest
server.setConnectors(new Connector[]{httpConnector, httpsConnector});
// Wire up contexts
String secureHosts[] = new String[]{"@secured"};
String[] secureHosts = new String[]{"@secured"};
ContextHandler test1Context = new ContextHandler();
test1Context.setContextPath("/test1");

View File

@ -82,7 +82,7 @@ public class StatisticsHandlerTest
@Test
public void testRequest() throws Exception
{
final CyclicBarrier barrier[] = {new CyclicBarrier(2), new CyclicBarrier(2)};
final CyclicBarrier[] barrier = {new CyclicBarrier(2), new CyclicBarrier(2)};
_statsHandler.setHandler(new AbstractHandler()
{
@ -175,7 +175,7 @@ public class StatisticsHandlerTest
@Test
public void testTwoRequests() throws Exception
{
final CyclicBarrier barrier[] = {new CyclicBarrier(3), new CyclicBarrier(3)};
final CyclicBarrier[] barrier = {new CyclicBarrier(3), new CyclicBarrier(3)};
_latchHandler.reset(2);
_statsHandler.setHandler(new AbstractHandler()
{
@ -239,7 +239,7 @@ public class StatisticsHandlerTest
final long dispatchTime = 10;
final long requestTime = 50;
final AtomicReference<AsyncContext> asyncHolder = new AtomicReference<>();
final CyclicBarrier barrier[] = {new CyclicBarrier(2), new CyclicBarrier(2), new CyclicBarrier(2)};
final CyclicBarrier[] barrier = {new CyclicBarrier(2), new CyclicBarrier(2), new CyclicBarrier(2)};
_statsHandler.setHandler(new AbstractHandler()
{
@Override
@ -369,7 +369,7 @@ public class StatisticsHandlerTest
final long dispatchTime = 10;
final long timeout = 100;
final AtomicReference<AsyncContext> asyncHolder = new AtomicReference<>();
final CyclicBarrier barrier[] = {new CyclicBarrier(2), new CyclicBarrier(2), new CyclicBarrier(2)};
final CyclicBarrier[] barrier = {new CyclicBarrier(2), new CyclicBarrier(2), new CyclicBarrier(2)};
_statsHandler.setHandler(new AbstractHandler()
{
@Override
@ -483,7 +483,7 @@ public class StatisticsHandlerTest
{
final long dispatchTime = 10;
final AtomicReference<AsyncContext> asyncHolder = new AtomicReference<>();
final CyclicBarrier barrier[] = {new CyclicBarrier(2), new CyclicBarrier(2)};
final CyclicBarrier[] barrier = {new CyclicBarrier(2), new CyclicBarrier(2)};
final CountDownLatch latch = new CountDownLatch(1);
_statsHandler.setHandler(new AbstractHandler()

View File

@ -22,6 +22,8 @@ import java.util.EventListener;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.eclipse.jetty.server.handler.ContextHandler;
/**
* ListenerHolder
*
@ -32,7 +34,6 @@ import javax.servlet.ServletException;
public class ListenerHolder extends BaseHolder<EventListener>
{
private EventListener _listener;
private boolean _initialized = false;
public ListenerHolder()
{
@ -68,35 +69,6 @@ public class ListenerHolder extends BaseHolder<EventListener>
setHeldClass(_listener.getClass());
}
public void initialize(ServletContext context) throws Exception
{
if (!_initialized)
{
initialize();
if (_listener == null)
{
//create an instance of the listener and decorate it
try
{
_listener = (context instanceof ServletContextHandler.Context)
? context.createListener(getHeldClass())
: getHeldClass().getDeclaredConstructor().newInstance();
}
catch (ServletException ex)
{
Throwable cause = ex.getRootCause();
if (cause instanceof InstantiationException)
throw (InstantiationException)cause;
if (cause instanceof IllegalAccessException)
throw (IllegalAccessException)cause;
throw ex;
}
}
_initialized = true;
}
}
@Override
public void doStart() throws Exception
{
@ -107,6 +79,29 @@ public class ListenerHolder extends BaseHolder<EventListener>
super.stop();
throw new IllegalStateException(msg);
}
ContextHandler contextHandler = ContextHandler.getCurrentContext().getContextHandler();
if (_listener == null)
{
//create an instance of the listener and decorate it
try
{
ServletContext scontext = contextHandler.getServletContext();
_listener = (scontext instanceof ServletContextHandler.Context)
? scontext.createListener(getHeldClass())
: getHeldClass().getDeclaredConstructor().newInstance();
}
catch (ServletException ex)
{
Throwable cause = ex.getRootCause();
if (cause instanceof InstantiationException)
throw (InstantiationException)cause;
if (cause instanceof IllegalAccessException)
throw (IllegalAccessException)cause;
throw ex;
}
}
contextHandler.addEventListener(_listener);
}
@Override
@ -115,7 +110,6 @@ public class ListenerHolder extends BaseHolder<EventListener>
super.doStop();
if (!_extInstance)
_listener = null;
_initialized = false;
}
@Override

View File

@ -107,6 +107,8 @@ public class ServletContextHandler extends ContextHandler
protected int _options;
protected JspConfigDescriptor _jspConfig;
private boolean _startListeners;
public ServletContextHandler()
{
this(null, null, null, null, null);
@ -347,14 +349,11 @@ public class ServletContextHandler extends ContextHandler
for (ListenerHolder holder : _servletHandler.getListeners())
{
holder.start();
//we need to pass in the context because the ServletHandler has not
//yet got a reference to the ServletContext (happens in super.startContext)
holder.initialize(_scontext);
addEventListener(holder.getListener());
}
}
}
_startListeners = true;
super.startContext();
// OK to Initialize servlet handler now that all relevant object trees have been started
@ -365,6 +364,7 @@ public class ServletContextHandler extends ContextHandler
@Override
protected void stopContext() throws Exception
{
_startListeners = false;
super.stopContext();
}
@ -1417,8 +1417,19 @@ public class ServletContextHandler extends ContextHandler
ListenerHolder holder = getServletHandler().newListenerHolder(Source.JAVAX_API);
holder.setListener(t);
getServletHandler().addListener(holder);
addProgrammaticListener(t);
getServletHandler().addListener(holder);
if (_startListeners)
{
try
{
holder.start();
}
catch (Exception e)
{
throw new IllegalStateException(e);
}
}
}
@Override

View File

@ -113,7 +113,7 @@ public class DefaultServletTest
connector.getConnectionFactory(HttpConfiguration.ConnectionFactory.class).getHttpConfiguration().setSendServerVersion(false);
File extraJarResources = MavenTestingUtils.getTestResourceFile(ODD_JAR);
URL urls[] = new URL[]{extraJarResources.toURI().toURL()};
URL[] urls = new URL[]{extraJarResources.toURI().toURL()};
ClassLoader parentClassLoader = Thread.currentThread().getContextClassLoader();
URLClassLoader extraClassLoader = new URLClassLoader(urls, parentClassLoader);

View File

@ -18,25 +18,48 @@
package org.eclipse.jetty.servlet;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EventListener;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.Servlet;
import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionIdListener;
import javax.servlet.http.HttpSessionListener;
import org.eclipse.jetty.security.ConstraintSecurityHandler;
@ -61,15 +84,6 @@ import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class ServletContextHandlerTest
{
private Server _server;
@ -157,8 +171,7 @@ public class ServletContextHandlerTest
}
public static class MyTestSessionListener implements HttpSessionAttributeListener, HttpSessionListener
{
{
@Override
public void sessionCreated(HttpSessionEvent se)
{
@ -184,6 +197,187 @@ public class ServletContextHandlerTest
{
}
}
public static class MySCAListener implements ServletContextAttributeListener
{
public static int adds = 0;
public static int removes = 0;
public static int replaces = 0;
@Override
public void attributeAdded(ServletContextAttributeEvent event)
{
++adds;
}
@Override
public void attributeRemoved(ServletContextAttributeEvent event)
{
++removes;
}
@Override
public void attributeReplaced(ServletContextAttributeEvent event)
{
++replaces;
}
}
public static class MyRequestListener implements ServletRequestListener
{
public static int destroys = 0;
public static int inits = 0;
@Override
public void requestDestroyed(ServletRequestEvent sre)
{
++destroys;
}
@Override
public void requestInitialized(ServletRequestEvent sre)
{
++inits;
}
}
public static class MyRAListener implements ServletRequestAttributeListener
{
public static int adds = 0;
public static int removes = 0;
public static int replaces = 0;
@Override
public void attributeAdded(ServletRequestAttributeEvent srae)
{
++adds;
}
@Override
public void attributeRemoved(ServletRequestAttributeEvent srae)
{
++removes;
}
@Override
public void attributeReplaced(ServletRequestAttributeEvent srae)
{
++replaces;
}
}
public static class MySListener implements HttpSessionListener
{
public static int creates = 0;
public static int destroys = 0;
@Override
public void sessionCreated(HttpSessionEvent se)
{
++creates;
}
@Override
public void sessionDestroyed(HttpSessionEvent se)
{
++destroys;
}
}
public static class MySAListener implements HttpSessionAttributeListener
{
public static int adds = 0;
public static int removes = 0;
public static int replaces = 0;
@Override
public void attributeAdded(HttpSessionBindingEvent event)
{
++adds;
}
@Override
public void attributeRemoved(HttpSessionBindingEvent event)
{
++removes;
}
@Override
public void attributeReplaced(HttpSessionBindingEvent event)
{
++replaces;
}
}
public static class MySIListener implements HttpSessionIdListener
{
public static int changes = 0;
@Override
public void sessionIdChanged(HttpSessionEvent event, String oldSessionId)
{
++changes;
}
}
public class InitialListener implements ServletContextListener
{
@Override
public void contextInitialized(ServletContextEvent sce)
{
//Add all of the sorts of listeners that are allowed
try
{
MySCAListener mySCAListener = sce.getServletContext().createListener(MySCAListener.class);
sce.getServletContext().addListener(mySCAListener);
MyRequestListener myRequestListener = sce.getServletContext().createListener(MyRequestListener.class);
sce.getServletContext().addListener(myRequestListener);
MyRAListener myRAListener = sce.getServletContext().createListener(MyRAListener.class);
sce.getServletContext().addListener(myRAListener);
MySListener mySListener = sce.getServletContext().createListener(MySListener.class);
sce.getServletContext().addListener(mySListener);
MySAListener mySAListener = sce.getServletContext().createListener(MySAListener.class);
sce.getServletContext().addListener(mySAListener);
MySIListener mySIListener = sce.getServletContext().createListener(MySIListener.class);
sce.getServletContext().addListener(mySIListener);
}
catch (Exception e)
{
fail(e);
}
//And also test you can't add a ServletContextListener from a ServletContextListener
try
{
MyContextListener contextListener = sce.getServletContext().createListener(MyContextListener.class);
sce.getServletContext().addListener(contextListener);
fail("Adding SCI from an SCI!");
}
catch (IllegalArgumentException e)
{
//expected
}
catch (Exception x)
{
fail(x);
}
sce.getServletContext().setAttribute("foo", "bar");
}
@Override
public void contextDestroyed(ServletContextEvent sce)
{
}
}
@BeforeEach
public void createServer()
@ -232,6 +426,114 @@ public class ServletContextHandlerTest
assertTrue((Boolean)root.getServletContext().getAttribute("MySCI.startup"));
assertTrue((Boolean)root.getServletContext().getAttribute("MyContextListener.contextInitialized"));
}
@Test
public void testListenersFromContextListener() throws Exception
{
ContextHandlerCollection contexts = new ContextHandlerCollection();
_server.setHandler(contexts);
ServletContextHandler root = new ServletContextHandler(contexts, "/", ServletContextHandler.SESSIONS);
ListenerHolder initialListener = new ListenerHolder();
initialListener.setListener(new InitialListener());
root.getServletHandler().addListener(initialListener);
ServletHolder holder0 = root.addServlet(TestServlet.class, "/test");
_server.start();
ListenerHolder[] listenerHolders = root.getServletHandler().getListeners();
assertNotNull(listenerHolders);
for (ListenerHolder l : listenerHolders)
{
assertTrue(l.isStarted());
assertNotNull(l.getListener());
//all listeners except the first should be programmatic
if (!"org.eclipse.jetty.servlet.ServletContextHandlerTest$InitialListener".equals(l.getClassName()))
{
assertFalse(root.isDurableListener(l.getListener()));
assertTrue(root.isProgrammaticListener(l.getListener()));
}
}
EventListener[] listeners = root.getEventListeners();
assertNotNull(listeners);
List<String> listenerClassNames = new ArrayList<>();
for (EventListener l : listeners)
listenerClassNames.add(l.getClass().getName());
assertTrue(listenerClassNames.contains("org.eclipse.jetty.servlet.ServletContextHandlerTest$MySCAListener"));
assertTrue(listenerClassNames.contains("org.eclipse.jetty.servlet.ServletContextHandlerTest$MyRequestListener"));
assertTrue(listenerClassNames.contains("org.eclipse.jetty.servlet.ServletContextHandlerTest$MyRAListener"));
assertTrue(listenerClassNames.contains("org.eclipse.jetty.servlet.ServletContextHandlerTest$MySListener"));
assertTrue(listenerClassNames.contains("org.eclipse.jetty.servlet.ServletContextHandlerTest$MySAListener"));
assertTrue(listenerClassNames.contains("org.eclipse.jetty.servlet.ServletContextHandlerTest$MySIListener"));
//test ServletRequestAttributeListener
String response = _connector.getResponse("GET /test?req=all HTTP/1.0\r\n\r\n");
assertThat(response, Matchers.containsString("200 OK"));
assertEquals(1, MyRAListener.adds);
assertEquals(1, MyRAListener.replaces);
assertEquals(1, MyRAListener.removes);
//test HttpSessionAttributeListener
response = _connector.getResponse("GET /test?session=create HTTP/1.0\r\n\r\n");
String sessionid = response.substring(response.indexOf("JSESSIONID"), response.indexOf(";"));
assertThat(response, Matchers.containsString("200 OK"));
assertEquals(1, MySListener.creates);
assertEquals(1, MySAListener.adds);
assertEquals(0, MySAListener.replaces);
assertEquals(0, MySAListener.removes);
StringBuffer request = new StringBuffer();
request.append("GET /test?session=replace HTTP/1.0\n");
request.append("Host: localhost\n");
request.append("Cookie: "+sessionid+"\n");
request.append("\n");
response = _connector.getResponse(request.toString());
assertThat(response, Matchers.containsString("200 OK"));
assertEquals(1, MySListener.creates);
assertEquals(1, MySAListener.adds);
assertEquals(1, MySAListener.replaces);
assertEquals(0, MySAListener.removes);
request = new StringBuffer();
request.append("GET /test?session=remove HTTP/1.0\n");
request.append("Host: localhost\n");
request.append("Cookie: "+sessionid+"\n");
request.append("\n");
response = _connector.getResponse(request.toString());
assertThat(response, Matchers.containsString("200 OK"));
assertEquals(1, MySListener.creates);
assertEquals(1, MySAListener.adds);
assertEquals(1, MySAListener.replaces);
assertEquals(1, MySAListener.removes);
//test HttpSessionIdListener.sessionIdChanged
request = new StringBuffer();
request.append("GET /test?session=change HTTP/1.0\n");
request.append("Host: localhost\n");
request.append("Cookie: "+sessionid+"\n");
request.append("\n");
response = _connector.getResponse(request.toString());
assertThat(response, Matchers.containsString("200 OK"));
assertEquals(1, MySIListener.changes);
sessionid = response.substring(response.indexOf("JSESSIONID"), response.indexOf(";"));
//test HttpServletListener.sessionDestroyed
request = new StringBuffer();
request.append("GET /test?session=delete HTTP/1.0\n");
request.append("Host: localhost\n");
request.append("Cookie: "+sessionid+"\n");
request.append("\n");
response = _connector.getResponse(request.toString());
assertThat(response, Matchers.containsString("200 OK"));
assertEquals(1, MySListener.destroys);
//test ServletContextAttributeListener
//attribute was set when context listener registered
assertEquals(1, MySCAListener.adds);
response = _connector.getResponse("GET /test?ctx=all HTTP/1.0\r\n\r\n");
assertThat(response, Matchers.containsString("200 OK"));
assertEquals(1, MySCAListener.replaces);
assertEquals(1, MySCAListener.removes);
}
@Test
public void testFindContainer() throws Exception
@ -670,6 +972,62 @@ public class ServletContextHandlerTest
resp.setStatus(HttpServletResponse.SC_OK);
PrintWriter writer = resp.getWriter();
writer.write("Test");
String action = req.getParameter("session");
if (!Objects.isNull(action))
{
if ("create".equalsIgnoreCase(action))
{
//Make a session
HttpSession session = req.getSession(true);
session.setAttribute("some", "thing");
}
else if ("change".equalsIgnoreCase(action))
{
HttpSession session = req.getSession(true);
req.changeSessionId();
}
else if ("replace".equalsIgnoreCase(action))
{
HttpSession session = req.getSession(false);
session.setAttribute("some", "other");
}
else if ("remove".equalsIgnoreCase(action))
{
HttpSession session = req.getSession(false);
session.removeAttribute("some");
}
else if ("delete".equalsIgnoreCase(action))
{
HttpSession session = req.getSession(false);
session.invalidate();
}
else
resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return;
}
action = req.getParameter("req");
if (!Objects.isNull(action))
{
//test all attribute ops
req.setAttribute("some", "value");
req.setAttribute("some", "other");
req.removeAttribute("some");
return;
}
action = req.getParameter("ctx");
if (!Objects.isNull(action))
{
//change and remove context attribute
req.getServletContext().setAttribute("foo", "foo");
req.getServletContext().removeAttribute("foo");
return;
}
}
}
}

View File

@ -151,7 +151,7 @@ public class GzipTester
digester = new DigestOutputStream(uncompressedStream, digest);
IO.copy(in, digester);
byte output[] = uncompressedStream.toByteArray();
byte[] output = uncompressedStream.toByteArray();
String actualSha1Sum = Hex.asHex(digest.digest());
return new ContentMetadata(output.length, actualSha1Sum);
}

View File

@ -29,7 +29,7 @@ public final class Hex
throw new IllegalArgumentException(String.format("Invalid ID length of <%d> expected range of <0> to <%d>", id.length(), (size * 2)));
}
byte buf[] = new byte[size];
byte[] buf = new byte[size];
byte hex;
int len = id.length();
@ -60,7 +60,7 @@ public final class Hex
public static String asHex(byte buf[])
{
int len = buf.length;
char out[] = new char[len * 2];
char[] out = new char[len * 2];
for (int i = 0; i < len; i++)
{
out[i * 2] = hexcodes[(buf[i] & 0xF0) >> 4];

View File

@ -45,7 +45,7 @@ public class ModuleGraphWriterTest
// Test Env
Path homeDir = MavenTestingUtils.getTestResourcePathDir("dist-home");
Path baseDir = testdir.getEmptyPathDir();
String cmdLine[] = new String[]{"jetty.version=TEST"};
String[] cmdLine = new String[]{"jetty.version=TEST"};
// Configuration
CommandLineConfigSource cmdLineSource = new CommandLineConfigSource(cmdLine);

View File

@ -48,7 +48,7 @@ public class ModuleTest
// Test Env
Path homeDir = MavenTestingUtils.getTestResourcePathDir("dist-home");
Path baseDir = testdir.getEmptyPathDir();
String cmdLine[] = new String[]{"jetty.version=TEST"};
String[] cmdLine = new String[]{"jetty.version=TEST"};
// Configuration
CommandLineConfigSource cmdLineSource = new CommandLineConfigSource(cmdLine);

View File

@ -50,7 +50,7 @@ public class ModulesTest
// Test Env
File homeDir = MavenTestingUtils.getTestResourceDir("dist-home");
File baseDir = testdir.getEmptyPathDir().toFile();
String cmdLine[] = new String[]{"jetty.version=TEST"};
String[] cmdLine = new String[]{"jetty.version=TEST"};
// Configuration
CommandLineConfigSource cmdLineSource = new CommandLineConfigSource(cmdLine);
@ -109,7 +109,7 @@ public class ModulesTest
// intentionally setup top level resources dir (as this would have many
// deep references)
File baseDir = MavenTestingUtils.getTestResourcesDir();
String cmdLine[] = new String[]{"jetty.version=TEST"};
String[] cmdLine = new String[]{"jetty.version=TEST"};
// Configuration
CommandLineConfigSource cmdLineSource = new CommandLineConfigSource(cmdLine);
@ -146,7 +146,7 @@ public class ModulesTest
// Test Env
File homeDir = MavenTestingUtils.getTestResourceDir("dist-home");
File baseDir = testdir.getEmptyPathDir().toFile();
String cmdLine[] = new String[]{"jetty.version=TEST"};
String[] cmdLine = new String[]{"jetty.version=TEST"};
// Configuration
CommandLineConfigSource cmdLineSource = new CommandLineConfigSource(cmdLine);

View File

@ -297,7 +297,7 @@ public class ConfigSourcesTest
ConfigSources sources = new ConfigSources();
String cmdLine[] = new String[0];
String[] cmdLine = new String[0];
sources.add(new CommandLineConfigSource(cmdLine));
sources.add(new JettyHomeConfigSource(home));
sources.add(new JettyBaseConfigSource(base));
@ -337,7 +337,7 @@ public class ConfigSourcesTest
ConfigSources sources = new ConfigSources();
String cmdLine[] = new String[0];
String[] cmdLine = new String[0];
sources.add(new CommandLineConfigSource(cmdLine));
sources.add(new JettyHomeConfigSource(home));
sources.add(new JettyBaseConfigSource(base));
@ -383,7 +383,7 @@ public class ConfigSourcesTest
ConfigSources sources = new ConfigSources();
String cmdLine[] = new String[0];
String[] cmdLine = new String[0];
sources.add(new CommandLineConfigSource(cmdLine));
sources.add(new JettyHomeConfigSource(home));
sources.add(new JettyBaseConfigSource(base));
@ -431,7 +431,7 @@ public class ConfigSourcesTest
ConfigSources sources = new ConfigSources();
String cmdLine[] = new String[0];
String[] cmdLine = new String[0];
sources.add(new CommandLineConfigSource(cmdLine));
sources.add(new JettyHomeConfigSource(home));
sources.add(new JettyBaseConfigSource(base));
@ -485,7 +485,7 @@ public class ConfigSourcesTest
ConfigSources sources = new ConfigSources();
String cmdLine[] = new String[]{
String[] cmdLine = new String[]{
// command line provided include-jetty-dir ref
"--include-jetty-dir=" + devops.toString()
};
@ -536,7 +536,7 @@ public class ConfigSourcesTest
ConfigSources sources = new ConfigSources();
String cmdLine[] = new String[]{
String[] cmdLine = new String[]{
// command line property should override all others
"jetty.http.port=7070"
};
@ -594,7 +594,7 @@ public class ConfigSourcesTest
UsageException e = assertThrows(UsageException.class, () ->
{
String cmdLine[] = new String[0];
String[] cmdLine = new String[0];
sources.add(new CommandLineConfigSource(cmdLine));
sources.add(new JettyHomeConfigSource(home));
sources.add(new JettyBaseConfigSource(base));

View File

@ -167,7 +167,7 @@ public class CorrectMavenCentralRefs
String rawpath = line.substring(idx + keyword.length(), pipe);
String destpath = line.substring(pipe + 1);
String parts[] = rawpath.split("/");
String[] parts = rawpath.split("/");
int rev = parts.length;
String filename = parts[--rev];

View File

@ -837,6 +837,7 @@ public class JSON
case '\r':
case '\n':
commentState = 0;
break;
default:
break;
}

View File

@ -759,9 +759,6 @@ public class BlockingArrayQueue<E> extends AbstractList<E> implements BlockingQu
}
}
/* Additional methods */
/**
* @return the current capacity of this queue
*/
@ -786,9 +783,6 @@ public class BlockingArrayQueue<E> extends AbstractList<E> implements BlockingQu
return _maxCapacity;
}
/* Implementation methods */
private boolean grow()
{
if (_growCapacity <= 0)

View File

@ -193,6 +193,11 @@ public class IncludeExcludeSet<T, P> implements Predicate<P>
return !_includes.isEmpty();
}
public boolean hasExcludes()
{
return !_excludes.isEmpty();
}
public int size()
{
return _includes.size() + _excludes.size();

View File

@ -288,8 +288,9 @@ public abstract class IteratingCallback implements Callback
}
default:
throw new IllegalStateException(String.format("%s[action=%s]", this, action));
break;
}
throw new IllegalStateException(String.format("%s[action=%s]", this, action));
}
case CALLED:

View File

@ -117,6 +117,7 @@ public class MultiException extends Exception
throw (Error)th;
if (th instanceof Exception)
throw (Exception)th;
throw new MultiException(nested);
default:
throw new MultiException(nested);
}

View File

@ -19,6 +19,7 @@
package org.eclipse.jetty.util.resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
@ -378,14 +379,9 @@ public class PathResource extends Resource
@Override
public InputStream getInputStream() throws IOException
{
/* Mimic behavior from old FileResource class and its
* usage of java.io.FileInputStream(File) which will trigger
* an IOException on construction if the path is a directory
*/
if (Files.isDirectory(path))
throw new IOException(path + " is a directory");
return Files.newInputStream(path, StandardOpenOption.READ);
// Use a FileInputStream rather than Files.newInputStream(path)
// since it produces a stream with a fast skip implementation
return new FileInputStream(getFile());
}
@Override

View File

@ -311,11 +311,14 @@ public abstract class Resource implements ResourceFactory, Closeable
return r.isContainedIn(containingResource);
}
//@checkstyle-disable-check : NoFinalizer
@Override
protected void finalize()
{
close();
}
//@checkstyle-enable-check : NoFinalizer
public abstract boolean isContainedIn(Resource r) throws MalformedURLException;

View File

@ -194,7 +194,7 @@ public class BufferUtilTest
@Test
public void testToBuffer_Array()
{
byte arr[] = new byte[128];
byte[] arr = new byte[128];
Arrays.fill(arr, (byte)0x44);
ByteBuffer buf = BufferUtil.toBuffer(arr);
@ -212,7 +212,7 @@ public class BufferUtilTest
@Test
public void testToBuffer_ArrayOffsetLength()
{
byte arr[] = new byte[128];
byte[] arr = new byte[128];
Arrays.fill(arr, (byte)0xFF); // fill whole thing with FF
int offset = 10;
int length = 100;

View File

@ -421,7 +421,7 @@ public class LazyListTest
@Test
public void testAddArray_NullInput_NullArray()
{
String arr[] = null;
String[] arr = null;
Object list = LazyList.addArray(null, arr);
assertNull(list);
}
@ -432,7 +432,7 @@ public class LazyListTest
@Test
public void testAddArray_NullInput_EmptyArray()
{
String arr[] = new String[0];
String[] arr = new String[0];
Object list = LazyList.addArray(null, arr);
if (STRICT)
{
@ -447,7 +447,7 @@ public class LazyListTest
@Test
public void testAddArray_NullInput_SingleArray()
{
String arr[] = new String[]{"a"};
String[] arr = new String[]{"a"};
Object list = LazyList.addArray(null, arr);
assertNotNull(list);
if (STRICT)
@ -464,7 +464,7 @@ public class LazyListTest
@Test
public void testAddArray_NullInput_Array()
{
String arr[] = new String[]{"a", "b", "c"};
String[] arr = new String[]{"a", "b", "c"};
Object list = LazyList.addArray(null, arr);
assertNotNull(list);
assertTrue(list instanceof List);
@ -481,7 +481,7 @@ public class LazyListTest
public void testAddArray_NonListInput_NullArray()
{
String input = "z";
String arr[] = null;
String[] arr = null;
Object list = LazyList.addArray(input, arr);
assertNotNull(list);
if (STRICT)
@ -499,7 +499,7 @@ public class LazyListTest
public void testAddArray_NonListInput_EmptyArray()
{
String input = "z";
String arr[] = new String[0];
String[] arr = new String[0];
Object list = LazyList.addArray(input, arr);
assertNotNull(list);
if (STRICT)
@ -517,7 +517,7 @@ public class LazyListTest
public void testAddArray_NonListInput_SingleArray()
{
String input = "z";
String arr[] = new String[]{"a"};
String[] arr = new String[]{"a"};
Object list = LazyList.addArray(input, arr);
assertNotNull(list);
assertTrue(list instanceof List);
@ -533,7 +533,7 @@ public class LazyListTest
public void testAddArray_NonListInput_Array()
{
String input = "z";
String arr[] = new String[]{"a", "b", "c"};
String[] arr = new String[]{"a", "b", "c"};
Object list = LazyList.addArray(input, arr);
assertNotNull(list);
assertTrue(list instanceof List);
@ -554,7 +554,7 @@ public class LazyListTest
input = LazyList.add(input, "y");
input = LazyList.add(input, "z");
String arr[] = null;
String[] arr = null;
Object list = LazyList.addArray(input, arr);
assertNotNull(list);
assertTrue(list instanceof List);
@ -574,7 +574,7 @@ public class LazyListTest
input = LazyList.add(input, "y");
input = LazyList.add(input, "z");
String arr[] = new String[0];
String[] arr = new String[0];
Object list = LazyList.addArray(input, arr);
assertNotNull(list);
assertTrue(list instanceof List);
@ -594,7 +594,7 @@ public class LazyListTest
input = LazyList.add(input, "y");
input = LazyList.add(input, "z");
String arr[] = new String[]{"a"};
String[] arr = new String[]{"a"};
Object list = LazyList.addArray(input, arr);
assertNotNull(list);
assertTrue(list instanceof List);
@ -615,7 +615,7 @@ public class LazyListTest
input = LazyList.add(input, "y");
input = LazyList.add(input, "z");
String arr[] = new String[]{"a", "b", "c"};
String[] arr = new String[]{"a", "b", "c"};
Object list = LazyList.addArray(input, arr);
assertNotNull(list);
assertTrue(list instanceof List);
@ -639,7 +639,7 @@ public class LazyListTest
input.add("y");
input.add("z");
String arr[] = null;
String[] arr = null;
Object list = LazyList.addArray(input, arr);
assertNotNull(list);
assertTrue(list instanceof List);
@ -660,7 +660,7 @@ public class LazyListTest
input.add("y");
input.add("z");
String arr[] = new String[0];
String[] arr = new String[0];
Object list = LazyList.addArray(input, arr);
assertNotNull(list);
assertTrue(list instanceof List);
@ -681,7 +681,7 @@ public class LazyListTest
input.add("y");
input.add("z");
String arr[] = new String[]{"a"};
String[] arr = new String[]{"a"};
Object list = LazyList.addArray(input, arr);
assertNotNull(list);
assertTrue(list instanceof List);
@ -703,7 +703,7 @@ public class LazyListTest
input.add("y");
input.add("z");
String arr[] = new String[]{"a", "b", "c"};
String[] arr = new String[]{"a", "b", "c"};
Object list = LazyList.addArray(input, arr);
assertNotNull(list);
assertTrue(list instanceof List);
@ -1285,7 +1285,7 @@ public class LazyListTest
assertTrue(arr.getClass().isArray());
assertTrue(arr instanceof String[]);
String strs[] = (String[])arr;
String[] strs = (String[])arr;
assertEquals(1, strs.length);
assertEquals("a", strs[0]);
}
@ -1305,7 +1305,7 @@ public class LazyListTest
assertTrue(arr.getClass().isArray());
assertTrue(arr instanceof String[]);
String strs[] = (String[])arr;
String[] strs = (String[])arr;
assertEquals(3, strs.length);
assertEquals("a", strs[0]);
assertEquals("b", strs[1]);
@ -1328,7 +1328,7 @@ public class LazyListTest
assertTrue(arr.getClass().isArray());
assertTrue(arr instanceof int[]);
int nums[] = (int[])arr;
int[] nums = (int[])arr;
assertEquals(4, nums.length);
assertEquals(22, nums[0]);
assertEquals(333, nums[1]);
@ -1352,7 +1352,7 @@ public class LazyListTest
assertTrue(arr.getClass().isArray());
assertTrue(arr instanceof String[]);
String strs[] = (String[])arr;
String[] strs = (String[])arr;
assertEquals(3, strs.length);
assertEquals("a", strs[0]);
assertEquals("b", strs[1]);
@ -1832,7 +1832,7 @@ public class LazyListTest
@Test
public void testArray2List_NullInput()
{
Object input[] = null;
Object[] input = null;
Object list = ArrayUtil.asMutableList(input);
assertNotNull(list);
@ -1846,7 +1846,7 @@ public class LazyListTest
@Test
public void testArray2List_EmptyInput()
{
String input[] = new String[0];
String[] input = new String[0];
Object list = ArrayUtil.asMutableList(input);
assertNotNull(list);
@ -1860,7 +1860,7 @@ public class LazyListTest
@Test
public void testArray2List_SingleInput()
{
String input[] = new String[]{"a"};
String[] input = new String[]{"a"};
Object list = ArrayUtil.asMutableList(input);
assertNotNull(list);
@ -1875,7 +1875,7 @@ public class LazyListTest
@Test
public void testArray2List_MultiInput()
{
String input[] = new String[]{"a", "b", "c"};
String[] input = new String[]{"a", "b", "c"};
Object list = ArrayUtil.asMutableList(input);
assertNotNull(list);
@ -1892,7 +1892,7 @@ public class LazyListTest
@Test
public void testArray2List_GenericsInput()
{
String input[] = new String[]{"a", "b", "c"};
String[] input = new String[]{"a", "b", "c"};
// Test the Generics definitions for array2List
List<String> list = ArrayUtil.asMutableList(input);
@ -1910,9 +1910,9 @@ public class LazyListTest
@Test
public void testAddToArray_NullInput_NullItem()
{
Object input[] = null;
Object[] input = null;
Object arr[] = ArrayUtil.addToArray(input, null, Object.class);
Object[] arr = ArrayUtil.addToArray(input, null, Object.class);
assertNotNull(arr);
if (STRICT)
{
@ -1935,9 +1935,9 @@ public class LazyListTest
assumeTrue(STRICT);
// Harsh test case.
Object input[] = null;
Object[] input = null;
Object arr[] = ArrayUtil.addToArray(input, null, null);
Object[] arr = ArrayUtil.addToArray(input, null, null);
assertNotNull(arr);
if (STRICT)
{
@ -1956,9 +1956,9 @@ public class LazyListTest
@Test
public void testAddToArray_NullInput_SimpleItem()
{
Object input[] = null;
Object[] input = null;
Object arr[] = ArrayUtil.addToArray(input, "a", String.class);
Object[] arr = ArrayUtil.addToArray(input, "a", String.class);
assertNotNull(arr);
assertEquals(1, arr.length);
assertEquals("a", arr[0]);
@ -1976,9 +1976,9 @@ public class LazyListTest
@Test
public void testAddToArray_EmptyInput_NullItem()
{
String input[] = new String[0];
String[] input = new String[0];
String arr[] = ArrayUtil.addToArray(input, null, Object.class);
String[] arr = ArrayUtil.addToArray(input, null, Object.class);
assertNotNull(arr);
if (STRICT)
{
@ -1997,9 +1997,9 @@ public class LazyListTest
@Test
public void testAddToArray_EmptyInput_SimpleItem()
{
String input[] = new String[0];
String[] input = new String[0];
String arr[] = ArrayUtil.addToArray(input, "a", String.class);
String[] arr = ArrayUtil.addToArray(input, "a", String.class);
assertNotNull(arr);
assertEquals(1, arr.length);
assertEquals("a", arr[0]);
@ -2011,9 +2011,9 @@ public class LazyListTest
@Test
public void testAddToArray_SingleInput_NullItem()
{
String input[] = new String[]{"z"};
String[] input = new String[]{"z"};
String arr[] = ArrayUtil.addToArray(input, null, Object.class);
String[] arr = ArrayUtil.addToArray(input, null, Object.class);
assertNotNull(arr);
if (STRICT)
{
@ -2034,9 +2034,9 @@ public class LazyListTest
@Test
public void testAddToArray_SingleInput_SimpleItem()
{
String input[] = new String[]{"z"};
String[] input = new String[]{"z"};
String arr[] = ArrayUtil.addToArray(input, "a", String.class);
String[] arr = ArrayUtil.addToArray(input, "a", String.class);
assertNotNull(arr);
assertEquals(2, arr.length);
assertEquals("z", arr[0]);
@ -2049,9 +2049,9 @@ public class LazyListTest
@Test
public void testRemoveFromArray_NullInput_NullItem()
{
Object input[] = null;
Object[] input = null;
Object arr[] = ArrayUtil.removeFromArray(input, null);
Object[] arr = ArrayUtil.removeFromArray(input, null);
assertNull(arr);
}
@ -2061,9 +2061,9 @@ public class LazyListTest
@Test
public void testRemoveFromArray_NullInput_SimpleItem()
{
Object input[] = null;
Object[] input = null;
Object arr[] = ArrayUtil.removeFromArray(input, "a");
Object[] arr = ArrayUtil.removeFromArray(input, "a");
assertNull(arr);
}
@ -2073,9 +2073,9 @@ public class LazyListTest
@Test
public void testRemoveFromArray_EmptyInput_NullItem()
{
String input[] = new String[0];
String[] input = new String[0];
String arr[] = ArrayUtil.removeFromArray(input, null);
String[] arr = ArrayUtil.removeFromArray(input, null);
assertNotNull(arr, "Should not be null");
assertEquals(0, arr.length);
}
@ -2086,9 +2086,9 @@ public class LazyListTest
@Test
public void testRemoveFromArray_EmptyInput_SimpleItem()
{
String input[] = new String[0];
String[] input = new String[0];
String arr[] = ArrayUtil.removeFromArray(input, "a");
String[] arr = ArrayUtil.removeFromArray(input, "a");
assertNotNull(arr, "Should not be null");
assertEquals(0, arr.length);
}
@ -2099,9 +2099,9 @@ public class LazyListTest
@Test
public void testRemoveFromArray_SingleInput()
{
String input[] = new String[]{"a"};
String[] input = new String[]{"a"};
String arr[] = ArrayUtil.removeFromArray(input, null);
String[] arr = ArrayUtil.removeFromArray(input, null);
assertNotNull(arr, "Should not be null");
assertEquals(1, arr.length);
assertEquals("a", arr[0]);
@ -2118,9 +2118,9 @@ public class LazyListTest
@Test
public void testRemoveFromArray_MultiInput()
{
String input[] = new String[]{"a", "b", "c"};
String[] input = new String[]{"a", "b", "c"};
String arr[] = ArrayUtil.removeFromArray(input, null);
String[] arr = ArrayUtil.removeFromArray(input, null);
assertNotNull(arr, "Should not be null");
assertEquals(3, arr.length);
assertEquals("a", arr[0]);

View File

@ -136,7 +136,7 @@ public class MultiMapTest
String key = "formats";
String input[] = {"gzip", "jar", "pack200"};
String[] input = {"gzip", "jar", "pack200"};
mm.putValues(key, input);
assertMapSize(mm, 1);
assertValues(mm, key, "gzip", "jar", "pack200");
@ -245,7 +245,7 @@ public class MultiMapTest
assertValues(mm, key, "gzip");
// Add to the key
String extras[] = {"jar", "pack200", "zip"};
String[] extras = {"jar", "pack200", "zip"};
mm.addValues(key, extras);
assertMapSize(mm, 1);
@ -268,7 +268,7 @@ public class MultiMapTest
assertValues(mm, key, "gzip");
// Add to the key
String extras[] = new String[0];
String[] extras = new String[0];
mm.addValues(key, extras);
assertMapSize(mm, 1);

View File

@ -262,7 +262,7 @@ public class PathWatcherTest
// average chunk buffer
int chunkBufLen = 16;
byte chunkBuf[] = new byte[chunkBufLen];
byte[] chunkBuf = new byte[chunkBufLen];
Arrays.fill(chunkBuf, (byte)'x');
long end = System.nanoTime() + timeUnit.toNanos(timeDuration);

View File

@ -83,7 +83,7 @@ public class TrieTest
@MethodSource("implementations")
public void testKeySet(Trie<Integer> trie) throws Exception
{
String values[] = new String[]{
String[] values = new String[]{
"hello",
"He",
"HELL",

View File

@ -85,7 +85,7 @@ public class URIUtilTest
assertEquals("f\u0629\u0629%23;,:=b a r", URIUtil.decodePath("f%d8%a9%d8%a9%2523%3b%2c:%3db%20a%20r"));
// Test for null character (real world ugly test case)
byte oddBytes[] = {'/', 0x00, '/'};
byte[] oddBytes = {'/', 0x00, '/'};
String odd = new String(oddBytes, StandardCharsets.ISO_8859_1);
assertEquals(odd, URIUtil.decodePath("/%00/"));
}

View File

@ -258,7 +258,7 @@ public class Utf8AppendableTest
@TestFactory
public Iterator<DynamicTest> testBadUtf8()
{
String samples[] = new String[]{
String[] samples = new String[]{
"c0af",
"EDA080",
"f08080af",

View File

@ -35,7 +35,7 @@ public final class Slf4jHelper
File testJarDir = MavenTestingUtils.getTargetFile("test-jars");
assumeTrue(testJarDir.exists()); // trigger @Ignore if dir not there
File jarfiles[] = testJarDir.listFiles(new FileFilter()
File[] jarfiles = testJarDir.listFiles(new FileFilter()
{
public boolean accept(File path)
{
@ -49,7 +49,7 @@ public final class Slf4jHelper
assumeTrue(jarfiles.length > 0); // trigger @Ignore if no jar files.
URL urls[] = new URL[jarfiles.length];
URL[] urls = new URL[jarfiles.length];
for (int i = 0; i < jarfiles.length; i++)
{
urls[i] = jarfiles[i].toURI().toURL();

View File

@ -621,7 +621,7 @@ public class FileSystemResourceTest
try (Resource base = newResource(resourceClass, dir.toFile()))
{
String list[] = base.list();
String[] list = base.list();
List<String> actual = Arrays.asList(list);
assertEquals(expected.size(), actual.size());

View File

@ -734,14 +734,14 @@ public class ClasspathPattern extends AbstractSet<String>
return false;
URI uri = location.get();
if (uri != null)
{
Boolean byLocation = locations.isIncludedAndNotExcluded(uri);
if (Boolean.FALSE == byLocation)
return false;
if (uri == null)
return locations.isEmpty() || locations.hasExcludes() && !locations.hasIncludes();
Boolean byLocation = locations.isIncludedAndNotExcluded(uri);
if (Boolean.FALSE == byLocation)
return false;
return Boolean.TRUE.equals(byName) || Boolean.TRUE.equals(byLocation) || !(names.hasIncludes() || locations.hasIncludes());
return Boolean.TRUE.equals(byName) || Boolean.TRUE.equals(byLocation) || !(names.hasIncludes() || locations.hasIncludes());
}
return false;
}
}

View File

@ -92,7 +92,7 @@ public class LargeMessageTest
// Issue connect using instance of class that extends Endpoint
Session session = container.connectToServer(echoer, wsUri);
byte buf[] = new byte[LARGER_THAN_DEFAULT_SIZE];
byte[] buf = new byte[LARGER_THAN_DEFAULT_SIZE];
Arrays.fill(buf, (byte)'x');
String message = new String(buf, UTF_8);
session.getBasicRemote().sendText(message);

View File

@ -63,7 +63,7 @@ public class MessageReceivingTest
public MessageReceivingTest()
{
byte raw[] = new byte[1024 * 1024];
byte[] raw = new byte[1024 * 1024];
Arrays.fill(raw, (byte)'x');
VERY_LONG_STRING = new String(raw, StandardCharsets.UTF_8);
}

View File

@ -43,7 +43,7 @@ public class ValidDualEncoder implements Encoder.Text<Integer>, Encoder.BinarySt
@Override
public void encode(Long object, OutputStream os) throws EncodeException, IOException
{
byte b[] = new byte[8];
byte[] b = new byte[8];
long v = object;
b[0] = (byte)(v >>> 56);
b[1] = (byte)(v >>> 48);

View File

@ -80,7 +80,7 @@ public class TypeTree
System.out.printf("%s (ParameterizedType) = %s%n", indent, ReflectUtils.toShortName(ptype));
// dumpTree(indent + ".ownerType()",ptype.getOwnerType());
dumpTree(indent + ".rawType(" + ReflectUtils.toShortName(ptype.getRawType()) + ")", ptype.getRawType());
Type args[] = ptype.getActualTypeArguments();
Type[] args = ptype.getActualTypeArguments();
if (args != null)
{
System.out.printf("%s.actualTypeArguments[].length = %d%n", indent, args.length);

View File

@ -90,7 +90,7 @@ public class LargeAnnotatedTest
// wait for connect
foo.get(1, TimeUnit.SECONDS);
// The message size should be bigger than default, but smaller than the limit that LargeEchoSocket specifies
byte txt[] = new byte[100 * 1024];
byte[] txt = new byte[100 * 1024];
Arrays.fill(txt, (byte)'o');
String msg = new String(txt, StandardCharsets.UTF_8);
clientEcho.sendMessage(msg);

View File

@ -79,7 +79,7 @@ public class LargeClientContainerServlet extends HttpServlet
size = Integer.parseInt(sizeParam);
}
byte buf[] = new byte[size];
byte[] buf = new byte[size];
Arrays.fill(buf, (byte)'x');
String destUrl = req.getParameter("destUrl");

View File

@ -77,7 +77,7 @@ public class LargeContainerTest
// wait for connect
foo.get(1, TimeUnit.SECONDS);
// The message size should be bigger than default, but smaller than the limit that LargeEchoSocket specifies
byte txt[] = new byte[100 * 1024];
byte[] txt = new byte[100 * 1024];
Arrays.fill(txt, (byte)'o');
String msg = new String(txt, StandardCharsets.UTF_8);
clientEcho.sendMessage(msg);

View File

@ -85,7 +85,7 @@ public class LargeOnOpenSessionConfiguredTest
// wait for connect
foo.get(1, TimeUnit.SECONDS);
// The message size should be bigger than default, but smaller than the limit that LargeEchoSocket specifies
byte txt[] = new byte[100 * 1024];
byte[] txt = new byte[100 * 1024];
Arrays.fill(txt, (byte)'o');
String msg = new String(txt, StandardCharsets.UTF_8);
clientEcho.sendMessage(msg);

View File

@ -78,7 +78,7 @@ public class LargeServerContainerAsClientContainerServlet extends HttpServlet
size = Integer.parseInt(sizeParam);
}
byte buf[] = new byte[size];
byte[] buf = new byte[size];
Arrays.fill(buf, (byte)'x');
String destUrl = req.getParameter("destUrl");

View File

@ -55,9 +55,9 @@ public class JsrBrowserSocket
@Override
public void run()
{
char letters[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-|{}[]():".toCharArray();
char[] letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-|{}[]():".toCharArray();
int lettersLen = letters.length;
char randomText[] = new char[size];
char[] randomText = new char[size];
Random rand = new Random(42);
String msg;
@ -141,7 +141,7 @@ public class JsrBrowserSocket
}
case "many":
{
String parts[] = StringUtil.csvSplit(val);
String[] parts = StringUtil.csvSplit(val);
int size = Integer.parseInt(parts[0]);
int count = Integer.parseInt(parts[1]);
@ -150,12 +150,12 @@ public class JsrBrowserSocket
}
case "manythreads":
{
String parts[] = StringUtil.csvSplit(val);
String[] parts = StringUtil.csvSplit(val);
int threadCount = Integer.parseInt(parts[0]);
int size = Integer.parseInt(parts[1]);
int count = Integer.parseInt(parts[2]);
Thread threads[] = new Thread[threadCount];
Thread[] threads = new Thread[threadCount];
// Setup threads
for (int n = 0; n < threadCount; n++)
@ -194,9 +194,9 @@ public class JsrBrowserSocket
private void writeManyAsync(int size, int count)
{
char letters[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-|{}[]():".toCharArray();
char[] letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-|{}[]():".toCharArray();
int lettersLen = letters.length;
char randomText[] = new char[size];
char[] randomText = new char[size];
Random rand = new Random(42);
for (int n = 0; n < count; n++)

View File

@ -43,7 +43,7 @@ public class PongMessageEndpoint extends Endpoint implements MessageHandler.Whol
@Override
public void onMessage(PongMessage pong)
{
byte buf[] = BufferUtil.toArray(pong.getApplicationData());
byte[] buf = BufferUtil.toArray(pong.getApplicationData());
String message = new String(buf, StandardCharsets.UTF_8);
this.session.getAsyncRemote().sendText("PongMessage[" + path + "]:" + message);
}

View File

@ -49,7 +49,7 @@ public class PongSocket
{
if (LOG.isDebugEnabled())
LOG.debug("onPong(): PongMessage.appData={}", BufferUtil.toDetailString(pong.getApplicationData()));
byte buf[] = BufferUtil.toArray(pong.getApplicationData());
byte[] buf = BufferUtil.toArray(pong.getApplicationData());
String message = new String(buf, StandardCharsets.UTF_8);
this.session.getAsyncRemote().sendText("@OnMessage(PongMessage)[" + path + "]:" + message);
}

View File

@ -0,0 +1,115 @@
//
// ========================================================================
// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.websocket.tests;
import java.net.URI;
import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.StatusCode;
import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.eclipse.jetty.websocket.common.WebSocketSession;
import org.eclipse.jetty.websocket.common.extensions.compress.CompressExtension;
import org.eclipse.jetty.websocket.servlet.WebSocketServlet;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class WriteAfterStopTest
{
public class UpgradeServlet extends WebSocketServlet
{
@Override
public void configure(WebSocketServletFactory factory)
{
factory.setCreator(((req, resp) -> serverSocket));
}
}
private Server server = new Server();
private WebSocketClient client = new WebSocketClient();
private EventSocket serverSocket = new EventSocket();
private ServerConnector connector;
@BeforeEach
public void start() throws Exception
{
connector = new ServerConnector(server);
server.addConnector(connector);
ServletContextHandler contextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
contextHandler.setContextPath("/");
contextHandler.addServlet(new ServletHolder(new UpgradeServlet()), "/");
server.setHandler(contextHandler);
server.start();
client.start();
}
@AfterEach
public void stop() throws Exception
{
client.stop();
server.stop();
}
@Test
public void test() throws Exception
{
URI uri = new URI("ws://localhost:" + connector.getLocalPort() + "/");
EventSocket clientSocket = new EventSocket();
ClientUpgradeRequest upgradeRequest = new ClientUpgradeRequest();
upgradeRequest.addExtensions("permessage-deflate");
Session session = client.connect(clientSocket, uri, upgradeRequest).get(5, TimeUnit.SECONDS);
clientSocket.getSession().getRemote().sendStringByFuture("init deflater");
assertThat(serverSocket.receivedMessages.poll(5, TimeUnit.SECONDS), is("init deflater"));
session.close(StatusCode.NORMAL, null);
// make sure both sides are closed
clientSocket.session.close();
assertTrue(clientSocket.closed.await(5, TimeUnit.SECONDS));
assertTrue(serverSocket.closed.await(5, TimeUnit.SECONDS));
// check we closed normally
assertThat(clientSocket.closeCode, is(StatusCode.NORMAL));
assertThat(serverSocket.closeCode, is(StatusCode.NORMAL));
((WebSocketSession)session).stop();
try (StacklessLogging stacklessLogging = new StacklessLogging(CompressExtension.class))
{
assertThrows(NullPointerException.class,
() -> session.getRemote().sendString("hello world"));
}
}
}

View File

@ -284,7 +284,7 @@ public class WebSocketClientTest
// Create string that is larger than default size of 64k
// but smaller than maxMessageSize of 100k
int size = 80 * 1024;
byte buf[] = new byte[size];
byte[] buf = new byte[size];
Arrays.fill(buf, (byte)'x');
String msg = StringUtil.toUTF8String(buf, 0, buf.length);

View File

@ -98,7 +98,7 @@ public class HttpClientInitTest
public void testXmlResourceInit() throws Exception
{
ClassLoader parent = Thread.currentThread().getContextClassLoader();
URL urls[] = new URL[]{
URL[] urls = new URL[]{
MavenTestingUtils.getTestResourceDir("httpclient/simple").toURI().toURL()
};
URLClassLoader classLoader = new URLClassLoader(urls, parent);

Some files were not shown because too many files have changed in this diff Show More