Java Code Examples for javax.servlet.ServletException#getMessage()

The following examples show how to use javax.servlet.ServletException#getMessage() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ModelRenderer.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
@Override
public void writeTo(final Model model, Class<?> type,
                    final Type genericType, final Annotation[] annotations,
                    final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders,
                    final OutputStream entityStream) throws WebApplicationException, IOException {
    model.data.forEach(request::setAttribute);
    try {
        request.getRequestDispatcher(model.path).forward(request, response);
    } catch (final ServletException e) {
        throw new InternalServerErrorException(e.getMessage(), e);
    }
}
 
Example 2
Source File: JaxWsWebServicePublisherBeanPostProcessor.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void setServletConfig(ServletConfig servletConfig) {
    try {
        shadowCxfServlet = (Servlet)servletClass.newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        throw new RuntimeException(e);
    }
    try {
        shadowCxfServlet.init(servletConfig);
    } catch (ServletException ex) {
        throw new RuntimeException(ex.getMessage(), ex);
    }
}
 
Example 3
Source File: ServletController.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void init() {
    if (servletConfig == null) {
        return;
    }

    String hideServiceList = servletConfig.getInitParameter("hide-service-list-page");
    if (!StringUtils.isEmpty(hideServiceList)) {
        this.isHideServiceList = Boolean.valueOf(hideServiceList);
    }

    String authServiceListPage = servletConfig.getInitParameter("service-list-page-authenticate");
    if (!StringUtils.isEmpty(authServiceListPage)) {
        this.isAuthServiceListPage = Boolean.valueOf(authServiceListPage);
    }

    String authServiceListRealm = servletConfig.getInitParameter("service-list-page-authenticate-realm");
    if (!StringUtils.isEmpty(authServiceListRealm)) {
        this.authServiceListPageRealm = authServiceListRealm;
    }

    String isDisableAddressUpdates = servletConfig.getInitParameter("disable-address-updates");
    if (!StringUtils.isEmpty(isDisableAddressUpdates)) {
        this.disableAddressUpdates = Boolean.valueOf(isDisableAddressUpdates);
    }
    String isForcedBaseAddress = servletConfig.getInitParameter("base-address");
    if (!StringUtils.isEmpty(isForcedBaseAddress)) {
        this.forcedBaseAddress = isForcedBaseAddress;
    }
    try {
        serviceListGenerator.init(servletConfig);
    } catch (ServletException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    String serviceListPath = servletConfig.getInitParameter("service-list-path");
    if (!StringUtils.isEmpty(serviceListPath)) {
        this.serviceListRelativePath = serviceListPath;
    }
}
 
Example 4
Source File: KeycloakOnUndertow.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void undeploy(Archive<?> archive) throws DeploymentException {
    if (isRemoteMode()) {
        log.infof("Skipped undeployment of '%s' as we are in remote mode!", archive.getName());
        return;
    }

    Field containerField = Reflections.findDeclaredField(UndertowJaxrsServer.class, "container");
    Reflections.setAccessible(containerField);
    ServletContainer container = (ServletContainer) Reflections.getFieldValue(containerField, undertow);

    DeploymentManager deploymentMgr = container.getDeployment(archive.getName());
    if (deploymentMgr != null) {
        DeploymentInfo deployment = deploymentMgr.getDeployment().getDeploymentInfo();

        try {
            deploymentMgr.stop();
        } catch (ServletException se) {
            throw new DeploymentException(se.getMessage(), se);
        }

        deploymentMgr.undeploy();

        Field rootField = Reflections.findDeclaredField(UndertowJaxrsServer.class, "root");
        Reflections.setAccessible(rootField);
        PathHandler root = (PathHandler) Reflections.getFieldValue(rootField, undertow);

        String path = deployedArchivesToContextPath.get(archive.getName());
        root.removePrefixPath(path);

        container.removeDeployment(deployment);
    } else {
        log.warnf("Deployment '%s' not found", archive.getName());
    }
}
 
Example 5
Source File: UndertowAppServer.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void undeploy(Archive<?> archive) throws DeploymentException {
    log.info("Undeploying archive " + archive.getName());
    Field containerField = Reflections.findDeclaredField(UndertowJaxrsServer.class, "container");
    Reflections.setAccessible(containerField);
    ServletContainer container = (ServletContainer) Reflections.getFieldValue(containerField, undertow);

    DeploymentManager deploymentMgr = container.getDeployment(archive.getName());
    if (deploymentMgr != null) {
        DeploymentInfo deployment = deploymentMgr.getDeployment().getDeploymentInfo();

        try {
            deploymentMgr.stop();
        } catch (ServletException se) {
            throw new DeploymentException(se.getMessage(), se);
        }

        deploymentMgr.undeploy();

        Field rootField = Reflections.findDeclaredField(UndertowJaxrsServer.class, "root");
        Reflections.setAccessible(rootField);
        PathHandler root = (PathHandler) Reflections.getFieldValue(rootField, undertow);

        String path = deployedArchivesToContextPath.get(archive.getName());
        root.removePrefixPath(path);

        container.removeDeployment(deployment);
    } else {
        log.warnf("Deployment '%s' not found", archive.getName());
    }
}
 
Example 6
Source File: ExtendsTag.java    From jsp-template-inheritance with Apache License 2.0 5 votes vote down vote up
@Override
public void doTag() throws JspException, IOException {
    StringWriter ignoredWriter = new StringWriter();
    getJspBody().invoke(ignoredWriter); // ignore body text

    PageContext pageContext = (PageContext) getJspContext();

    try {
        pageContext.forward(getRefinedName());
    } catch (ServletException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example 7
Source File: SSIServletExternalResolver.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Override
public String getFileText(String originalPath, boolean virtual)
        throws IOException {
    try {
        ServletContextAndPath csAndP = getServletContextAndPath(
                originalPath, virtual);
        ServletContext context = csAndP.getServletContext();
        String path = csAndP.getPath();
        RequestDispatcher rd = context.getRequestDispatcher(path);
        if (rd == null) {
            throw new IOException(
                    "Couldn't get request dispatcher for path: " + path);
        }
        ByteArrayServletOutputStream basos = new ByteArrayServletOutputStream();
        ResponseIncludeWrapper responseIncludeWrapper = new ResponseIncludeWrapper(res, basos);
        rd.include(req, responseIncludeWrapper);
        //We can't assume the included servlet flushed its output
        responseIncludeWrapper.flushOutputStreamOrWriter();
        byte[] bytes = basos.toByteArray();

        //Assume platform default encoding unless otherwise specified
        String retVal;
        if (inputEncoding == null) {
            retVal = new String( bytes );
        } else {
            retVal = new String (bytes,
                    B2CConverter.getCharset(inputEncoding));
        }

        //make an assumption that an empty response is a failure. This is
        // a problem
        // if a truly empty file
        //were included, but not sure how else to tell.
        if (retVal.equals("") && !req.getMethod().equalsIgnoreCase("HEAD")) {
            throw new IOException("Couldn't find file: " + path);
        }
        return retVal;
    } catch (ServletException e) {
        throw new IOException("Couldn't include file: " + originalPath
                + " because of ServletException: " + e.getMessage());
    }
}
 
Example 8
Source File: SSIServletExternalResolver.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
@Override
public String getFileText(String originalPath, boolean virtual)
        throws IOException {
    try {
        ServletContextAndPath csAndP = getServletContextAndPath(
                originalPath, virtual);
        ServletContext context = csAndP.getServletContext();
        String path = csAndP.getPath();
        RequestDispatcher rd = context.getRequestDispatcher(path);
        if (rd == null) {
            throw new IOException(
                    "Couldn't get request dispatcher for path: " + path);
        }
        ByteArrayServletOutputStream basos =
            new ByteArrayServletOutputStream();
        ResponseIncludeWrapper responseIncludeWrapper =
            new ResponseIncludeWrapper(context, req, res, basos);
        rd.include(req, responseIncludeWrapper);
        //We can't assume the included servlet flushed its output
        responseIncludeWrapper.flushOutputStreamOrWriter();
        byte[] bytes = basos.toByteArray();

        //Assume platform default encoding unless otherwise specified
        String retVal;
        if (inputEncoding == null) {
            retVal = new String( bytes );
        } else {
            retVal = new String (bytes,
                    B2CConverter.getCharset(inputEncoding));
        }

        //make an assumption that an empty response is a failure. This is
        // a problem
        // if a truly empty file
        //were included, but not sure how else to tell.
        if (retVal.equals("") && !req.getMethod().equalsIgnoreCase(
                org.apache.coyote.http11.Constants.HEAD)) {
            throw new IOException("Couldn't find file: " + path);
        }
        return retVal;
    } catch (ServletException e) {
        throw new IOException("Couldn't include file: " + originalPath
                + " because of ServletException: " + e.getMessage());
    }
}
 
Example 9
Source File: JspViewHandler.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
public void render(String name, String page, String contentType, String encoding, String info, HttpServletRequest request, HttpServletResponse response) throws ViewHandlerException {
    // some containers call filters on EVERY request, even forwarded ones,
    // so let it know that it came from the control servlet

    if (request == null) {
        throw new ViewHandlerException("Null HttpServletRequest object");
    }
    if (UtilValidate.isEmpty(page)) {
        throw new ViewHandlerException("Null or empty source");
    }

    //Debug.logInfo("Requested Page : " + page, module);
    //Debug.logInfo("Physical Path  : " + context.getRealPath(page));

    // tell the ContextFilter we are forwarding
    request.setAttribute(ContextFilter.FORWARDED_FROM_SERVLET, Boolean.TRUE);
    RequestDispatcher rd = request.getRequestDispatcher(page);

    if (rd == null) {
        Debug.logInfo("HttpServletRequest.getRequestDispatcher() failed; trying ServletContext", module);
        rd = context.getRequestDispatcher(page);
        if (rd == null) {
            Debug.logInfo("ServletContext.getRequestDispatcher() failed; trying ServletContext.getNamedDispatcher(\"jsp\")", module);
            rd = context.getNamedDispatcher("jsp");
            if (rd == null) {
                throw new ViewHandlerException("Source returned a null dispatcher (" + page + ")");
            }
        }
    }

    try {
        rd.include(request, response);
    } catch (IOException ie) {
        throw new ViewHandlerException("IO Error in view", ie);
    } catch (ServletException e) {
        Throwable throwable = e.getRootCause() != null ? e.getRootCause() : e;

        if (throwable instanceof JspException) {
            JspException jspe = (JspException) throwable;

            throwable = jspe.getCause() != null ? jspe.getCause() : jspe;
        }
        Debug.logError(throwable, "ServletException rendering JSP view", module);
        throw new ViewHandlerException(e.getMessage(), throwable);
    }
}
 
Example 10
Source File: SSIServletExternalResolver.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
@Override
public String getFileText(String originalPath, boolean virtual)
        throws IOException {
    try {
        ServletContextAndPath csAndP = getServletContextAndPath(
                originalPath, virtual);
        ServletContext context = csAndP.getServletContext();
        String path = csAndP.getPath();
        RequestDispatcher rd = context.getRequestDispatcher(path);
        if (rd == null) {
            throw new IOException(
                    "Couldn't get request dispatcher for path: " + path);
        }
        ByteArrayServletOutputStream basos =
            new ByteArrayServletOutputStream();
        ResponseIncludeWrapper responseIncludeWrapper =
            new ResponseIncludeWrapper(context, req, res, basos);
        rd.include(req, responseIncludeWrapper);
        //We can't assume the included servlet flushed its output
        responseIncludeWrapper.flushOutputStreamOrWriter();
        byte[] bytes = basos.toByteArray();

        //Assume platform default encoding unless otherwise specified
        String retVal;
        if (inputEncoding == null) {
            retVal = new String( bytes );
        } else {
            retVal = new String (bytes,
                    B2CConverter.getCharset(inputEncoding));
        }

        //make an assumption that an empty response is a failure. This is
        // a problem
        // if a truly empty file
        //were included, but not sure how else to tell.
        if (retVal.equals("") && !req.getMethod().equalsIgnoreCase(
                org.apache.coyote.http11.Constants.HEAD)) {
            throw new IOException("Couldn't find file: " + path);
        }
        return retVal;
    } catch (ServletException e) {
        throw new IOException("Couldn't include file: " + originalPath
                + " because of ServletException: " + e.getMessage());
    }
}
 
Example 11
Source File: WebUtils.java    From rice with Educational Community License v2.0 4 votes vote down vote up
public static void getMultipartParameters(HttpServletRequest request, ActionServletWrapper servletWrapper,
		ActionForm form, ActionMapping mapping) {
	Map params = new HashMap();

	// Get the ActionServletWrapper from the form bean
	// ActionServletWrapper servletWrapper = getServletWrapper();

	try {
		CommonsMultipartRequestHandler multipartHandler = new CommonsMultipartRequestHandler();
		if (multipartHandler != null) {
			// Set servlet and mapping info
			if (servletWrapper != null) {
				// from pojoformbase
				// servlet only affects tempdir on local disk
				servletWrapper.setServletFor(multipartHandler);
			}
			multipartHandler.setMapping((ActionMapping) request.getAttribute(Globals.MAPPING_KEY));
			// Initialize multipart request class handler
			multipartHandler.handleRequest(request);

			Collection<FormFile> files = multipartHandler.getFileElements().values();
			Enumeration keys = multipartHandler.getFileElements().keys();

			while (keys.hasMoreElements()) {
				Object key = keys.nextElement();
				FormFile file = (FormFile) multipartHandler.getFileElements().get(key);
				long maxSize = WebUtils.getMaxUploadSize(form);
				if (LOG.isDebugEnabled()) {
					LOG.debug(file.getFileSize());
				}
				if (maxSize > 0 && Long.parseLong(file.getFileSize() + "") > maxSize) {

					GlobalVariables.getMessageMap().putError(key.toString(),
							RiceKeyConstants.ERROR_UPLOADFILE_SIZE,
							new String[] { file.getFileName(), Long.toString(maxSize) });

				}
			}

			// get file elements for kualirequestprocessor
			if (servletWrapper == null) {
				request.setAttribute(KRADConstants.UPLOADED_FILE_REQUEST_ATTRIBUTE_KEY,
						getFileParametersForMultipartRequest(request, multipartHandler));
			}
		}
	}
	catch (ServletException e) {
		throw new ValidationException("unable to handle multipart request " + e.getMessage(), e);
	}
}
 
Example 12
Source File: JobDirectoryServerServiceImpl.java    From genie with Apache License 2.0 4 votes vote down vote up
private void handleRequest(
    final URI baseUri,
    final String relativePath,
    final HttpServletRequest request,
    final HttpServletResponse response,
    final DirectoryManifest manifest,
    final URI jobDirectoryRoot
) throws IOException, GenieNotFoundException, GenieServerException {
    log.debug(
        "Handle request, baseUri: '{}', relpath: '{}', jobRootUri: '{}'",
        baseUri,
        relativePath,
        jobDirectoryRoot
    );
    final DirectoryManifest.ManifestEntry entry = manifest.getEntry(relativePath).orElseThrow(
        () -> new GenieNotFoundException("No such entry in job manifest: " + relativePath)
    );

    if (entry.isDirectory()) {
        // For now maintain the V3 structure
        // TODO: Once we determine what we want for V4 use v3/v4 flags or some way to differentiate
        // TODO: there's no unit test covering this section
        final DefaultDirectoryWriter.Directory directory = new DefaultDirectoryWriter.Directory();
        final List<DefaultDirectoryWriter.Entry> files = Lists.newArrayList();
        final List<DefaultDirectoryWriter.Entry> directories = Lists.newArrayList();
        try {
            entry.getParent().ifPresent(
                parentPath -> {
                    final DirectoryManifest.ManifestEntry parentEntry = manifest
                        .getEntry(parentPath)
                        .orElseThrow(IllegalArgumentException::new);
                    directory.setParent(createEntry(parentEntry, baseUri));
                }
            );

            for (final String childPath : entry.getChildren()) {
                final DirectoryManifest.ManifestEntry childEntry = manifest
                    .getEntry(childPath)
                    .orElseThrow(IllegalArgumentException::new);

                if (childEntry.isDirectory()) {
                    directories.add(this.createEntry(childEntry, baseUri));
                } else {
                    files.add(this.createEntry(childEntry, baseUri));
                }
            }
        } catch (final IllegalArgumentException iae) {
            throw new GenieServerException("Error while traversing files manifest: " + iae.getMessage(), iae);
        }

        directories.sort(Comparator.comparing(DefaultDirectoryWriter.Entry::getName));
        files.sort(Comparator.comparing(DefaultDirectoryWriter.Entry::getName));

        directory.setDirectories(directories);
        directory.setFiles(files);

        final String accept = request.getHeader(HttpHeaders.ACCEPT);
        if (accept != null && accept.contains(MediaType.TEXT_HTML_VALUE)) {
            response.setContentType(MediaType.TEXT_HTML_VALUE);
            response
                .getOutputStream()
                .write(
                    DefaultDirectoryWriter
                        .directoryToHTML(entry.getName(), directory)
                        .getBytes(StandardCharsets.UTF_8)
                );
        } else {
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            GenieObjectMapper.getMapper().writeValue(response.getOutputStream(), directory);
        }
    } else {
        final URI location = jobDirectoryRoot.resolve(entry.getPath());
        final String locationString = location.toString()
            + (jobDirectoryRoot.getFragment() != null ? ("#" + jobDirectoryRoot.getFragment()) : "");
        log.debug("Get resource: {}", locationString);
        final Resource jobResource = this.resourceLoader.getResource(locationString);
        // Every file really should have a media type but if not use text/plain
        final String mediaType = entry.getMimeType().orElse(MediaType.TEXT_PLAIN_VALUE);
        final ResourceHttpRequestHandler handler = this.genieResourceHandlerFactory.get(mediaType, jobResource);
        try {
            handler.handleRequest(request, response);
        } catch (ServletException e) {
            throw new GenieServerException("Servlet exception: " + e.getMessage(), e);
        }
    }
}
 
Example 13
Source File: ViewImportSupport.java    From velocity-tools with Apache License 2.0 4 votes vote down vote up
/**
 *
 * @param url the local URL resource to return as string
 * @return the URL resource as string
 * @throws IOException if not allowed or if thrown by underlying code
 */
protected String acquireLocalURLString(String url) throws IOException
{
    // URL is local, so we must be an HTTP request
    if (!(request instanceof HttpServletRequest
        && response instanceof HttpServletResponse))
    {
        throw new IOException("Local import from non-HTTP request not allowed");
    }

    // retrieve an appropriate ServletContext
    // normalize the URL if we have an HttpServletRequest
    if (!url.startsWith("/"))
    {
        String sp = ((HttpServletRequest)request).getServletPath();
        url = sp.substring(0, sp.lastIndexOf('/')) + '/' + url;
    }

    // strip the session id from the url
    url = stripSession(url);

    // According to the 3.1 Servlet API specification, the query string parameters of the URL to include
    // take *precedence* over the original query string parameters. It means that:
    // - we must merge both query strings
    // - we must set aside the cached request toolbox during the include
    url = mergeQueryStrings(url);
    Object parentToolbox = request.getAttribute(Toolbox.KEY);
    request.removeAttribute(Toolbox.KEY);

    // from this context, get a dispatcher
    RequestDispatcher rd = application.getRequestDispatcher(url);
    if (rd == null)
    {
        throw new IOException("Couldn't get a RequestDispatcher for \""
            + url + "\"");
    }

    // include the resource, using our custom wrapper
    ImportResponseWrapper irw =
        new ImportResponseWrapper((HttpServletResponse)response);
    try
    {
        rd.include(request, irw);
    }
    catch (IOException ex)
    {
        throw new IOException("Problem importing the local URL \"" + url + "\": " + ex.getMessage(), ex);
    }
    catch (ServletException se)
    {
        throw new IOException("Problem importing the local URL \"" + url + "\": " + se.getMessage(), se);

    }
    finally
    {
        request.setAttribute(Toolbox.KEY, parentToolbox);
    }
    /* let RuntimeExceptions go through */

    // disallow inappropriate response codes per JSTL spec
    if (irw.getStatus() < 200 || irw.getStatus() > 299)
    {
        throw new IOException("Invalid response code '" + irw.getStatus()
            + "' for \"" + url + "\"");
    }

    // recover the response String from our wrapper
    return irw.getString();
}