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.spiffyui.server.AuthServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType(CONTENT_TYPE);

    String auth = null;//from ww w. jav a  2  s  . c o m

    /*
     * We are manually reading the request as bytes and
     * then converting it to characters.  This is extra
     * work and we should be able to just call getReader
     * insted of getInputStream.  However, the JBoss
     * implementation of the reader here has a bug that
     * sometiems shows up where the index of the reader
     * is wrong so we can work around it using the input
     * stream directly.
     *
     * https://jira.jboss.org/browse/JBAS-7817
     */

    InputStream in = request.getInputStream();
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    int read;
    byte[] buf = new byte[1024];

    try {
        while ((read = in.read(buf)) > 0) {
            out.write(buf, 0, read);
        }
    } finally {
        if (in != null) {
            in.close();
        }
    }
    if (request.getCharacterEncoding() != null) {
        auth = out.toString(request.getCharacterEncoding());
    } else {
        /*
         * There are some cases where the requested character encoding is null.
         * This happens with some application servers and with IE7.  We need to
         * use some encoding in that case so we just use UTF-8.
         */
        auth = out.toString("UTF-8");
    }

    try {
        JSONObject authObj = new JSONObject(auth);
        if (request.getMethod().equals("POST")) {
            doLogin(request, response, authObj.getString(RESTAuthConstants.USERNAME_TOKEN),
                    authObj.getString(RESTAuthConstants.PASSWORD_TOKEN),
                    authObj.getString(RESTAuthConstants.AUTH_URL_TOKEN),
                    authObj.getString(RESTAuthConstants.AUTH_LOGOUT_URL_TOKEN));
            return;
        } else if (request.getMethod().equals("DELETE")) {
            doLogout(request, response, authObj.getString(RESTAuthConstants.USER_TOKEN),
                    authObj.getString(RESTAuthConstants.AUTH_URL_TOKEN));
            return;
        }
    } catch (JSONException e) {
        LOGGER.throwing(AuthServlet.class.getName(), "service", e);
        returnError(response, e.getMessage(), RESTAuthConstants.INVALID_JSON);
    }
}

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

@Override
public void put(@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 {
    if (userId != null) {
        throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.USER_NOT_ALLOWED,
                "A user cannot update a command state");
    }/*from   w  ww.  j  a v a  2 s .c om*/
    String commandId = (path.length > 1 ? path[1] : null);

    if (commandId == null) {
        throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_OPERATION,
                "You cannot PUT against the command root");
    }
    try {
        PendingCommand cmd = PendingCommand.getCommand(commandId);

        if (cmd == null) {
            throw new RestException(HttpServletResponse.SC_NOT_FOUND, RestException.NO_SUCH_OBJECT,
                    "No such command: " + commandId);
        }
        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());
        String action;

        if (object.has("action") && !object.isNull("action")) {
            action = object.getString("action");
        } else {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_ACTION,
                    "An invalid action was specified (or not specified) in the PUT");
        }
        if (action.equals("complete")) {
            object = object.getJSONObject("result");
            boolean result = (object.has("result") && object.getBoolean("result"));
            String errorMessage = (object.has("errorMessage") ? object.getString("errorMessage") : null);
            ControllerRelay relay = ControllerRelay.getRelay(cmd.getRelayId());

            cmd.update(PendingCommandState.EXECUTED, result, errorMessage);

            if (relay != null) {
                resp.setHeader("x-imaginary-has-commands", String.valueOf(PendingCommand.hasCommands(relay)));
            }
            resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
        } else {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_ACTION,
                    "The action " + action + " is not a valid action.");
        }
    } catch (JSONException e) {
        throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_JSON,
                "Invalid JSON in request");
    } catch (PersistenceException e) {
        throw new RestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, RestException.INTERNAL_ERROR,
                e.getMessage());
    }

}

From source file:org.openxdata.server.servlet.DataImportServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ServletOutputStream out = response.getOutputStream();
    try {/*from   w ww . j a va 2 s  .c  o m*/
        // authenticate user
        User user = getUser(request.getHeader("Authorization"));
        if (user != null) {
            log.info("authenticated user:");
            // check msisdn
            String msisdn = request.getParameter("msisdn");
            if (msisdn != null && !msisdn.equals("")) {
                // if an msisdn is sent, then we retrieve the user with that phone number
                authenticateUserBasedOnMsisd(msisdn);
            }

            // can be empty or null, then the default is used. this parameter is a key in the settings table indicating the classname of the serializer to use
            String serializer = request.getParameter("serializer");

            // input stream
            // first byte contains number of forms (x)
            // followed by x number of UTF strings (use writeUTF method in DataOutput)
            formDownloadService.submitForms(request.getInputStream(), out, serializer);

        } else {
            response.setHeader("WWW-Authenticate", "BASIC realm=\"openxdata\"");
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
    } catch (UserNotFoundException userNotFound) {
        out.println("Invalid msisdn");
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    } catch (Exception e) {
        log.error("Could not import data", e);
        out.println(e.getMessage());
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } finally {
        out.close();
    }
}

From source file:com.sitewhere.web.rest.controllers.AssignmentsController.java

/**
 * Adds data to an existing device stream.
 * //from   www.  j  a  v  a2s . c  o m
 * @param token
 * @param streamId
 * @param sequenceNumber
 * @param svtRequest
 * @param svtResponse
 * @throws SiteWhereException
 */
@RequestMapping(value = "/{token}/streams/{streamId:.+}", method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "Add data to device assignment data stream")
@Secured({ SiteWhereRoles.REST })
@Documented
public void addDeviceStreamData(
        @ApiParam(value = "Assignment token", required = true) @PathVariable String token,
        @ApiParam(value = "Stream Id", required = true) @PathVariable String streamId,
        @ApiParam(value = "Sequence Number", required = false) @RequestParam(required = false) Long sequenceNumber,
        HttpServletRequest servletRequest, HttpServletResponse svtResponse) throws SiteWhereException {
    Tracer.start(TracerCategory.RestApiCall, "addDeviceStreamData", LOGGER);
    try {
        ServletInputStream inData = servletRequest.getInputStream();
        ByteArrayOutputStream byteData = new ByteArrayOutputStream();
        int data;
        while ((data = inData.read()) != -1) {
            byteData.write(data);
        }
        byte[] payload = byteData.toByteArray();
        DeviceStreamDataCreateRequest request = new DeviceStreamDataCreateRequest();
        request.setStreamId(streamId);
        request.setSequenceNumber(sequenceNumber);
        request.setEventDate(new Date());
        request.setUpdateState(false);
        request.setData(payload);
        SiteWhere.getServer().getDeviceEventManagement(getTenant(servletRequest)).addDeviceStreamData(token,
                request);
        svtResponse.setStatus(HttpServletResponse.SC_CREATED);
    } catch (SiteWhereSystemException e) {
        if (e.getCode() == ErrorCode.InvalidStreamId) {
            svtResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else {
            LOGGER.error("Unhandled SiteWhere exception.", e);
            svtResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    } catch (IOException e) {
        LOGGER.error(e);
        svtResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } finally {
        Tracer.stop(LOGGER);
    }
}

From source file:com.xqdev.sql.MLSQL.java

protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setContentType("text/xml");

    Namespace sql = Namespace.getNamespace("sql", "http://xqdev.com/sql");
    Document responseDoc = new Document();
    Element root = new Element("result", sql);
    Element meta = new Element("meta", sql);
    responseDoc.setRootElement(root);//  w  w w  . j  a v a  2 s. c  om
    root.addContent(meta);

    Document requestDoc = null;
    try {
        // Normally the request comes via the post body,
        // but we let you bookmark w/ a query string
        String postbody = req.getParameter("postbody");
        if (postbody != null) {
            SAXBuilder builder = new SAXBuilder();
            requestDoc = builder.build(new StringReader(postbody));
        } else {
            InputStream in = req.getInputStream();
            SAXBuilder builder = new SAXBuilder();
            requestDoc = builder.build(in);
        }
    } catch (Exception e) {
        addExceptions(meta, e);
        // Now write the error and return
        OutputStream out = res.getOutputStream();
        new XMLOutputter().output(responseDoc, out);
        out.flush();
        return;
    }

    Connection con = null;
    try {
        Namespace[] namespaces = new Namespace[] { sql };
        XPathHelper xpath = new XPathHelper(requestDoc, namespaces);

        String type = xpath.getString("/sql:request/sql:type");
        String query = xpath.getString("/sql:request/sql:query");
        int maxRows = xpath.getInt("/sql:request/sql:execute-options/sql:max-rows", -1);
        int queryTimeout = xpath.getInt("/sql:request/sql:execute-options/sql:query-timeout", -1);
        int maxFieldSize = xpath.getInt("/sql:request/sql:execute-options/sql:max-field-size", -1);
        List<Element> params = xpath
                .getElements("/sql:request/sql:execute-options/sql:parameters/sql:parameter");

        con = pool.getConnection();

        PreparedStatement stmt = null;

        if (type.equalsIgnoreCase("procedure")) {
            stmt = con.prepareCall(query);
        } else {
            // Note this call depends on JDBC 3.0 (accompanying Java 1.4).
            // The call without the 2nd argument would work on earlier JVMs,
            // you just won't catch any generated keys.
            stmt = con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
        }
        configureStatement(stmt, maxRows, queryTimeout, maxFieldSize);
        parameterizeStatement(stmt, params);

        if (type.equalsIgnoreCase("select")) {
            try {
                ResultSet rs = stmt.executeQuery();
                addWarnings(meta, stmt.getWarnings());
                addResultSet(root, rs);
            } catch (SQLException e) {
                addExceptions(meta, e);
                Log.log(e);
            }
        } else if (type.equalsIgnoreCase("update")) {
            try {
                int count = stmt.executeUpdate();
                addWarnings(meta, stmt.getWarnings());
                addUpdateCount(meta, count);
                try {
                    addGeneratedKeys(meta, stmt.getGeneratedKeys());
                } catch (SQLException e) {
                    // Generated keys are available on INSERT calls but not UPDATE calls
                    // So catch and eat the exception that Oracle (and maybe others) will throw
                }
            } catch (SQLException e) {
                addExceptions(meta, e);
            }
        } else if (type.equalsIgnoreCase("procedure")) {
            boolean isResultSet = stmt.execute();
            if (isResultSet) {
                addResultSet(root, stmt.getResultSet());
                addOutParam(root, stmt, params);
            } else {
                addOutParam(root, stmt, params);
            }
        } else {
            try {
                boolean isResultSet = stmt.execute();
                addWarnings(meta, stmt.getWarnings());
                if (isResultSet) {
                    addResultSet(root, stmt.getResultSet());
                } else {
                    addUpdateCount(meta, stmt.getUpdateCount());
                    addGeneratedKeys(meta, stmt.getGeneratedKeys());
                }
            } catch (SQLException e) {
                addExceptions(meta, e);
            }
        }
        // Close the statement holding the connection to the JDBC Server
        stmt.close();
    } catch (Exception e) {
        addExceptions(meta, e);
    } finally {
        if (con != null)
            pool.returnConnection(con);
    }

    OutputStream out = res.getOutputStream();
    new XMLOutputter().output(responseDoc, out);
    out.flush();
}

From source file:com.cloud.bridge.service.controller.s3.S3BucketAction.java

/**
 * In order to support a policy on the "s3:CreateBucket" action we must be able to set and get
 * policies before a bucket is actually created.
 *
 * @param request//ww  w  .jav  a2  s  .  c  om
 * @param response
 * @throws IOException
 */
private void executePutBucketPolicy(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    String bucketName = (String) request.getAttribute(S3Constants.BUCKET_ATTR_KEY);
    String policy = streamToString(request.getInputStream());

    // [A] Is there an owner of an existing policy or bucket?
    SBucketVO bucket = bucketDao.getByName(bucketName);
    String owner = null;

    if (null != bucket) {
        owner = bucket.getOwnerCanonicalId();
    } else {
        try {
            owner = bPolicyDao.getByName(bucketName).getOwnerCanonicalID();
        } catch (Exception e) {
        }
    }

    // [B] "The bucket owner by default has permissions to attach bucket policies to their buckets using PUT Bucket policy."
    //  -> the bucket owner may want to restrict the IP address from where this can be executed
    String client = UserContext.current().getCanonicalUserId();
    S3PolicyContext context = new S3PolicyContext(PolicyActions.PutBucketPolicy, bucketName);

    switch (S3Engine.verifyPolicy(context)) {
    case ALLOW:
        break;

    case DEFAULT_DENY:
        if (null != owner && !client.equals(owner)) {
            response.setStatus(405);
            return;
        }
        break;
    case DENY:
        response.setStatus(403);
        return;
    }
    TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.AWSAPI_DB);
    // [B] Place the policy into the database over writting an existing policy
    try {
        // -> first make sure that the policy is valid by parsing it
        PolicyParser parser = new PolicyParser();
        S3BucketPolicy sbp = parser.parse(policy, bucketName);
        bPolicyDao.deletePolicy(bucketName);

        if (null != policy && !policy.isEmpty()) {
            BucketPolicyVO bpolicy = new BucketPolicyVO(bucketName, client, policy);
            bpolicy = bPolicyDao.persist(bpolicy);
            //policyDao.addPolicy( bucketName, client, policy );
        }

        if (null != sbp)
            ServiceProvider.getInstance().setBucketPolicy(bucketName, sbp);
        response.setStatus(200);
        txn.commit();
        txn.close();
    } catch (PermissionDeniedException e) {
        logger.error("Put Bucket Policy failed due to " + e.getMessage(), e);
        throw e;
    } catch (ParseException e) {
        logger.error("Put Bucket Policy failed due to " + e.getMessage(), e);
        throw new PermissionDeniedException(e.toString());
    } catch (Exception e) {
        logger.error("Put Bucket Policy failed due to " + e.getMessage(), e);
        response.setStatus(500);
    }
}

From source file:graphql.servlet.GraphQLServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    GraphQLContext context = createContext(Optional.of(req), Optional.of(resp));
    InputStream inputStream = null;
    if (ServletFileUpload.isMultipartContent(req)) {
        ServletFileUpload upload = new ServletFileUpload();
        try {// w  ww. java 2  s  . co  m
            FileItemIterator it = upload.getItemIterator(req);
            context.setFiles(Optional.of(it));
            while (inputStream == null && it.hasNext()) {
                FileItemStream stream = it.next();
                if (stream.getFieldName().contentEquals("graphql")) {
                    inputStream = stream.openStream();
                }
            }
            if (inputStream == null) {
                throw new ServletException("no query found");
            }
        } catch (FileUploadException e) {
            throw new ServletException("no query found");
        }
    } else {
        // this is not a multipart request
        inputStream = req.getInputStream();
    }
    Request request = new ObjectMapper().readValue(inputStream, Request.class);
    Map<String, Object> variables = request.variables;
    if (variables == null) {
        variables = new HashMap<>();
    }
    query(request.query, request.operationName, variables, getSchema(), req, resp, context);
}

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

/**
 * POST can be used to modify a resource or to copy/move it.
 *
 * @param req//from w  w  w .j av  a 2  s . co  m
 * @param resp
 * @throws ServiceException
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {
    String sourceURI = restUtils.extractRepositoryUri(req.getPathInfo());
    String destURI = restUtils.getDetinationUri(req);
    if (destURI != null) {
        if (req.getParameterMap().containsKey(restUtils.REQUEST_PARAMENTER_COPY_TO))
            resourcesManagementRemoteService.copyResource(sourceURI, destURI);
        else
            resourcesManagementRemoteService.moveResource(sourceURI, destURI);
    } else // Modify the resource...
    {
        HttpServletRequest mreq = restUtils.extractAttachments(runReportService, req);
        String resourceDescriptorXml = null;

        // get the resource descriptor...
        if (mreq instanceof MultipartHttpServletRequest)
            resourceDescriptorXml = mreq.getParameter(restUtils.REQUEST_PARAMENTER_RD);
        else {
            try {
                resourceDescriptorXml = IOUtils.toString(req.getInputStream());
            } catch (IOException ex) {
                throw new ServiceException(ServiceException.INTERNAL_SERVER_ERROR, ex.getLocalizedMessage());
            }
        }
        if (resourceDescriptorXml == null) {
            String msg = "Missing parameter " + restUtils.REQUEST_PARAMENTER_RD + " "
                    + runReportService.getInputAttachments();
            restUtils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, msg);
            throw new ServiceException(ServiceException.INTERNAL_SERVER_ERROR, msg);
        }

        // Parse the resource descriptor...
        InputSource is = new InputSource(new StringReader(resourceDescriptorXml));
        Document doc = null;
        ResourceDescriptor rd = null;
        try {
            doc = XMLUtil.getNewDocumentBuilder().parse(is);
            rd = Unmarshaller.readResourceDescriptor(doc.getDocumentElement());

            // we force the rd to be new...
            rd.setIsNew(false);

            if (rd.getUriString() == null || !rd.getUriString().equals(sourceURI)) {
                throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST,
                        "Request URI and descriptor URI are not equals");
            }
            resourcesManagementRemoteService.updateResource(sourceURI, rd, true);

            restUtils.setStatusAndBody(HttpServletResponse.SC_OK, resp, "");

        } catch (SAXException ex) {
            log.error("error parsing...", ex);
            throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, ex.getMessage());
        } catch (ServiceException ex) {
            log.error("error executing the service...", ex);
            throw ex;
        } catch (ParserConfigurationException e) {
            throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        } catch (IOException e) {
            throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        }
    }
}

From source file:com.mb.ext.web.controller.UserController.java

@RequestMapping(value = "/wechatPayResponse", method = RequestMethod.POST)
@ResponseBody//w  w w.j av  a  2s . co  m
public String wechatPayResponse(HttpServletRequest request, HttpServletResponse response) {
    int length = request.getContentLength();
    byte[] bytes = new byte[length];
    InputStream inputStream;
    try {
        inputStream = request.getInputStream();
        inputStream.read(bytes);
        String responseStr = new String(bytes, "UTF-8");

        XStream xstream = new XStream(new XppDriver() {
            public HierarchicalStreamWriter createWriter(Writer out) {
                return new PrettyPrintWriter(out) {
                    // CDATA
                    boolean cdata = true;

                    @SuppressWarnings("rawtypes")
                    public void startNode(String name, Class clazz) {
                        super.startNode(name, clazz);
                    }

                    protected void writeText(QuickWriter writer, String text) {
                        if (cdata) {
                            writer.write("<![CDATA[");
                            writer.write(text);
                            writer.write("]]>");
                        } else {
                            writer.write(text);
                        }
                    }
                };
            }
        });

        xstream.alias("xml", PayResultResponse.class);
        PayResultResponse payResultResponse = (PayResultResponse) xstream.fromXML(responseStr);

        if (!"SUCCESS".equals(payResultResponse.getResult_code())
                || !"SUCCESS".equals(payResultResponse.getResult_code())) {
            response.sendError(500);
        } else {
            String orderNumber = payResultResponse.getOut_trade_no();
            try {
                userService.updateOrderStatus(orderNumber, Constants.ORDER_STATUS_INPROGRESS);
                return WechatConstants.SUCCESS_RESPONSE;
            } catch (BusinessException e) {
                logger.error(e.getMessage());
                response.sendError(500);
            }
        }

    } catch (Exception e) {
        logger.error(e.getMessage());
        try {
            response.sendError(500);
        } catch (IOException e1) {
            logger.error(e1.getMessage());
        }
    }
    return "";
}