Example usage for javax.servlet.http HttpServletRequest getClass

List of usage examples for javax.servlet.http HttpServletRequest getClass

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:jp.opencollector.guacamole.auth.delegated.DelegatedAuthenticationProvider.java

private static Optional<GuacamoleConfiguration> buildConfigurationFromRequest(HttpServletRequest req)
        throws GuacamoleException {
    try {/*from   ww  w  .ja  va2  s . co m*/
        if (req.getClass().getName().equals("org.glyptodon.guacamole.net.basic.rest.APIRequest")) {
            final GuacamoleConfiguration config = new GuacamoleConfiguration();
            final String protocol = req.getParameter("protocol");
            if (protocol == null)
                throw new GuacamoleException("required parameter \"protocol\" is missing");
            config.setProtocol(protocol);
            for (Map.Entry<String, String[]> param : req.getParameterMap().entrySet()) {
                String[] values = param.getValue();
                if (values.length > 0)
                    config.setParameter(param.getKey(), values[0]);
            }
            return Optional.of(config);
        } else {
            final ServletInputStream is = req.getInputStream();
            if (!is.isReady()) {
                MediaType contentType = MediaType.parse(req.getContentType());
                boolean invalidContentType = true;
                if (contentType.type().equals("application")) {
                    if (contentType.subtype().equals("json")) {
                        invalidContentType = false;
                    } else if (contentType.subtype().equals("x-www-form-urlencoded")
                            && req.getParameter("token") != null) {
                        return Optional.<GuacamoleConfiguration>absent();
                    }
                }
                if (invalidContentType)
                    throw new GuacamoleException(String.format("expecting application/json, got %s",
                            contentType.withoutParameters()));
                final GuacamoleConfiguration config = new GuacamoleConfiguration();
                try {
                    final ObjectMapper mapper = new ObjectMapper();
                    JsonNode root = (JsonNode) mapper.readTree(
                            createJsonParser(req.getInputStream(), contentType.charset().or(UTF_8), mapper));
                    {
                        final JsonNode protocol = root.get("protocol");
                        if (protocol == null)
                            throw new GuacamoleException("required parameter \"protocol\" is missing");
                        final JsonNode parameters = root.get("parameters");
                        if (parameters == null)
                            throw new GuacamoleException("required parameter \"parameters\" is missing");
                        config.setProtocol(protocol.asText());
                        {
                            for (Iterator<Entry<String, JsonNode>> i = parameters.fields(); i.hasNext();) {
                                Entry<String, JsonNode> member = i.next();
                                config.setParameter(member.getKey(), member.getValue().asText());
                            }
                        }
                    }
                } catch (ClassCastException e) {
                    throw new GuacamoleException("error occurred during parsing configuration", e);
                }
                return Optional.of(config);
            } else {
                return Optional.<GuacamoleConfiguration>absent();
            }
        }
    } catch (IOException e) {
        throw new GuacamoleException("error occurred during retrieving configuration from the request body", e);
    }
}

From source file:in.xebia.poc.FileUploadUtils.java

public static boolean parseFileUploadRequest(HttpServletRequest request, File outputFile,
        Map<String, String> params) throws Exception {
    log.debug("Request class? " + request.getClass().toString());
    log.debug("Request is multipart? " + ServletFileUpload.isMultipartContent(request));
    log.debug("Request method: " + request.getMethod());
    log.debug("Request params: ");
    for (Object key : request.getParameterMap().keySet()) {
        log.debug((String) key);/*from   w w  w.  ja va 2 s.com*/
    }
    log.debug("Request attribute names: ");

    boolean filedataInAttributes = false;
    Enumeration attrNames = request.getAttributeNames();
    while (attrNames.hasMoreElements()) {
        String attrName = (String) attrNames.nextElement();
        log.debug(attrName);
        if ("filedata".equals(attrName)) {
            filedataInAttributes = true;
        }
    }

    if (filedataInAttributes) {
        log.debug("Found filedata in request attributes, getting it out...");
        log.debug("filedata class? " + request.getAttribute("filedata").getClass().toString());
        FileItem item = (FileItem) request.getAttribute("filedata");
        item.write(outputFile);
        for (Object key : request.getParameterMap().keySet()) {
            params.put((String) key, request.getParameter((String) key));
        }
        return true;
    }

    /*ServletFileUpload upload = new ServletFileUpload();
    //upload.setSizeMax(Globals.MAX_UPLOAD_SIZE);
    FileItemIterator iter = upload.getItemIterator(request);
    while(iter.hasNext()){
       FileItemStream item = iter.next();
       InputStream stream = item.openStream();
               
       //If this item is a file
       if(!item.isFormField()){
             
     log.debug("Found non form field in upload request with field name = " + item.getFieldName());
             
     String name = item.getName();
     if(name == null){
         throw new Exception("File upload did not have filename specified");
     }
             
        // Some browsers, including IE, return the full path so trim off everything but the file name
        name = getFileNameFromPath(name);
                 
    //Enforce required file extension, if present
    if(!name.toLowerCase().endsWith( ".zip" )){
       throw new Exception("File uploaded did not have required extension .zip");
    }
            
      bufferedCopyStream(stream, new FileOutputStream(outputFile));
       }
       else {
    params.put(item.getFieldName(), Streams.asString(stream));
       }
    }
    return true;*/

    // Create a factory for disk-based file items
    FileItemFactory factory = new DiskFileItemFactory();

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    // Parse the request
    List /* FileItem */ items = upload.parseRequest(request);

    // Process the uploaded items
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (!item.isFormField()) {
            log.debug("Found non form field in upload request with field name = " + item.getFieldName());

            String name = item.getName();
            if (name == null) {
                throw new Exception("File upload did not have filename specified");
            }

            // Some browsers, including IE, return the full path so trim off everything but the file name
            name = getFileNameFromPath(name);

            item.write(outputFile);
        } else {
            params.put(item.getFieldName(), item.getString());
        }
    }
    return true;
}

From source file:io.pivotal.poc.gateway.filters.AbstractFilter.java

protected StandardMultipartHttpServletRequest extractMultipartRequest(HttpServletRequest request) {
    while (request != null) {
        log.info("request class: {}", request.getClass());
        if (StandardMultipartHttpServletRequest.class.isAssignableFrom(request.getClass())) {
            return (StandardMultipartHttpServletRequest) request;
        }//w w  w. j a va2s  .  c  om
        try {
            request = (HttpServletRequest) ReflectionUtils.getField(requestField, request);
        } catch (Exception e) {
            break;
        }
    }
    return null;
}

From source file:org.energyos.espi.common.utils.StringToLongFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {

    if (logger.isDebugEnabled()) {

        logger.debug("StringToLongFilter processing");

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        logger.debug("Request is " + httpRequest.getClass());
        logger.debug("Request URL: " + httpRequest.getRequestURL());
        logger.debug("Request Method is '" + httpRequest.getMethod() + "'");
        logger.debug("Response is " + httpResponse.getClass());

    }/*w ww.java  2s. com*/

    // TODO: Add Long to String conversion logic

    filterChain.doFilter(request, response);
}

From source file:io.neba.core.mvc.SlingMultipartResolver.java

@Override
public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {
    if (request == null) {
        throw new IllegalArgumentException("Method argument request must not be null.");
    }//w w  w .j  a va2 s .  c  o  m
    if (!(request instanceof SlingHttpServletRequest)) {
        throw new IllegalArgumentException("Method argument request must be a " + SlingHttpServletRequest.class
                + ", but is a " + request.getClass() + ".");
    }
    return new MultipartSlingHttpServletRequest((SlingHttpServletRequest) request);
}

From source file:com.boylesoftware.web.Router.java

/**
 * Route request./*from  www.ja  v a  2 s.com*/
 *
 * @param webapp The application.
 * @param request The HTTP request.
 * @param response The HTTP response.
 *
 * @return {@code true} if the router took care of the request processing
 * and no further action is required, {@code false} if the router did not
 * process the request because it does not have a route for it.
 *
 * @throws ServletException If an error happens.
 * @throws IOException If an I/O error happens reading the request or
 * sending the response.
 */
boolean route(final AbstractWebApplication webapp, final HttpServletRequest request,
        final HttpServletResponse response) throws ServletException, IOException {

    if (this.log.isDebugEnabled())
        this.log.debug("received " + request.getDispatcherType() + " " + request.getMethod() + " "
                + request.getRequestURI() + " (" + request.getClass().getName() + ")");

    // execute corresponding logic
    return (request.getDispatcherType() == DispatcherType.ASYNC ? this.doAsync(webapp, request, response)
            : this.doRequest(webapp, request, response));
}

From source file:com.sun.identity.provider.springsecurity.OpenSSOAuthenticationEntryPoint.java

public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {
    if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        request = HttpUtil.unwrapOriginalHttpServletRequest(httpRequest);
        redirectToLoginUrl(httpRequest, httpResponse);
    } else {/*from   w ww.ja v a2s .  co  m*/
        debug.error("Request: " + request.getClass() + " Response: " + response.getClass());
        throw new ServletException("Handles only HttpServletRequest/Response");
    }
}

From source file:io.milton.servlet.ServletRequest.java

public ServletRequest(HttpServletRequest r, ServletContext servletContext) {
    this.request = r;
    this.servletContext = servletContext;
    String sMethod = r.getMethod();
    method = Request.Method.valueOf(sMethod);
    String s = r.getRequestURL().toString(); //MiltonUtils.stripContext(r);
    url = s;/*from w  w w  .  j a va  2s . co  m*/
    tlRequest.set(r);
    tlServletContext.set(servletContext);

    if (log.isTraceEnabled()) {
        log.trace("Dumping headers ---- " + r.getMethod() + " " + r.getRequestURL() + " -----");
        log.trace("Request class: " + r.getClass());
        log.trace("Response class: " + r.getClass());
        Enumeration names = r.getHeaderNames();
        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            String value = r.getHeader(name);
            log.trace("  " + name + "=" + value);
        }
        log.trace("-------------------------------------------");
    }
}

From source file:net.officefloor.plugin.servlet.container.ServletConfirmer.java

@Override
@SuppressWarnings("unchecked")
protected synchronized void service(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    try {//ww  w. j a v a 2s .  c o  m

        // Ensure method recorded
        TestCase.assertTrue("No method recorded", this.invocations.size() > 0);

        // Iterate over the methods for invocation
        for (RecordedMethodInvocation invocation : this.invocations) {

            // Obtain the parameter types
            Class<?>[] parameterTypes = new Class[invocation.arguments.length];
            for (int i = 0; i < parameterTypes.length; i++) {
                parameterTypes[i] = invocation.arguments[i].getClass();
            }

            // Obtain the method
            Method method = req.getClass().getMethod(invocation.method.getName(), parameterTypes);

            // Invoke the method to obtain as last result
            Object result = method.invoke(req, invocation.arguments);

            // Take copy of enumeration (stop concurrent access)
            if (result instanceof Enumeration) {
                Enumeration<Object> enumeration = (Enumeration<Object>) result;
                Vector<Object> vector = new Vector<Object>();
                while (enumeration.hasMoreElements()) {
                    vector.add(enumeration.nextElement());
                }
                result = vector.elements();
            }

            // Provide the result
            this.lastResult = result;
        }
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
}