Example usage for javax.servlet.http HttpServletRequest getInputStream

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

Introduction

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

Prototype

public ServletInputStream getInputStream() throws IOException;

Source Link

Document

Retrieves the body of the request as binary data using a ServletInputStream .

Usage

From source file:grails.converters.XML.java

/**
 * Parses the give XML (read from the POST Body of the Request)
 *
 * @param request an HttpServletRequest//from   w w w  .ja  va  2 s .com
 * @return a groovy.util.XmlSlurper
 * @throws ConverterException
 */
public static Object parse(HttpServletRequest request) throws ConverterException {
    Object xml = request.getAttribute(CACHED_XML);
    if (xml != null)
        return xml;

    String encoding = request.getCharacterEncoding();
    if (encoding == null) {
        encoding = Converter.DEFAULT_REQUEST_ENCODING;
    }
    try {
        if (!request.getMethod().equalsIgnoreCase("GET")) {
            xml = parse(request.getInputStream(), encoding);
            request.setAttribute(CACHED_XML, xml);
        }
        return xml;
    } catch (IOException e) {
        throw new ConverterException("Error parsing XML", e);
    }
}

From source file:org.nlp2rdf.webservice.NIFParameterWebserviceFactory.java

/**
 * Factory method//  ww  w.  ja v a 2  s  .c om
 *
 * @param httpServletRequest
 * @return
 */
public static NIFParameters getInstance(HttpServletRequest httpServletRequest, String defaultPrefix)
        throws ParameterException, IOException {

    //twice the size to split key value
    String[] args = new String[httpServletRequest.getParameterMap().size() * 2];

    int x = 0;

    for (Object key : httpServletRequest.getParameterMap().keySet()) {
        String pname = (String) key;
        //transform key to CLI style
        pname = (pname.length() == 1) ? "-" + pname : "--" + pname;

        //collect CLI args
        args[x++] = pname;
        args[x++] = httpServletRequest.getParameter((String) key);

    }

    String line;
    String content = "";
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(httpServletRequest.getInputStream()));

        while ((line = reader.readLine()) != null) {
            if (line.startsWith("---") || line.startsWith("Content") || line.startsWith("html"))
                continue;
            content += line;

        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (args.length == 0 && !content.isEmpty()) {
        args = new String[4];
        String[] params = content.split("&");
        if (params.length > 0) {
            String[] i = params[0].split("=");
            String[] id = params[1].split("=");
            if (i.length > 0) {
                args[0] = "--" + i[0];
                args[1] = URLDecoder.decode(i[1], "UTF-8");
            }
            if (id.length > 0) {
                args[2] = "-" + id[0];
                args[3] = URLDecoder.decode(id[1], "UTF-8");
            }
            content = "";
        }
    }

    //        System.out.println(content);

    //parse CLI args
    OptionParser parser = ParameterParser.getParser(args, defaultPrefix);
    OptionSet options = ParameterParser.getOption(parser, args);

    // print help screen
    if (options.has("h")) {
        String addHelp = "";
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        parser.printHelpOn(baos);
        throw new ParameterException(baos.toString());
    }

    // parse options with webservice setted to true
    return ParameterParserMS.parseOptions(options, true, content);
}

From source file:de.knowwe.core.user.UserContextUtil.java

/**
 * Returns a Map<String, String> with all parameters of a http request. This
 * is necessary because the parameter map of the http request is locked.
 * //from w  w w  .  j  av  a 2 s .co  m
 * @created Mar 9, 2011
 * @param request the http request
 * @return map containing the parameters of the http request.
 */
public static Map<String, String> getParameters(HttpServletRequest request) {
    Map<String, String> parameters = new HashMap<>();
    if (request != null) {
        Enumeration<?> iter = request.getParameterNames();
        boolean decode = checkForFlowChart(request.getParameter("action"));
        while (iter.hasMoreElements()) {
            String key = (String) iter.nextElement();
            String value = request.getParameter(key);
            parameters.put(key, decode ? Strings.decodeURL(value) : value);
        }
        if (request.getMethod() != null && request.getMethod().equals("POST")) {

            // do not handle file uploads, leave this to the action
            if (!ServletFileUpload.isMultipartContent(request)) {

                try {
                    BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));

                    String line;
                    StringBuilder bob = new StringBuilder();

                    while ((line = br.readLine()) != null) {
                        bob.append(line).append("\n");
                    }

                    parameters.put("data", bob.toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    return parameters;
}

From source file:gov.va.vinci.chartreview.util.CRSchemaXML.java

/**
 * Parses the give CRSchemaXML (read from the POST Body of the Request)
 *
 * @param request an HttpServletRequest//from w ww. j  a v a  2  s  .  c o m
 * @return a groovy.util.XmlSlurper
 * @throws ConverterException
 */
public static Object parse(HttpServletRequest request) throws ConverterException {
    Object xml = request.getAttribute(CACHED_XML);
    if (xml != null)
        return xml;

    String encoding = request.getCharacterEncoding();
    if (encoding == null) {
        encoding = Converter.DEFAULT_REQUEST_ENCODING;
    }
    try {
        if (!request.getMethod().equalsIgnoreCase("GET")) {
            xml = parse(request.getInputStream(), encoding);
            request.setAttribute(CACHED_XML, xml);
        }
        return xml;
    } catch (IOException e) {
        throw new ConverterException("Error parsing CRSchemaXML", e);
    }
}

From source file:com.zimbra.cs.service.FileUploadServlet.java

/**
 * Reads the end of the client request when an error occurs, to avoid cases where
 * the client blocks when writing the HTTP request.
 *//*from w  ww  .ja  v a2 s .  c o m*/
public static void drainRequestStream(HttpServletRequest req) {
    try {
        InputStream in = req.getInputStream();
        byte[] buf = new byte[1024];
        int numRead = 0;
        int totalRead = 0;
        mLog.debug("Draining request input stream");
        while ((numRead = in.read(buf)) >= 0) {
            totalRead += numRead;
        }
        mLog.debug("Drained %d bytes", totalRead);
    } catch (IOException e) {
        mLog.info("Ignoring error that occurred while reading the end of the client request: " + e);
    }
}

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

private static Optional<GuacamoleConfiguration> buildConfigurationFromRequest(HttpServletRequest req)
        throws GuacamoleException {
    try {/*from  ww  w . j  ava 2  s.  com*/
        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:com.liferay.util.servlet.fileupload.LiferayInputStream.java

public LiferayInputStream(HttpServletRequest req) throws IOException {
    super(req.getInputStream());

    _req = req;/*from   ww  w .ja v a 2s  . c om*/
    _ses = req.getSession();
    _totalSize = req.getContentLength();
}

From source file:com.apipulse.bastion.controllers.ApiController.java

@RequestMapping(value = "/api/admittance/{id}", produces = "application/json", method = RequestMethod.POST)
@ResponseBody//from w  w  w .j  a  v a2s. c  o  m
public String admittance(final @PathVariable String id, final HttpServletRequest request) throws IOException {
    final InputStream is = request.getInputStream();
    final String payload = IOUtils.toString(is);
    is.close();
    final StepMessage message = new StepMessage(payload);
    final HashMap<String, String> headers = new HashMap<String, String>();
    final Enumeration<String> eh = request.getHeaderNames();
    while (eh.hasMoreElements()) {
        final String headerName = eh.nextElement();
        headers.put(headerName, request.getHeader(headerName));
    }
    message.getContext().put("headers", headers);
    message.getContext().put("id", id);
    final String uuid = UUID.randomUUID().toString();
    message.getContext().put("uuid", uuid);
    BastionActors.getInstance().getHttpRouter().tell(message, null);
    return "{\"accepted\":true,\"id\":\"" + uuid + "\"}";
}

From source file:com.arvato.thoroughly.filter.FilterRequestWrapper.java

public FilterRequestWrapper(HttpServletRequest request) throws IOException {
    super(request);
    body = IOUtils.toString(request.getInputStream());
}

From source file:org.test.skeleton.controller.ExpliotDemoController.java

@RequestMapping(value = "/csrf/messages/", method = RequestMethod.POST)
public void exploit(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Message messageToSave = messageParser.parse(request.getInputStream());

    messageDao.save(messageToSave);//from ww  w. j  ava 2 s  .co m

    response.sendRedirect(request.getContextPath());
}