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:org.eclipse.jgit.lfs.server.fs.FileLfsServlet.java

/**
 * Handle object uploads//from w  w w  . j  a v  a  2s .com
 *
 * @param req
 *            servlet request
 * @param rsp
 *            servlet response
 * @throws ServletException
 *             if a servlet-specific error occurs
 * @throws IOException
 *             if an I/O error occurs
 */
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
    AnyLongObjectId id = getObjectToTransfer(req, rsp);
    if (id != null) {
        AsyncContext context = req.startAsync();
        context.setTimeout(timeout);
        req.getInputStream().setReadListener(new ObjectUploadListener(repository, context, req, rsp, id));
    }
}

From source file:edu.emory.cci.aiw.cvrg.eureka.servlet.ProxyServlet.java

@Override
protected void doPut(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    LOGGER.debug("ProxyServlet - PUT");

    StringBuilder stringBuilder = new StringBuilder(1000);
    Scanner scanner = new Scanner(servletRequest.getInputStream());
    while (scanner.hasNextLine()) {
        stringBuilder.append(scanner.nextLine());
    }/* w  ww.ja  va 2s.  c o  m*/
    LOGGER.debug("json: {}", stringBuilder.toString());
    StringBuilder uri = new StringBuilder(500);
    uri.append(getTargetUri());
    // Handle the path given to the servlet
    if (servletRequest.getPathInfo() != null) {//ex: /my/path.html
        uri.append(servletRequest.getPathInfo());
    }
    LOGGER.debug("uri: {}", uri.toString());
    try {
        servicesClient.proxyPut(uri.toString(), stringBuilder.toString());
    } catch (ClientException e) {
        e.printStackTrace();
    }
}

From source file:edu.emory.cci.aiw.cvrg.eureka.servlet.ProxyServlet.java

@Override
protected void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {

    LOGGER.debug("ProxyServlet - POST");

    StringBuilder stringBuilder = new StringBuilder(1000);
    Scanner scanner = new Scanner(servletRequest.getInputStream());
    while (scanner.hasNextLine()) {
        stringBuilder.append(scanner.nextLine());
    }/*  w  w w  .  ja v a 2 s . c o  m*/
    LOGGER.debug("json: {}", stringBuilder.toString());
    StringBuilder uri = new StringBuilder(500);
    uri.append(getTargetUri());
    // Handle the path given to the servlet
    if (servletRequest.getPathInfo() != null) {//ex: /my/path.html
        uri.append(servletRequest.getPathInfo());
    }
    LOGGER.debug("uri: {}", uri.toString());
    try {
        servicesClient.proxyPost(uri.toString(), stringBuilder.toString());
    } catch (ClientException e) {
        e.printStackTrace();
    }

}

From source file:com.nebhale.cyclinglibrary.web.GzipFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {

    HttpServletRequest newRequest;/*from   w w w . j  av a 2s .  c om*/
    if (sendsGzipEncoding(request)) {
        newRequest = new DelegatingHttpServletRequest(request, new GZIPInputStream(request.getInputStream()));
    } else {
        String method = request.getMethod();
        if ("POST".equals(method) || "PUT".equals(method)) {
            this.logger.warn("Uncompressed input received for '{} {}'", method, request.getRequestURI());
        }

        newRequest = request;
    }

    HttpServletResponse newResponse;
    OutputStream outputStream;
    if (acceptsGzipEncoding(request)) {
        response.setHeader("Content-Encoding", "gzip");
        outputStream = new GZIPOutputStream(response.getOutputStream());
        newResponse = new DelegatingHttpServletResponse(response, outputStream);
    } else {
        String method = request.getMethod();
        if (!"DELETE".equals(method)) {
            this.logger.warn("Uncompressed output requested for '{} {}'", method, request.getRequestURI());
        }

        outputStream = response.getOutputStream();
        newResponse = response;
    }

    filterChain.doFilter(newRequest, newResponse);
}

From source file:de.eorganization.crawler.server.servlets.JSONImportServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    try {/*from  w w  w.j  av a  2  s . com*/

        resp.setContentType("text/plain");

        InputStream stream = req.getInputStream();

        log.info("Got Upload " + req.getContentType() + " (" + req.getContentLength() + " bytes) from "
                + req.getRemoteAddr());

        String amiId = req.getHeader("AMI-ID");
        log.info("Got AMI ID:" + amiId);
        String repository = req.getHeader("REPO");
        log.info("Got REPO:" + repository);
        if (amiId == null || repository == null || "".equals(amiId) || "".equals(repository)) {
            log.severe("AMI ID and REPO HTTP Header required.");
            return;
        }

        // Gson gson = new Gson();
        // log.info("Parsed Gson " + gson.fromJson(new
        // InputStreamReader(stream), JsonObject.class));

        String jsonString = IOUtils.toString(stream);
        log.info("Got JSON String "
                + jsonString.substring(0, jsonString.length() > 128 ? 128 : jsonString.length() - 1));
        JSONObject json = new JSONObject();
        try {
            json = new JSONObject(jsonString);
            log.fine("Parsed Json " + json);
            log.finer("Json has keys: " + json.names());
        } catch (JSONException e) {
            log.severe("No JSON sent or wrong format.");
            return;
        }

        JSONObject software = json.optJSONObject("software");
        if (software != null) {
            log.finer("Software JSON " + software);

            JSONArray softwareNames = software.names();
            log.finer("Key Array JSON " + softwareNames);
            for (int i = 0; i < softwareNames.length(); i++) {
                log.fine("software " + softwareNames.getString(i) + " with version "
                        + software.getJSONObject(softwareNames.getString(i)).getString("version"));

                Map<String, String> softAttributes = new HashMap<String, String>();
                JSONArray softwareAttributes = software.getJSONObject(softwareNames.getString(i)).names();
                for (int j = 0; j < softwareAttributes.length(); j++)
                    softAttributes.put(softwareAttributes.getString(j),
                            software.getJSONObject(softwareNames.getString(i))
                                    .getString(softwareAttributes.getString(j)));

                Software soft = AmiManager.saveSoftware(amiId, repository, softwareNames.getString(i),
                        software.getJSONObject(softwareNames.getString(i)).getString("version"),
                        softAttributes);
                if (soft != null) {
                    log.fine("Saved/restored software " + soft);
                    // soft.getAttributes().putAll(softAttributes);
                    // AmiManager.updateSoftware(soft);
                    // log.fine("Saved object " + soft);
                } else
                    log.severe("Not able to save software information for given Ami Id " + amiId + "!");

            }
            List<String> names = new ArrayList<String>();
            for (int i = 0; i < softwareNames.length(); i++)
                names.add(softwareNames.getString(i));
            AmiManager.updateSoftwareNames(names);
            log.info("Saved " + softwareNames.length() + " software objects");

        }

        JSONObject languages = json.optJSONObject("languages");
        if (languages != null) {
            log.finer("Languages JSON " + languages);

            JSONArray languagesNames = languages.names();
            log.finer("Key Array JSON " + languagesNames);
            for (int i = 0; i < languagesNames.length(); i++) {
                log.fine("languages " + languagesNames.getString(i) + " with version "
                        + languages.getJSONObject(languagesNames.getString(i)).getString("version"));

                Map<String, String> langAttributes = new HashMap<String, String>();
                JSONArray languageAttributes = languages.getJSONObject(languagesNames.getString(i)).names();
                for (int j = 0; j < languageAttributes.length(); j++)
                    langAttributes.put(languageAttributes.getString(j),
                            languages.getJSONObject(languagesNames.getString(i))
                                    .getString(languageAttributes.getString(j)));

                Language lang = AmiManager.saveLanguage(amiId, repository, languagesNames.getString(i),
                        languages.getJSONObject(languagesNames.getString(i)).getString("version"),
                        langAttributes);
                if (lang != null) {
                    log.fine("Saved/restored programming language " + lang);
                    lang.getAttributes().putAll(langAttributes);
                    AmiManager.updateLanguage(lang);
                    log.fine("Saved object " + lang);
                } else
                    log.severe("Not able to save programming language information for given Ami Id " + amiId
                            + "!");

            }
            log.info("Saved " + languagesNames.length() + " programming language objects");
        }

        resp.getWriter().println(
                "Saving software packages and programming languages for " + amiId + " (" + repository + ").");

    } catch (JSONException e) {
        log.severe("Error while parsing JSON upload" + e.getMessage() + ", trace: " + e.getStackTrace());
        log.throwing(JSONImportServlet.class.getName(), "doPost", e);
        e.printStackTrace();

    } catch (Exception ex) {
        log.severe("Unexpected error" + ex.getMessage() + ", trace: " + ex.getStackTrace());
        log.throwing(JSONImportServlet.class.getName(), "doPost", ex);
        ex.printStackTrace();
    }

    // log.info("returning to referer " + req.getHeader("referer"));
    // resp.sendRedirect(req.getHeader("referer") != null &&
    // !"".equals(req.getHeader("referer")) ? req.getHeader("referer") :
    // "localhost:8088");
}

From source file:ee.ria.xroad.common.request.DummyCentralServiceHandler.java

@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.info("Received request from {}", request.getRemoteAddr());
    try {/*from w ww. java 2  s.  c  o m*/
        SoapMessageImpl requestMessage = ManagementRequestHandler.readRequest(request.getContentType(),
                request.getInputStream());

        log.info("Got request message: {}", requestMessage.getXml());

        String service = requestMessage.getService().getServiceCode();
        switch (service) {
        case "authCertRegRequest":
            handleAuthCertRegRequest(requestMessage, response);
            break;
        case "authCertDeletionRequest":
            handleAuthCertDeletionRequest(requestMessage, response);
            break;
        case "clientRegRequest":
            handleClientRegRequest(requestMessage, response);
            break;
        case "clientDeletionRequest":
            handleClientDeletionRequest(requestMessage, response);
            break;
        default:
            throw new RuntimeException("Unknown service " + service);
        }
    } catch (Exception e) {
        sendErrorResponse(response, translateException(e));
    } finally {
        baseRequest.setHandled(true);
    }
}

From source file:com.jaspersoft.jasperserver.rest.services.RESTPermission.java

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {
    try {//from  w  ww  .  ja va2s  .  c o  m
        JAXBList<ObjectPermission> perm = (JAXBList<ObjectPermission>) restUtils.unmarshal(req.getInputStream(),
                JAXBList.class, ObjectPermissionImpl.class, UserImpl.class, RoleImpl.class);
        for (int i = 0; i < perm.size(); i++) {
            if (isValidObjectPermission(perm.get(i)) && canUpdateObjectPermissions(perm.get(i)))
                try {
                    permissionsService.putPermission(perm.get(i));
                } catch (IllegalArgumentException e) {
                    throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
                } catch (RemoteException e) {
                    throw new ServiceException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                            e.getClass().getName() + (e.getMessage() != null ? ": " + e.getMessage() : ""));
                }
            else {
                if (perm.get(i).getPermissionRecipient() instanceof User) {
                    throw new AccessDeniedException("could not set permissions for: "
                            + ((User) perm.get(i).getPermissionRecipient()).getUsername());
                } else if (perm.get(i).getPermissionRecipient() instanceof Role) {
                    throw new AccessDeniedException("could not set permissions for: "
                            + ((Role) perm.get(i).getPermissionRecipient()).getRoleName());
                } else {
                    throw new AccessDeniedException(
                            "could not set permissions for: " + (perm.get(i).getPermissionRecipient() != null
                                    ? perm.get(i).getPermissionRecipient().toString()
                                    : "null"));
                }
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("finished PUT permissions " + perm.size() + " permissions were added");
        }
        restUtils.setStatusAndBody(HttpServletResponse.SC_OK, resp, "");
    } catch (AxisFault axisFault) {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST,
                "please check the request job descriptor");
    } catch (IOException e) {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST,
                "please check the request job descriptor");
    } catch (JAXBException e) {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST,
                "please check the request job descriptor");
    }
}

From source file:com.github.matthesrieke.jprox.JProxViaParameterServlet.java

private HttpUriRequest prepareRequest(HttpServletRequest req, String target) throws IOException {
    String method = req.getMethod();
    if (method.equals(HttpGet.METHOD_NAME)) {
        return new HttpGet(target);
    } else if (method.equals(HttpPost.METHOD_NAME)) {
        HttpPost post = new HttpPost(target);
        post.setEntity(new ByteArrayEntity(readInputStream(req.getInputStream(), req.getContentLength()),
                ContentType.parse(req.getContentType())));
        return post;
    }//from w w w.j a v a 2s .co m
    throw new UnsupportedOperationException("Only GET and POST are supported by this proxy.");
}

From source file:au.org.ala.biocache.web.ValidationRuleController.java

/**
 * Example expected payload/* w w  w.  ja v  a  2 s . c  om*/
 *
 * {
 *    "status": "new",
 *    "ignored": false,
 *    "apiKey": "XXXXXXXXXX",
 *    "user": {
 *    "isAdmin": true,
 *    "email": "xxxxxxxx@gmail.com",
 *    "authority": 1000
 *    },
 *    "classification": "invalid",
 *    "area": "MULTIPOLYGON(((137.5 -26,137.5 -25.5,138 -25.5,138 -26,137.5 -26)),((134.5 -29.5,134.5 -29,135 -29,135 -29.5,134.5 -29.5)))",
 *    "lastModified": "2013-01-01T09:05:19",
 *    "id": 5090,
 *    "comment": "",
 *    "species": "Trichoglossus haematodus"
 * }
 *
 * @param request
 * @param response
 * @throws Exception
 */
@RequestMapping(value = { "/assertions/query/add", "/validation/rule/add" }, method = RequestMethod.POST)
public void addValidationRule(HttpServletRequest request, HttpServletResponse response) throws Exception {

    try {
        String rawValue = org.apache.commons.io.IOUtils.toString(request.getInputStream(), "UTF-8");
        logger.debug("The raw value :" + rawValue);

        try {
            ObjectMapper om = new ObjectMapper();
            ValidationRuleDTO validationRuleDTO = om.readValue(rawValue, ValidationRuleDTO.class);

            //we know that it is a JCU assertion
            if (shouldPerformOperation(validationRuleDTO.getApiKey(), response)) {
                //delete
                if (validationRuleDTO.getStatus().equals("deleted")) {
                    Store.deleteValidationRule(validationRuleDTO.getApiKey() + "|" + validationRuleDTO.getId(),
                            validationRuleDTO.getLastModified());
                } else {
                    //new or update
                    //does the species exist
                    String guid = speciesLookupService.getGuidForName(validationRuleDTO.getSpecies());
                    if ((guid != null || validationRuleDTO.getQuery() != null)
                            && validationRuleDTO.getId() != null) {
                        //check to see if the area is well formed.
                        SpatialSearchRequestParams ssr = new SpatialSearchRequestParams();
                        String query = guid != null ? "lsid:" + guid : validationRuleDTO.getQuery();
                        ssr.setQ(query);
                        ssr.setWkt(validationRuleDTO.getArea());
                        ssr.setFacet(false);
                        try {
                            SolrDocumentList list = searchDAO.findByFulltext(ssr);
                            Long recordCount = list.getNumFound();
                            logger.debug("Validation rule should apply to records: " + recordCount);
                            //now create the query assertion
                            ValidationRule validationRule = new ValidationRule();
                            //NQ: need the id to be populated to construct the correct validation rowkey to allow for updates
                            validationRule.setId(validationRuleDTO.getId().toString());
                            //copy form DTO -> model object for storage
                            validationRule.setApiKey(validationRuleDTO.apiKey);
                            validationRule.setRawAssertion(rawValue);
                            validationRule.setWkt(validationRuleDTO.area);
                            validationRule.setComment(validationRuleDTO.getComment());

                            //auth details
                            String userId = authService.getMapOfEmailToId()
                                    .get(validationRuleDTO.user.getEmail());
                            validationRule.setUserId(userId);
                            validationRule.setUserEmail(validationRuleDTO.user.getEmail());
                            validationRule.setAuthority(validationRuleDTO.user.getAuthority().toString());

                            validationRule.setRawQuery(getRawQuery(validationRuleDTO.getQuery(), guid,
                                    validationRuleDTO.getArea()));
                            if (validationRuleDTO.getStatus().equals("new")) {
                                validationRule.setCreatedDate(validationRuleDTO.getLastModified());
                            }

                            Store.addValidationRule(validationRule);
                        } catch (Exception e) {
                            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                                    "Unable to construct a valid validation rule from the provided information. "
                                            + validationRuleDTO.getId());
                            logger.error("Error constructing query or adding to datastore", e);
                        }
                    } else {
                        response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                                "Unable to locate species " + validationRuleDTO.getSpecies()
                                        + " for validation rule " + validationRuleDTO.getId());
                    }
                }
            }
        } catch (Exception e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
            logger.error("Unable to resolve message to known type", e);
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        response.sendError(HttpURLConnection.HTTP_BAD_REQUEST);
    }
}

From source file:io.klerch.alexa.tellask.model.wrapper.AlexaSpeechletServletTest.java

private SpeechletResponseEnvelope doPost(final AlexaSpeechletServlet servlet,
        final SpeechletRequestEnvelope envelope) throws Exception {
    final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);

    final InputStream stream = convertToStream(envelope);

    final ServletInputStream servletInputStream = new ServletInputStream() {
        @Override//from  w  w w .  j  a v  a  2s  .  c o  m
        public int read() throws IOException {
            return stream.read();
        }
    };
    when(request.getInputStream()).thenReturn(servletInputStream);
    when(request.getReader()).thenReturn(new BufferedReader(new InputStreamReader(stream)));

    final ByteArrayOutputStream responseStream = new ByteArrayOutputStream();
    final HttpServletResponse response = givenServletResponse(responseStream);
    servlet.doPost(request, response);

    return convertToResponseEnvelope(responseStream);
}