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.atlasapi.application.SourceLicenseController.java

@RequestMapping(value = "/4/license.*", method = RequestMethod.POST)
public void writeLicense(HttpServletRequest request, HttpServletResponse response) throws IOException {
    ResponseWriter writer = null;//w  ww .  j  av a2  s .  c  o m
    try {
        writer = writerResolver.writerFor(request, response);
        User user = userFetcher.userFor(request).get();
        if (!user.is(Role.ADMIN)) {
            throw new ResourceForbiddenException();
        }

        SourceLicense license = deserialize(new InputStreamReader(request.getInputStream()),
                SourceLicense.class);
        store.store(license);
        UserAwareQueryResult<SourceLicense> queryResult = UserAwareQueryResult.singleResult(license,
                UserAwareQueryContext.standard(request));
        resultWriter.write(queryResult, writer);
    } catch (Exception e) {
        log.error("Request exception " + request.getRequestURI(), e);
        ErrorSummary summary = ErrorSummary.forException(e);
        new ErrorResultWriter().write(summary, writer, request, response);
    }
}

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

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {
    try {//  www.java  2s. co  m
        String userName = restUtils.extractResourceName(req.getPathInfo());

        WSUser user = restUtils.unmarshal(WSUser.class, req.getInputStream());
        if (isUserNameValid(userName, user))
            this.updateUser(user);
        else {
            throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, "check your request parameters");
        }
        restUtils.setStatusAndBody(HttpServletResponse.SC_OK, resp, "");
    } catch (AxisFault axisFault) {
        throw new ServiceException(axisFault.getLocalizedMessage());
    } catch (IOException e) {
        throw new ServiceException(e.getLocalizedMessage());
    } catch (JAXBException e) {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, "could not marshal the user descriptor");
    }
}

From source file:edu.utah.further.i2b2.hook.further.FurtherInterceptionFilter.java

/**
 * @param request//  w ww .  ja  v  a 2s.com
 * @return
 */
private byte[] getRequestBytes(final HttpServletRequest request) {
    byte[] requestBytes = new byte[0];
    try {
        requestBytes = CoreUtil.readBytesFromStream(request.getInputStream());
    } catch (final IOException readEx) {
        log.error("Error reading request", readEx);
    }
    return requestBytes;
}

From source file:org.atlasapi.application.users.EndUserLicenseController.java

@RequestMapping(value = "/4/eula.*", method = RequestMethod.POST)
public void updatelicense(HttpServletRequest request, HttpServletResponse response) throws IOException {
    ResponseWriter writer = null;//ww w  .  ja v  a  2 s . com
    try {
        User editingUser = userFetcher.userFor(request).get();
        if (!editingUser.is(Role.ADMIN)) {
            throw new ResourceForbiddenException();
        }

        writer = writerResolver.writerFor(request, response);
        EndUserLicense posted = deserialize(new InputStreamReader(request.getInputStream()),
                EndUserLicense.class);
        // set to the EULA id
        licenseStore.store(posted.copy().withId(LICENSE_ID).build());
        QueryResult<EndUserLicense> queryResult = QueryResult.singleResult(posted,
                QueryContext.standard(request));
        resultWriter.write(queryResult, writer);
    } catch (Exception e) {
        log.error("Request exception " + request.getRequestURI(), e);
        ErrorSummary summary = ErrorSummary.forException(e);
        new ErrorResultWriter().write(summary, writer, request, response);
    }
}

From source file:com.haulmont.cuba.restapi.FileUploadController.java

@RequestMapping(value = "/api/upload", method = RequestMethod.POST)
public void upload(HttpServletRequest request, HttpServletResponse response) throws IOException {
    UserSession userSession = getSession(request, response);
    if (userSession == null)
        return;//w ww  .j a  v  a  2 s.  c o  m

    AppContext.setSecurityContext(new SecurityContext(userSession));
    try {
        InputStream is = request.getInputStream();
        if (is == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        FileDescriptor fd = getFileDescriptor(request, response);
        if (fd == null)
            return;

        try {
            uploadToMiddleware(userSession, is, fd);
            saveFileDescriptor(fd);

            response.setStatus(HttpServletResponse.SC_OK);
            PrintWriter writer = new PrintWriter(
                    new OutputStreamWriter(response.getOutputStream(), StandardCharsets.UTF_8));
            writer.write(fd.getId().toString());
            writer.close();

        } catch (FileStorageException e) {
            log.error("Unable to upload file", e);
            response.sendError(e.getType().getHttpStatus());
        } finally {
            IOUtils.closeQuietly(is);
        }
    } finally {
        AppContext.setSecurityContext(null);
    }
}

From source file:com.github.dactiv.fear.user.web.AccountController.java

/**
 * ?/*  w  w w  .  j a va 2  s.  c  o m*/
 *
 * @param request HttpServletRequest http servlet request ? FaustCplus ??
 *
 * @return ? json: {status:"success"}?
 *
 * @throws IOException
 */
@ResponseBody
@RequestMapping("update-portrait")
public Map<String, Object> updatePortrait(HttpServletRequest request) throws IOException {
    Map<String, Object> user = Subjects.getPrincipal();
    Apis.invoke("accountService", "updateUserPortrait", user, IOUtils.toByteArray(request.getInputStream()));

    Map<String, Object> result = Maps.newHashMap();
    // ? FaustCplus ?? jsfunc  js 
    result.put("state", Boolean.TRUE);
    result.put("message", "??");

    return result;
}

From source file:com.indoqa.httpproxy.HttpClientProxy.java

private void copyRequestBody(HttpServletRequest request, HttpUriRequest proxyRequest) throws IOException {
    if (!(proxyRequest instanceof HttpEntityEnclosingRequest)) {
        return;//from w w  w .j  a v a  2s .c o m
    }

    HttpEntityEnclosingRequest httpEntityEnclosingRequest = (HttpEntityEnclosingRequest) proxyRequest;
    httpEntityEnclosingRequest.setEntity(new InputStreamEntity(request.getInputStream()));
}

From source file:com.twinsoft.convertigo.engine.util.HttpServletRequestTwsWrapper.java

public HttpServletRequestTwsWrapper(HttpServletRequest request) {
    super(request);
    try {//from  www  . ja va  2  s  .  c  o  m
        if (request.getCharacterEncoding() == null) {
            request.setCharacterEncoding("UTF-8");
        }

        if (request.getMethod().equalsIgnoreCase("PUT")
                && MimeType.WwwForm.is(HeaderName.ContentType.getHeader(request))) {
            try {
                String content = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
                addQuery(content);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // parse GET parameters
        addQuery(request.getQueryString());

        // retrieve POST parameters ( == not defined in GET )
        for (Entry<String, String[]> entry : GenericUtils.<Map<String, String[]>>cast(request.getParameterMap())
                .entrySet()) {
            if (!parameters.containsKey(entry.getKey())) {
                parameters.put(entry.getKey(), entry.getValue());
            }
        }
    } catch (UnsupportedEncodingException e) {
        parameters.clear();
        parameters.putAll(GenericUtils.<Map<String, String[]>>cast(request.getParameterMap()));
    }
}

From source file:de.ifgi.mosia.wpswfs.BaseServlet.java

@Override
protected void doPost(final HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    RequestHandler handler;/*from  www .j  a va2 s.  com*/
    String payload;
    String enc;
    try {
        enc = req.getCharacterEncoding();

        if (enc == null || enc.isEmpty()) {
            enc = CharEncoding.ISO_8859_1;
        }

        payload = Util.readContent(req.getInputStream(), enc);
        handler = resolveHandlerFromPost(payload);
    } catch (ServiceException e) {
        throw new RuntimeException(e);
    }

    if (handler == null) {
        handler = genericHandler;
    }

    try {
        handler.handlePostRequest(req, resp, payload, enc);
    } catch (ServiceException e) {
        throw new IOException(e);
    }
}

From source file:com.imaginary.home.cloud.api.call.RelayCall.java

@Override
public void post(@Nonnull String requestId, @Nullable String userId, @Nonnull String[] path,
        @Nonnull HttpServletRequest req, @Nonnull HttpServletResponse resp,
        @Nonnull Map<String, Object> headers, @Nonnull Map<String, Object> parameters)
        throws RestException, IOException {
    try {/*from   w  w  w  . jav a2s  .  c  om*/
        BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream()));
        StringBuilder source = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            source.append(line);
            source.append(" ");
        }
        JSONObject object = new JSONObject(source.toString());

        if (!object.has("pairingCode") || object.isNull("pairingCode")) {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.MISSING_PAIRING_CODE,
                    "Pairing code is missing");
        }
        String code = object.getString("pairingCode");

        if (code.equalsIgnoreCase("null")) {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.MISSING_PAIRING_CODE,
                    "Pairing code is missing");
        }
        Location location = Location.findForPairing(code);

        if (location == null) {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_PAIRING_CODE,
                    "Invalid pairing code; pairing did not occur");
        }
        String relayName;

        if (object.has("name") && !object.isNull("name")) {
            relayName = object.getString("name");
        } else {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.MISSING_DATA,
                    "Missing relay name from JSON");
        }
        ControllerRelay relay = location.pair(code, relayName);

        if (relay == null) {
            throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.PAIRING_FAILURE,
                    "Pairing failed due to an invalid pairing code or expired pairing code");
        }
        HashMap<String, Object> json = new HashMap<String, Object>();

        json.put("apiKeyId", relay.getControllerRelayId());
        json.put("apiKeySecret", Configuration.decrypt(location.getLocationId(), relay.getApiKeySecret()));
        resp.setStatus(HttpServletResponse.SC_CREATED);
        resp.getWriter().println((new JSONObject(json)).toString());
        resp.getWriter().flush();
    } catch (JSONException e) {
        throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_JSON,
                "Invalid JSON in body");
    } catch (PersistenceException e) {
        e.printStackTrace();
        throw new RestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, RestException.INTERNAL_ERROR,
                "Internal database error");
    }
}