use of jakarta.servlet.ServletException in project tomcat by apache.
the class Request method upgrade.
@SuppressWarnings("unchecked")
@Override
public <T extends HttpUpgradeHandler> T upgrade(Class<T> httpUpgradeHandlerClass) throws java.io.IOException, ServletException {
T handler;
InstanceManager instanceManager = null;
try {
// need injection
if (InternalHttpUpgradeHandler.class.isAssignableFrom(httpUpgradeHandlerClass)) {
handler = httpUpgradeHandlerClass.getConstructor().newInstance();
} else {
instanceManager = getContext().getInstanceManager();
handler = (T) instanceManager.newInstance(httpUpgradeHandlerClass);
}
} catch (ReflectiveOperationException | NamingException | IllegalArgumentException | SecurityException e) {
throw new ServletException(e);
}
UpgradeToken upgradeToken = new UpgradeToken(handler, getContext(), instanceManager, getUpgradeProtocolName(httpUpgradeHandlerClass));
coyoteRequest.action(ActionCode.UPGRADE, upgradeToken);
// Output required by RFC2616. Protocol specific headers should have
// already been set.
response.setStatus(HttpServletResponse.SC_SWITCHING_PROTOCOLS);
return handler;
}
use of jakarta.servlet.ServletException in project tomcat by apache.
the class Request method parseParts.
private void parseParts(boolean explicit) {
// Return immediately if the parts have already been parsed
if (parts != null || partsParseException != null) {
return;
}
Context context = getContext();
MultipartConfigElement mce = getWrapper().getMultipartConfigElement();
if (mce == null) {
if (context.getAllowCasualMultipartParsing()) {
mce = new MultipartConfigElement(null, connector.getMaxPostSize(), connector.getMaxPostSize(), connector.getMaxPostSize());
} else {
if (explicit) {
partsParseException = new IllegalStateException(sm.getString("coyoteRequest.noMultipartConfig"));
return;
} else {
parts = Collections.emptyList();
return;
}
}
}
Parameters parameters = coyoteRequest.getParameters();
parameters.setLimit(getConnector().getMaxParameterCount());
boolean success = false;
try {
File location;
String locationStr = mce.getLocation();
if (locationStr == null || locationStr.length() == 0) {
location = ((File) context.getServletContext().getAttribute(ServletContext.TEMPDIR));
} else {
// If relative, it is relative to TEMPDIR
location = new File(locationStr);
if (!location.isAbsolute()) {
location = new File((File) context.getServletContext().getAttribute(ServletContext.TEMPDIR), locationStr).getAbsoluteFile();
}
}
if (!location.exists() && context.getCreateUploadTargets()) {
log.warn(sm.getString("coyoteRequest.uploadCreate", location.getAbsolutePath(), getMappingData().wrapper.getName()));
if (!location.mkdirs()) {
log.warn(sm.getString("coyoteRequest.uploadCreateFail", location.getAbsolutePath()));
}
}
if (!location.isDirectory()) {
parameters.setParseFailedReason(FailReason.MULTIPART_CONFIG_INVALID);
partsParseException = new IOException(sm.getString("coyoteRequest.uploadLocationInvalid", location));
return;
}
// Create a new file upload handler
DiskFileItemFactory factory = new DiskFileItemFactory();
try {
factory.setRepository(location.getCanonicalFile());
} catch (IOException ioe) {
parameters.setParseFailedReason(FailReason.IO_ERROR);
partsParseException = ioe;
return;
}
factory.setSizeThreshold(mce.getFileSizeThreshold());
ServletFileUpload upload = new ServletFileUpload();
upload.setFileItemFactory(factory);
upload.setFileSizeMax(mce.getMaxFileSize());
upload.setSizeMax(mce.getMaxRequestSize());
parts = new ArrayList<>();
try {
List<FileItem> items = upload.parseRequest(new ServletRequestContext(this));
int maxPostSize = getConnector().getMaxPostSize();
int postSize = 0;
Charset charset = getCharset();
for (FileItem item : items) {
ApplicationPart part = new ApplicationPart(item, location);
parts.add(part);
if (part.getSubmittedFileName() == null) {
String name = part.getName();
if (maxPostSize >= 0) {
// Have to calculate equivalent size. Not completely
// accurate but close enough.
postSize += name.getBytes(charset).length;
// Equals sign
postSize++;
// Value length
postSize += part.getSize();
// Value separator
postSize++;
if (postSize > maxPostSize) {
parameters.setParseFailedReason(FailReason.POST_TOO_LARGE);
throw new IllegalStateException(sm.getString("coyoteRequest.maxPostSizeExceeded"));
}
}
String value = null;
try {
value = part.getString(charset.name());
} catch (UnsupportedEncodingException uee) {
// Not possible
}
parameters.addParameter(name, value);
}
}
success = true;
} catch (InvalidContentTypeException e) {
parameters.setParseFailedReason(FailReason.INVALID_CONTENT_TYPE);
partsParseException = new ServletException(e);
} catch (SizeException e) {
parameters.setParseFailedReason(FailReason.POST_TOO_LARGE);
checkSwallowInput();
partsParseException = new IllegalStateException(e);
} catch (IOException e) {
parameters.setParseFailedReason(FailReason.IO_ERROR);
partsParseException = new IOException(e);
} catch (IllegalStateException e) {
// addParameters() will set parseFailedReason
checkSwallowInput();
partsParseException = e;
}
} finally {
// respect to changes in the remainder of the method.
if (partsParseException != null || !success) {
parameters.setParseFailedReason(FailReason.UNKNOWN);
}
}
}
use of jakarta.servlet.ServletException in project tomcat by apache.
the class JspRuntimeContext method checkCompile.
/**
* Method used by background thread to check the JSP dependencies
* registered with this class for JSP's.
*/
public void checkCompile() {
if (lastCompileCheck < 0) {
// Checking was disabled
return;
}
long now = System.currentTimeMillis();
if (now > (lastCompileCheck + (options.getCheckInterval() * 1000L))) {
lastCompileCheck = now;
} else {
return;
}
List<JspServletWrapper> wrappersToReload = new ArrayList<>();
// Tell JspServletWrapper to ignore the reload attribute while this
// check is in progress. See BZ 62603.
compileCheckInProgress = true;
Object[] wrappers = jsps.values().toArray();
for (Object wrapper : wrappers) {
JspServletWrapper jsw = (JspServletWrapper) wrapper;
JspCompilationContext ctxt = jsw.getJspEngineContext();
// Sync on JspServletWrapper when calling ctxt.compile()
synchronized (jsw) {
try {
ctxt.compile();
if (jsw.getReload()) {
wrappersToReload.add(jsw);
}
} catch (FileNotFoundException ex) {
ctxt.incrementRemoved();
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
jsw.getServletContext().log(Localizer.getMessage("jsp.error.backgroundCompilationFailed"), t);
}
}
}
// See BZ 62603.
// OK to process reload flag now.
compileCheckInProgress = false;
// Ensure all servlets and tags that need to be reloaded, are reloaded.
for (JspServletWrapper jsw : wrappersToReload) {
// Triggers reload
try {
if (jsw.isTagFile()) {
// conditions during the reload.
synchronized (this) {
jsw.loadTagFile();
}
} else {
jsw.getServlet();
}
} catch (ServletException e) {
jsw.getServletContext().log(Localizer.getMessage("jsp.error.reload"), e);
}
}
}
use of jakarta.servlet.ServletException in project tomcat by apache.
the class TestRequestFilterValve method oneTest.
private void oneTest(String allow, String deny, boolean denyStatus, boolean addConnectorPort, boolean usePeerAddress, boolean auth, String property, String type, boolean allowed) {
// PREPARE
RequestFilterValve valve = null;
Connector connector = new Connector();
Context context = new StandardContext();
Request request = new Request(connector);
Response response = new MockResponse();
StringBuilder msg = new StringBuilder();
int expected = allowed ? OK : FORBIDDEN;
connector.setPort(PORT);
request.getMappingData().context = context;
request.setCoyoteRequest(new org.apache.coyote.Request());
Assert.assertNotNull("Invalid test with null type", type);
request.setCoyoteRequest(new org.apache.coyote.Request());
if (property != null) {
if (type.equals("Addr")) {
valve = new RemoteAddrValve();
if (usePeerAddress) {
request.setRemoteAddr(ADDR_OTHER);
request.getCoyoteRequest().peerAddr().setString(property);
((RemoteAddrValve) valve).setUsePeerAddress(true);
msg.append(" peer='" + property + "'");
} else {
request.setRemoteAddr(property);
request.getCoyoteRequest().peerAddr().setString(ADDR_OTHER);
msg.append(" ip='" + property + "'");
}
} else if (type.equals("Host")) {
valve = new RemoteHostValve();
request.setRemoteHost(property);
msg.append(" host='" + property + "'");
} else if (type.equals("CIDR")) {
valve = new RemoteCIDRValve();
if (usePeerAddress) {
request.setRemoteAddr(ADDR_OTHER);
request.getCoyoteRequest().peerAddr().setString(property);
((RemoteCIDRValve) valve).setUsePeerAddress(true);
msg.append(" peer='" + property + "'");
} else {
request.setRemoteAddr(property);
request.getCoyoteRequest().peerAddr().setString(ADDR_OTHER);
msg.append(" ip='" + property + "'");
}
}
}
Assert.assertNotNull("Invalid test type" + type, valve);
valve.setNext(new TerminatingValve());
if (allow != null) {
valve.setAllow(allow);
msg.append(" allow='" + allow + "'");
}
if (deny != null) {
valve.setDeny(deny);
msg.append(" deny='" + deny + "'");
}
if (denyStatus) {
valve.setDenyStatus(CUSTOM);
msg.append(" denyStatus='" + CUSTOM + "'");
if (!allowed) {
expected = CUSTOM;
}
}
if (addConnectorPort) {
if (valve instanceof RemoteAddrValve) {
((RemoteAddrValve) valve).setAddConnectorPort(true);
} else if (valve instanceof RemoteHostValve) {
((RemoteHostValve) valve).setAddConnectorPort(true);
} else if (valve instanceof RemoteCIDRValve) {
((RemoteCIDRValve) valve).setAddConnectorPort(true);
} else {
Assert.fail("Can only set 'addConnectorPort' for RemoteAddrValve, RemoteHostValve and RemoteCIDRValve");
}
msg.append(" addConnectorPort='true'");
}
if (auth) {
context.setPreemptiveAuthentication(true);
valve.setInvalidAuthenticationWhenDeny(true);
msg.append(" auth='true'");
}
// TEST
try {
valve.invoke(request, response);
} catch (IOException | ServletException ex) {
// Ignore
}
// VERIFY
if (!allowed && auth) {
Assert.assertEquals(msg.toString(), OK, response.getStatus());
Assert.assertEquals(msg.toString(), "invalid", request.getHeader("authorization"));
} else {
Assert.assertEquals(msg.toString(), expected, response.getStatus());
}
}
use of jakarta.servlet.ServletException in project spring-security by spring-projects.
the class Saml2WebSsoAuthenticationRequestFilterTests method doFilterWhenPostThenSaveRedirectRequest.
@Test
public void doFilterWhenPostThenSaveRedirectRequest() throws ServletException, IOException {
RelyingPartyRegistration registration = this.rpBuilder.assertingPartyDetails((asserting) -> asserting.singleSignOnServiceBinding(Saml2MessageBinding.POST)).build();
Saml2AuthenticationRequestContext context = authenticationRequestContext().relyingPartyRegistration(registration).build();
Saml2PostAuthenticationRequest request = postAuthenticationRequest(context).build();
given(this.resolver.resolve(any())).willReturn(context);
given(this.factory.createPostAuthenticationRequest(any())).willReturn(request);
this.filter.doFilterInternal(this.request, this.response, this.filterChain);
verify(this.authenticationRequestRepository).saveAuthenticationRequest(any(Saml2PostAuthenticationRequest.class), eq(this.request), eq(this.response));
}
Aggregations