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:communicator.doSignUp.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// ww w.  j a  va  2s.c  o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = null;
    JSONObject outputObject = new JSONObject();
    try {
        out = response.getWriter();
        JSONObject signUpRequestObject = new JSONObject(IOUtils.toString(request.getInputStream()));
        signUpRequestObject = signUpRequestObject.getJSONObject(Constants.JSON_SIGNUP_KEY);

        System.out.println(signUpRequestObject.toString());

        /**
         * Check For all the keys are present or not.
         */
        JSONObject mJSONObjec = Constants.checkForAllKeys(signUpRequestObject, Constants.signUpRequestParams);
        System.out.println(mJSONObjec.toString());

        if (mJSONObjec.getString(Constants.JSON_STATUS).compareToIgnoreCase(Constants.JSON_FAILURE) == 0) {
            System.out.println("IF LOOP");
            out.println(mJSONObjec);
            out.close();
            return;
        }

        String emailAddress = signUpRequestObject.getString(Constants.JSON_EMAIL_ADDRESS);
        String password = signUpRequestObject.getString(Constants.JSON_PASSWORD);//"123456789";
        String address = signUpRequestObject.getString(Constants.JSON_ADDRESS);//"FlatNo: 104, SyNo:110, Celebrity Signature, Dodda Thogur,Electronic city pahse 1, Bangalore-560100,karnataka, India ";
        String phoneNumber = signUpRequestObject.getString(Constants.JSON_PHONE_NUMBER); //"917406667752";
        String name = signUpRequestObject.getString(Constants.JSON_NAME); //"Anas Abubacker";

        if (userDbFacade.isEmailIdRegistered(emailAddress)) {

            outputObject.put(Constants.JSON_STATUS, Constants.JSON_FAILURE);
            outputObject.put(Constants.JSON_MSG, Constants.JSON_EMAIL_ID_REGISERED_ALREADY);
            out.println(outputObject);
            out.close();
            return;

        }

        UserDb new_user = new UserDb();

        new_user.setUserId(UUID.randomUUID().toString());
        new_user.setEmailAddress(emailAddress);
        new_user.setAddress(address);
        new_user.setPhoneNumber(phoneNumber);
        new_user.setPassword(password);
        new_user.setName(name);

        new_user.setIsEmailVerified(false);
        new_user.setIsPhoneVerified(false);
        userDbFacade.create(new_user);

        UserDb mUserDb = userDbFacade.getThisUser(emailAddress, password);

        try {
            Gson gson = new Gson();
            outputObject.put(Constants.JSON_STATUS, Constants.JSON_SUCCESS);
            outputObject.put(Constants.JSON_MSG, Constants.JSON_SUCCESS);
            outputObject.put(Constants.JSON_PROFILE, new JSONObject(gson.toJson(mUserDb)));
        } catch (JSONException ex1) {
            Logger.getLogger(doSignUp.class.getName()).log(Level.SEVERE, null, ex1);
        }

        out.println(outputObject.toString());

    } catch (JSONException ex) {
        outputObject = new JSONObject();
        try {
            outputObject.put(Constants.JSON_STATUS, Constants.JSON_FAILURE);
            outputObject.put(Constants.JSON_MSG, Constants.JSON_EXCEPTION);
        } catch (JSONException ex1) {
            Logger.getLogger(doSignUp.class.getName()).log(Level.SEVERE, null, ex1);
        }

        out.println(outputObject.toString());
        Logger.getLogger(doSignUp.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        out.close();
    }

}

From source file:com.ebay.pulsar.collector.servlet.IngestServlet.java

private void batchAdd(HttpServletRequest request, String pathInfo, HttpServletResponse response)
        throws Exception {
    String eventType = pathInfo.substring(pathInfo.lastIndexOf('/') + 1);

    UTF8InputStreamReaderWrapper reader;

    if (request.getCharacterEncoding() != null) {
        reader = new UTF8InputStreamReaderWrapper(request.getInputStream(), request.getCharacterEncoding());
    } else {/* w ww .jav  a 2s . com*/
        reader = new UTF8InputStreamReaderWrapper(request.getInputStream());
    }

    List<Map<String, Object>> eventList = mapper.readValue(reader, TYPE_LIST_OF_MAP);
    List<ValidationResult> failedEvents = null;
    for (Map<String, Object> values : eventList) {
        if (validator != null) {
            ValidationResult result = validator.validate(values, eventType);
            if (result == null || result.isSuccess()) {
                JetstreamEvent event = createEvent(values, eventType);
                inboundChannel.onMessage(event);
            } else {
                if (failedEvents == null) {
                    failedEvents = new ArrayList<ValidationResult>();
                }
                failedEvents.add(result);
            }
        } else {
            JetstreamEvent event = createEvent(values, eventType);
            inboundChannel.onMessage(event);
        }
    }
    if (failedEvents == null) {
        response.setStatus(HttpServletResponse.SC_OK);
    } else {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        PrintWriter printWriter = response.getWriter();
        printWriter.write("[");
        for (int i = 0, t = failedEvents.size() - 1; i < t; i++) {
            printWriter.write(validateReusltWriter.writeValueAsString(failedEvents.get(i)));
            printWriter.write(",");
        }
        printWriter.write(validateReusltWriter.writeValueAsString(failedEvents.get(failedEvents.size() - 1)));
        printWriter.write("]");
    }

}

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

/**
 * Method for simple file upload. File contents are placed in the request body. Optional file name parameter is
 * passed as a query param./*from  w ww.ja  v  a2  s .co m*/
 */
@PostMapping(consumes = "!multipart/form-data")
public ResponseEntity<FileInfo> uploadFile(HttpServletRequest request,
        @RequestParam(required = false) String name) {
    try {
        String contentLength = request.getHeader("Content-Length");

        long size = 0;
        try {
            size = Long.parseLong(contentLength);
        } catch (NumberFormatException ignored) {
        }

        FileDescriptor fd = createFileDescriptor(name, size);

        ServletInputStream is = request.getInputStream();
        uploadToMiddleware(is, fd);
        saveFileDescriptor(fd);

        return createFileInfoResponseEntity(request, fd);
    } catch (Exception e) {
        log.error("File upload failed", e);
        throw new RestAPIException("File upload failed", "File upload failed",
                HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:kms.prolog.comms.TransportServlet.java

/** 
 * Prolog typically deals with HTTP POST for RESTful communication
 * Therefore we use the doPost to implement a RESTful web service
 * for contacting the chosen web service to receive the chosen data
 * Prolog sends JSON { transport: "moduleId", queryPayload="relevant parameters" }
 * This method://from w ww  . j a v  a 2  s  . c o  m
 * 1. Looks up module id in RDBMS in order to find external web service location
 *    to retrieve data from
 * 2. Acts as a SOAP client to retrieve data from this service
 * --> For first web service 
 *     a.Create and generate web service WSDL
 *     b.Use wsimport to generate necessary stubs
 *     c.Import stubs to project
 *     d.Use WSDL as generic wsdl for people to implement other web services
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //       logger.log(Level.INFO, "Inside the transport servlet");
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        ServletInputStream inputStream = request.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder requestStringBuilder = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            requestStringBuilder.append(line + "\n");
        }
        inputStream.close();
        PrologRESTClient restClient = new PrologRESTClient();
        JSONParser jsonParser = new JSONParser();
        ContainerFactory jsonContainerFactory = getJsonContainerFactory();
        try {
            //              out.print(requestStringBuilder.toString());
            Map<String, Object> jsonMap = (Map<String, Object>) jsonParser
                    .parse(requestStringBuilder.toString(), jsonContainerFactory);
            String transportId = (String) jsonMap.get(TRANSPORT_PARAMETER_ID);
            Object queryObject = (Object) jsonMap.get(TRANSPORT_PARAMETER_QUERY);
            String query = null;
            if (queryObject instanceof String) {
                query = (String) queryObject;
            } else if (queryObject instanceof Map) {
                query = JSONValue.toJSONString(queryObject);
            }
            if (transportId != null) {
                TransportServiceImpl transportService = getTransportModuleWebService(transportId);
                if (transportService != null) {
                    String result = (String) transportService.transport(query);
                    out.print(result);
                } else {
                    throw new TransportException(
                            "Transport Servlet could not locate transport web service with transportId: "
                                    + transportId);
                }
            } else {
                throw new TransportException("Transport Servlet not supplied with transportId");
            }
        } catch (ParseException e) {
            //log and put something in response
            logger.log(Level.SEVERE, "", e);
        } catch (ServiceException e) {
            //log and put something in response
            logger.log(Level.SEVERE, "", e);
        } catch (IOException e) {
            //log and put something in response
            logger.log(Level.SEVERE, "", e);
            throw (e);
        } catch (TransportException e) {
            logger.log(Level.SEVERE, "", e);
        }
    } finally {
        out.close();
    }
    processRequest(request, response);
}

From source file:org.bedework.notifier.web.MethodBase.java

protected Map<?, ?> getJson(final HttpServletRequest req, final HttpServletResponse resp) throws NoteException {
    final int len = req.getContentLength();
    if (len == 0) {
        return null;
    }//from  w w w. j a v  a 2  s.  co  m

    try {
        return (Map<?, ?>) om.readValue(req.getInputStream(), Object.class);
    } catch (Throwable t) {
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        throw new NoteException(t);
    }
}

From source file:it.anyplace.sync.httprelay.server.HttpRelayServer.java

public void start(int port) throws Exception {
    server = new Server(port);
    //            if (soapSsl) {
    //                SslContextFactory sslContextFactory = new SslContextFactory();
    //                sslContextFactory.setKeyStorePath(Main.class.getResource("/keystore.jks").toExternalForm());
    //                sslContextFactory.setKeyStorePassword("cjstorepass");
    //                sslContextFactory.setKeyManagerPassword("cjrestkeypass");
    //                SslSocketConnector connector = new SslSocketConnector(sslContextFactory);
    //                connector.setPort(serverPort);
    //                server.setConnectors(new Connector[]{connector});
    //            } else {
    //                SocketConnector connector = new SocketConnector();
    //                connector.setPort(port);
    //                server.setConnectors(new Connector[]{connector});
    //            }

    server.setHandler(new AbstractHandler() {

        @Override/*from w ww  .  j ava2s.c  om*/
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {
            logger.trace("handling requenst");
            HttpRelayProtos.HttpRelayServerMessage serverMessage;
            try {
                HttpRelayProtos.HttpRelayPeerMessage peerMessage = HttpRelayProtos.HttpRelayPeerMessage
                        .parseFrom(request.getInputStream());
                logger.debug("handle peer message type = {} session id = {} sequence = {}",
                        peerMessage.getMessageType(), peerMessage.getSessionId(), peerMessage.getSequence());
                serverMessage = handleMessage(peerMessage);
            } catch (Exception ex) {
                logger.error("error", ex);
                serverMessage = HttpRelayProtos.HttpRelayServerMessage.newBuilder()
                        .setMessageType(HttpRelayProtos.HttpRelayServerMessageType.ERROR)
                        .setData(ByteString.copyFromUtf8("error : " + ex.toString())).build();
            }
            logger.debug("send server response message type = {} session id = {} sequence = {}",
                    serverMessage.getMessageType(), serverMessage.getSessionId(), serverMessage.getSequence());
            try {
                serverMessage.writeTo(response.getOutputStream());
                response.getOutputStream().flush();
            } catch (Exception ex) {
                logger.error("error", ex);
            }
        }
    });
    server.start();
    logger.info("http relay server READY on port {}", port);
}

From source file:com.bluelotussoftware.apache.commons.fileupload.example.OctetStreamReader.java

/** 
 * Handles the HTTP <code>POST</code> method.
 * @param request servlet request/*www. j a  v a2s  . c o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {

    PrintWriter writer = null;
    InputStream is = null;
    FileOutputStream fos = null;

    try {
        writer = response.getWriter();
    } catch (IOException ex) {
        log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage());
    }

    String filename = request.getHeader("X-File-Name");
    try {
        is = request.getInputStream();
        fos = new FileOutputStream(new File(realPath + filename));
        IOUtils.copy(is, fos);
        response.setStatus(response.SC_OK);
        writer.print("{success: true}");
    } catch (FileNotFoundException ex) {
        response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
        writer.print("{success: false}");
        log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage());
    } catch (IOException ex) {
        response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
        writer.print("{success: false}");
        log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage());
    } finally {
        try {
            fos.close();
            is.close();
        } catch (IOException ignored) {
        }
    }

    writer.flush();
    writer.close();
}

From source file:com.honnix.yaacs.adapter.http.ACRequestHandler.java

private Map<String, String> getParameterMap(HttpServletRequest request) {
    Map<String, String> paramMap = null;
    InputStream inputStream = getRequestInputStream(request);

    if (inputStream != null) {
        try {//from w ww  .j a  v  a 2  s  .  co m
            paramMap = ACHttpBodyUtil.buildParameterMap(request.getInputStream(),
                    ACHttpPropertiesConstant.HTTP_CHARSET);
        } catch (IOException e) {
            LOG.warn(ACError.CORRUPTED_REQUEST, e);
        } finally {
            StreamUtil.closeStream(inputStream);
        }
    }

    return paramMap;
}

From source file:net.sf.farrago.server.FarragoServletCommandSink.java

private void handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException {
    ObjectInputStream ois = null;
    ObjectOutputStream oos = null;

    try {//from  ww w  .  ja v  a 2 s. c o  m
        // Get the method to execute
        String method = httpServletRequest.getHeader(ServletCommandSinkIdentifier.METHOD_IDENTIFIER);

        if (method != null) {
            ois = new ObjectInputStream(httpServletRequest.getInputStream());
            // And initialize the output
            OutputStream os = httpServletResponse.getOutputStream();
            oos = new ObjectOutputStream(os);
            Object objectToReturn = null;

            try {
                // Some command to process ?
                if (method.equals(ServletCommandSinkIdentifier.PROCESS_COMMAND)) {
                    // Read parameter objects
                    Long connuid = (Long) ois.readObject();
                    Long uid = (Long) ois.readObject();
                    Command cmd = (Command) ois.readObject();
                    CallingContext ctx = (CallingContext) ois.readObject();
                    // Delegate execution to the CommandProcessor
                    objectToReturn = processor.process(connuid, uid, cmd, ctx);
                } else if (method.equals(ServletCommandSinkIdentifier.CONNECT_COMMAND)) {
                    String url = ois.readUTF();
                    Properties props = (Properties) ois.readObject();
                    Properties clientInfo = (Properties) ois.readObject();
                    CallingContext ctx = (CallingContext) ois.readObject();

                    ConnectionConfiguration connectionConfiguration = VJdbcConfiguration.singleton()
                            .getConnection(url);

                    if (connectionConfiguration != null) {
                        Connection conn = connectionConfiguration.create(props);
                        objectToReturn = processor.registerConnection(conn, connectionConfiguration, clientInfo,
                                ctx);
                    } else {
                        objectToReturn = new SQLException("VJDBC-Connection " + url + " not found");
                    }
                }
            } catch (Throwable t) {
                // Wrap any exception so that it can be transported back to
                // the client
                objectToReturn = SQLExceptionHelper.wrap(t);
            }

            // Write the result in the response buffer
            oos.writeObject(objectToReturn);
            oos.flush();

            httpServletResponse.flushBuffer();
        } else {
            // No VJDBC-Method ? Then we redirect the stupid browser user to
            // some information page :-)
            httpServletResponse.sendRedirect("index.html");
        }
    } catch (Exception e) {
        logger.error("Unexpected Exception", e);
        throw new ServletException(e);
    } finally {
        StreamCloser.close(ois);
        StreamCloser.close(oos);
    }
}

From source file:com.grameenfoundation.ictc.controllers.FarmManagementPlanController.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  www  .  j  a v a 2 s .com*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    Logger log = Logger.getLogger(FarmManagementPlanController.class.getName());
    BiodataModel biodataModel = new BiodataModel();
    String theString = IOUtils.toString(request.getInputStream(), "UTF-8");
    System.out.println("Salesforce data/n " + theString);
    Transaction tx;
    tx = ICTCDBUtil.getInstance().getGraphDB().beginTx();
    org.neo4j.graphdb.Node farmManagementPlanParent;
    try (PrintWriter out = response.getWriter()) {

        System.out.println(" " + request.getContentType());

        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(theString));
        System.out.println("After parsing XML");
        Document doc = db.parse(is);
        System.out.println("Should be normalised now");
        doc.getDocumentElement().normalize();

        Element ele = doc.getDocumentElement();
        //System.out.println("Root element :" + doc.getDocumentElement());
        Node node = doc.getDocumentElement();

        System.out.println("Root element " + doc.getDocumentElement());

        //get fields from objects
        NodeList sObject = doc.getElementsByTagName("sObject");
        // String farmerID = getXmlNodeValue("sf:Farmer_name__c",ele);

        for (int j = 0; j < sObject.getLength(); j++) {

            Node rowNode = sObject.item(j);
            //  Map<String,String> m = (Map<String,String>) rowNode.getAttributes();
            String salesforceObj = rowNode.getAttributes().getNamedItem("xsi:type").getNodeValue();
            System.out.println(salesforceObj);
            String farmerID = getXmlNodeValue("sf:Farmer_name__c", ele);
            System.out.println("farmerid " + farmerID);
            org.neo4j.graphdb.Node FMPNode = ICTCDBUtil.getInstance().getGraphDB()
                    .createNode(Labels.FARM_MANAGEMENT_PLAN);
            for (int k = 0; k < rowNode.getChildNodes().getLength(); k++) {

                //System.out.println("node: " + rowNode.getChildNodes().item(k).getNodeName() + ": " + rowNode.getChildNodes().item(k).getTextContent());
                if (rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id")) {
                    System.out
                            .println("id : " + getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName()));
                    FMPNode.setProperty(getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName()),
                            rowNode.getChildNodes().item(k).getTextContent());
                }

                if (!rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id")
                        && !rowNode.getChildNodes().item(k).getNodeName().equals("#text")) {

                    System.out.println(getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName()));
                    FMPNode.setProperty(getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName()),
                            rowNode.getChildNodes().item(k).getTextContent());

                }
            }

            farmManagementPlanParent = ParentNode.FMPlanParentNode();
            farmManagementPlanParent.createRelationshipTo(FMPNode, ICTCRelationshipTypes.FARM_MANAGEMENT_PLAN);

            log.log(Level.INFO, "new node created {0}", FMPNode.getId());
            Biodata b = biodataModel.getBiodata("Id", farmerID);

            biodataModel.BiodataToFMP(b.getId(), FMPNode);

            tx.success();

            out.println(sendAck());

        }

    } catch (ParserConfigurationException ex) {
        Logger.getLogger(FarmManagementPlanController.class.getName()).log(Level.SEVERE, null, ex);
        tx.failure();
    } catch (SAXException ex) {
        tx.failure();
        Logger.getLogger(FarmManagementPlanController.class.getName()).log(Level.SEVERE, null, ex);
    } finally {

        tx.finish();
    }
}