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:net.sf.sripathi.ws.mock.servlet.MockServlet.java

/**
 * The service operation generated the mocked response for the input SOAP request message.
 *///from   w w  w .jav  a 2s  .c  o  m
@Override
public void service(HttpServletRequest req, HttpServletResponse resp) {

    long startTime = System.currentTimeMillis();

    try {
        String tmp = req.getRequestURI().substring((req.getContextPath() + "/mock/").length());
        String[] tmps = tmp.split("/");

        String domainName = tmps[0];

        Domain domain = DomainFactory.getInstance().getDomain(domainName);

        String soapResp = null;
        String soapReq = "";
        if (tmps.length != 3) {
            soapResp = SoapUtil.getSoapFault("NOT_A_VALID_URL", "URL " + req.getRequestURI() + " is not valid");
        } else if (domain == null) {
            soapResp = SoapUtil.getSoapFault("NOT_A_VALID_PROFILE", "Domain " + domainName + " is not valid");
            LOGGER.error(soapResp);
        } else {
            String serviceName = tmps[2];

            Service service = domain.getService(serviceName);

            if (service == null) {
                soapResp = SoapUtil.getSoapFault("NOT_A_VALID_SERVICE",
                        "Service " + serviceName + " is not valid");
                LOGGER.error(soapResp);
            } else {
                LOGGER.info("Request received for service - " + serviceName + " on domain - " + domainName);
                InputStream is = req.getInputStream();

                soapReq = new String(IOUtils.toByteArray(is));

                this.getLogger(domainName, serviceName).info("Request - " + soapReq);
                try {
                    Scenario scenario = service.getMockResponse(soapReq);
                    soapResp = scenario.getResponse();

                    if (scenario.getDelayInMilliSec() > 0) {
                        long curTime = System.currentTimeMillis();
                        long diff = curTime - startTime;
                        if (diff < scenario.getDelayInMilliSec()) {
                            Thread.sleep(scenario.getDelayInMilliSec() - diff);
                        }
                    }

                } catch (MockException me) {
                    soapResp = SoapUtil.getSoapFault("UNABLE_TO_PROCESS_REQ", me.getMessage());
                }
                this.getLogger(domainName, serviceName).info("Mock Response - " + soapResp);
            }
        }

        if (soapReq.contains(javax.xml.soap.SOAPConstants.URI_NS_SOAP_1_2_ENVELOPE)) {
            resp.setContentType(javax.xml.soap.SOAPConstants.SOAP_1_2_CONTENT_TYPE);
        } else {
            resp.setContentType(javax.xml.soap.SOAPConstants.SOAP_1_1_CONTENT_TYPE);
        }

        if (soapResp != null && soapResp.indexOf("Fault>") != -1 && soapResp.indexOf("faultcode>") != -1
                && soapResp.indexOf("faultstring>") != -1) {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }

        resp.getOutputStream().write(soapResp.getBytes());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:be.integrationarchitects.web.dragdrop.servlet.impl.DragDropServletUtils.java

protected Map<String, Map<String, String>> getHeadersParams(HttpServletRequest request,
        boolean readFormDataPost) throws IOException {
    Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>();

    Map<String, String> reqparams = new HashMap<String, String>();
    Map<String, String> reqheaders = new HashMap<String, String>();
    map.put("params", reqparams);
    map.put("headers", reqheaders);

    if (readFormDataPost) {
        // servlet api <3.0 will return null values for formdata post, from 3.0 servlet api use request.getParts()
        //using 2.0 api and parsing ourselves parts

        // in the javascript we use jquery object.serialize() to submit the form with ajax
        //this format is used:
        /**FORM DATA will be:
         * /*from   ww w  .j a  v a  2 s .c o  m*/
         * ------WebKitFormBoundary3UAOvASvkiQACgBY
        Content-Disposition: form-data; name="formsubmitdata"
                
        dropId=1406409768959&md5_1=5b9f16527d8d27f541cbb3fabf432eb6&filename_1=17.csv&doctype_1=
        ------WebKitFormBoundary3UAOvASvkiQACgBY--
         */
        InputStream in = request.getInputStream();
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        byte[] buff = new byte[10000];
        int bytesread = 0;
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String line = null;
        //while((line=br.readLine()).length()>0){
        while ((bytesread = in.read(buff)) > 0) {
            bout.write(buff, 0, bytesread);

            //System.out.println("FORMDATA:"+new String(buff,0,bytesread));
            //         System.out.println("FORMDATA:"+line);
            //bout.write(buff,0,bytesread);

            //                if(!line.startsWith("Content-Disposition")){
            //                         //bout.write(buff,0,bytesread);
            //                       bout.write(line.getBytes());
            //           }
        }
        String formparamsStr = new String(bout.toByteArray());
        logger.logTrace("FORMDATA:" + formparamsStr);
        int jj = formparamsStr.indexOf("name=\"formsubmitdata\"");
        formparamsStr = formparamsStr.substring(jj + 21);
        jj = formparamsStr.indexOf("---");
        formparamsStr = formparamsStr.substring(0, jj);

        String[] formParamPairs = formparamsStr.split("&");
        if (formParamPairs != null) {
            for (String pair : formParamPairs) {

                int ii = pair.indexOf("=");
                if (ii <= 0) {
                    continue;
                }
                String key = pair.substring(0, ii).trim();
                String value = pair.substring(ii + 1).trim();
                value = URLDecoder.decode(value, "UTF-8");
                reqparams.put(key, value);
                logger.logTrace("FORM PARAM:" + key + ":" + value);

            }
        }
        logger.logTrace("FORM PARAMZZ:" + reqparams);

    }

    Enumeration<String> headers = request.getHeaderNames();
    while (headers.hasMoreElements()) {
        String header = headers.nextElement();
        String val = request.getHeader(header);
        logger.logTrace("HEADER:" + header + "=" + val);
        reqheaders.put(header, val);
    }

    Enumeration<String> params = request.getParameterNames();
    if (params == null)
        return map;

    while (params.hasMoreElements()) {
        String param = params.nextElement();
        if (param == null)
            continue;

        String val = request.getHeader(param);
        logger.logTrace("PARAM:" + param + "=" + val);
        reqparams.put(param, val);

    }
    return map;
}

From source file:keyserver.KeyServerServlet.java

private void oneStepPictureUpload(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    User user = getCurrentGoogleUser();// ww w.  j a va2 s .  com
    try {
        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

        Key userId = KeyFactory.createKey(DB_KIND_USER, user.getUserId());
        Query query = new Query(DB_KIND_USER, userId);
        Entity identification = datastore.prepare(query).asSingleEntity();

        String userKey;

        if (identification == null) { // a new user (not in the DB)
            Entity newUser = new Entity(DB_KIND_USER, user.getUserId());
            userKey = createKeyForUser(user);
            newUser.setProperty(DB_USER_KEY, userKey);
            datastore.put(newUser);
            identification = newUser;
        } else { // user was already in the DB
            userKey = (String) identification.getProperty(DB_USER_KEY);
        }

        JSONArray array = new JSONArray(
                (new BufferedReader(new InputStreamReader(req.getInputStream()))).readLine());
        JSONObject obj;
        obj = array.getJSONObject(0);
        Entity newPicture = new Entity(DB_KIND_PICTURE, identification.getKey());
        newPicture.setProperty(DB_PICTURE_CREATED,
                new SimpleDateFormat(MISC_DATE_FORMAT, Locale.US).format(new Date()));
        newPicture.setProperty(DB_PICTURE_FILENAME, obj.get(JSON_FILENAME));
        newPicture.setProperty(DB_PICTURE_HEIGHT, obj.get(JSON_IMGHEIGHT));
        newPicture.setProperty(DB_PICTURE_WIDTH, obj.get(JSON_IMGWIDTH));
        datastore.put(newPicture);

        JSONArray response = new JSONArray();
        Key picId = newPicture.getKey();

        response.put(new JSONObject(JSON_DEFAULTOK));
        response.put(new JSONObject("{\"" + JSON_PICTUREID + "\": \"" + KeyFactory.keyToString(picId) + "\"}"));

        Entity newLine;
        JSONArray usernames;
        String key;
        int x0, xEnd, y0, yEnd;
        for (int i = 1; i < array.length(); i++) {
            obj = array.getJSONObject(i);
            x0 = obj.getInt(JSON_HSTART);
            xEnd = obj.getInt(JSON_HEND);
            y0 = obj.getInt(JSON_VSTART);
            yEnd = obj.getInt(JSON_VEND);
            usernames = obj.getJSONArray(JSON_USERNAME);

            for (int j = 0; j < usernames.length(); j++) {
                newLine = new Entity(DB_KIND_PERMISSION, picId);
                newLine.setProperty(DB_PERMISSION_H_START, x0);
                newLine.setProperty(DB_PERMISSION_H_END, xEnd);
                newLine.setProperty(DB_PERMISSION_V_START, y0);
                newLine.setProperty(DB_PERMISSION_V_END, yEnd);
                newLine.setProperty(DB_PERMISSION_USERNAME, (String) usernames.get(j));
                datastore.put(newLine);
            }
            key = createKeyForPermission(userKey, picId, obj.getInt(JSON_HSTART), obj.getInt(JSON_HEND),
                    obj.getInt(JSON_VSTART), obj.getInt(JSON_VEND));
            response.put(new JSONObject("{\"" + JSON_KEY + "\": \"" + key + "\"}"));
        }
        resp.getWriter().print(response.toString());
    } catch (JSONException jsonEx) {
        JSONArray error = createJsonErrorObject("Malformed JSON object received");
        resp.getWriter().print(error);
    }
}

From source file:com.funambol.server.sendlog.LogServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 * @param request servlet request/*from  w w  w .  j a v a 2 s  .c o m*/
 * @param response servlet response
 * @throws javax.servlet.ServletException
 * @throws java.io.IOException
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // Checks mandatory headers:
    if (!validateMandatoryHeaders(request, response)) {
        //
        // If the mandatory headers are missed or in a bad format, it's
        // not possible to continue..
        //
        return;
    }

    // Authorizes and authenticates the user
    HttpBasicAuthenticator authenticator = null;
    try {

        if (log.isTraceEnabled()) {
            log.trace("Authenticating the incoming request..");
        }
        authenticator = new HttpBasicAuthenticator(credentialHeader, deviceId);

        authenticator.authenticate();

    } catch (UnauthorizedException e) {
        log.error(AUTHENTICATE_REQUEST_ERRMSG, e);
        handleError(response, e);
        return;
    } catch (Throwable e) {
        log.error(AUTHENTICATE_REQUEST_UNEXPECTED_ERRMSG, e);
        handleError(response, e);
        return;
    }

    InputStream inputStream = null;
    try {
        inputStream = request.getInputStream();
    } catch (IOException e) {
        log.error(ACCESS_REQUEST_AS_INPUT_STREAM_ERRMSG, e);
        handleError(response, e);
        return;
    }

    LogInformationProvider provider = null;
    FileUploader uploader = null;
    try {
        if (log.isTraceEnabled()) {
            log.trace("Handling the incoming request..");
        }
        String username = authenticator.getUsername();
        provider = new LogInformationProvider(inputStream, username, deviceId, contentType, clientsLogBaseDir,
                clientsLogMaxSize);

        uploader = new FileUploader(provider);

        uploader.uploadFile();

    } catch (UploadFileException e) {
        log.error(PROCESSING_UPLOAD_ERRMSG, e);
        handleError(response, e);
        return;
    } catch (Throwable e) {
        log.error(HANDLE_REQUEST_UNEXPECTED_ERRMSG, e);
        handleError(response, e);
        return;
    }

    PrintWriter writer = null;
    try {
        response.setContentType(MimeTypeDictionary.TEXT_PLAIN);
        response.setStatus(HttpServletResponse.SC_OK);
        writer = response.getWriter();
        writer.write(UPLOAD_COMPLETED_MSG);
        writer.flush();

    } finally {
        if (writer != null) {
            writer.close();
        }
    }
}

From source file:photosharing.api.conx.CommentsDefinition.java

/**
 * manages interactions with comments based on method
 * //from   w  w  w  .  j a v  a 2s.  c  o  m
 * @see photosharing.api.base.APIDefinition#run(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 */
@Override
public void run(HttpServletRequest request, HttpServletResponse response) {
    // HTTP Method that the request was made with:
    String method = request.getMethod();

    /**
     * get the users bearer token
     */
    HttpSession session = request.getSession(false);
    Object o = session.getAttribute(OAuth20Handler.CREDENTIALS);
    if (o == null) {
        logger.warning("Credential Object is not present");
    } else {
        OAuth20Data data = (OAuth20Data) o;
        String bearer = data.getAccessToken();

        // Create a Comment
        if (method.compareTo("POST") == 0) {
            // Extract the URL parameters from the request
            String pid = request.getParameter("pid");
            String uid = request.getParameter("uid");

            try {
                String body = IOUtils.toString(request.getInputStream());

                // Checks the State of the URL parameters
                if (pid == null || uid == null || body == null || body.isEmpty() || pid.isEmpty()
                        || uid.isEmpty()) {
                    response.setStatus(HttpStatus.SC_PRECONDITION_FAILED);
                } else {
                    String nonce = getNonce(bearer, response);
                    if (!nonce.isEmpty()) {
                        createComment(bearer, pid, uid, body, nonce, response);
                    }
                }

            } catch (IOException e) {
                response.setHeader("X-Application-Error", e.getClass().getName());
                response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
                logger.severe("Issue with POST comment" + e.toString());
            }
        }
        // Update a Comment
        else if (method.compareTo("PUT") == 0) {
            // Extract the URL parameters from the request
            String cid = request.getParameter("cid");
            String pid = request.getParameter("pid");
            String uid = request.getParameter("uid");

            try {
                String body = IOUtils.toString(request.getInputStream());

                // Checks the State of the URL parameters
                if (cid == null || pid == null || uid == null || body == null || body.isEmpty() || cid.isEmpty()
                        || pid.isEmpty() || uid.isEmpty()) {
                    response.setStatus(HttpStatus.SC_PRECONDITION_FAILED);
                } else {
                    String nonce = getNonce(bearer, response);
                    if (!nonce.isEmpty()) {
                        updateComment(bearer, cid, pid, uid, body, nonce, response);
                    }
                }

            } catch (IOException e) {
                response.setHeader("X-Application-Error", e.getClass().getName());
                response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
                logger.severe("Issue with PUT comment" + e.toString());
            }

        }
        // Delete a Comment
        else if (method.compareTo("DELETE") == 0) {
            // Extract the URL parameters from the request
            String cid = request.getParameter("cid");
            String pid = request.getParameter("pid");
            String uid = request.getParameter("uid");

            // Checks the State of the URL parameters
            if (cid == null || pid == null || uid == null || cid.isEmpty() || pid.isEmpty() || uid.isEmpty()) {
                response.setStatus(HttpStatus.SC_PRECONDITION_FAILED);
            } else {
                String nonce = getNonce(bearer, response);

                if (!nonce.isEmpty()) {
                    deleteComment(bearer, cid, pid, uid, response, nonce);
                }
            }

        }
        // Read a Comment and default to a GET
        else {
            // Extract the URL parameters from the request
            String pid = request.getParameter("pid");
            String uid = request.getParameter("uid");

            if (pid == null || uid == null || pid.isEmpty() || uid.isEmpty()) {
                response.setStatus(HttpStatus.SC_PRECONDITION_FAILED);
            } else {
                readComments(bearer, pid, uid, response);
            }

        }

    }

}

From source file:com.ge.apm.web.WeChatCoreController.java

/**
 * ?webservice??????//  w ww  .j  av a 2  s.  c o  m
 *
 * @param request
 * @param response
 * @throws Exception
 */
@RequestMapping(value = "core")
public void wechatCore(HttpServletRequest request, HttpServletResponse response) throws Exception {
    response.setContentType("text/html;charset=utf-8");
    response.setStatus(HttpServletResponse.SC_OK);

    String signature = request.getParameter("signature");
    String nonce = request.getParameter("nonce");
    String timestamp = request.getParameter("timestamp");

    if (!this.wxMpService.checkSignature(timestamp, nonce, signature)) {
        // ?????????
        response.getWriter().println("?");
        return;
    }

    String echoStr = request.getParameter("echostr");
    if (StringUtils.isNotBlank(echoStr)) {
        // ??echostr
        String echoStrOut = String.copyValueOf(echoStr.toCharArray());
        response.getWriter().println(echoStrOut);
        return;
    }
    System.out.println("current token is \n" + wxMpService.getAccessToken());
    String apiTicket = wxMpService.getJsapiTicket();
    System.out.println("current apiTicket is \n" + apiTicket);
    String encryptType = StringUtils.isBlank(request.getParameter("encrypt_type")) ? "raw"
            : request.getParameter("encrypt_type");

    if ("raw".equals(encryptType)) {
        // ?
        WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(request.getInputStream());
        WxMpXmlOutMessage outMessage = this.coreService.route(inMessage);
        response.getWriter().write(outMessage == null ? "" : outMessage.toXml());
        return;
    }

    if ("aes".equals(encryptType)) {
        // aes?
        String msgSignature = request.getParameter("msg_signature");
        WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(request.getInputStream(), this.configStorage,
                timestamp, nonce, msgSignature);
        WxMpXmlOutMessage outMessage = this.coreService.route(inMessage);
        response.getWriter().write(outMessage == null ? "" : outMessage.toEncryptedXml(this.configStorage));
        return;
    }

    response.getWriter().println("??");
    return;
}

From source file:org.basinmc.irc.bridge.github.GitHubServerHandler.java

/**
 * {@inheritDoc}//from w w  w  .j a va2  s  .c om
 */
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    // only handle requests to /
    if (!target.equals("/webhook")) {
        return;
    }

    // verify whether the call comes directly from GitHub using the X-GitHub-Event,
    // X-Hub-Signature and X-GitHub-Delivery headers
    String eventType = request.getHeader("X-GitHub-Event");
    String signature = request.getHeader("X-Hub-Signature");
    String deliveryId = request.getHeader("X-GitHub-Delivery");

    if (eventType == null || eventType.isEmpty()
            || (this.secret != null && (signature == null || signature.isEmpty())) || deliveryId == null
            || deliveryId.isEmpty()) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        baseRequest.setHandled(true);
        return;
    }

    if (signature != null) {
        // strip sha1=
        // TODO: Decide upon signature method based on this parameter
        signature = signature.substring(5);
    }

    logger.info("Processing GitHub request " + deliveryId + ".");

    // decode the data passed in the request body
    String data;
    try (InputStream inputStream = request.getInputStream()) {
        data = new String(ByteStreams.toByteArray(inputStream),
                Charset.forName(request.getCharacterEncoding()));
    }

    // verify the signature supplied to us (as long as a secret key was configured)
    try {
        if (!verifySignature(data, signature)) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            baseRequest.setHandled(true);
            return;
        }
    } catch (IllegalStateException ex) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        baseRequest.setHandled(true);
        return;
    }

    // find correct event message
    eventType = eventType.replace('_', '.');

    // de-serialize and handle event data
    Map<String, Object> context = new HashMap<>();
    context.put("color", COLOR_MAP);
    context.put("event", reader.readValue(data));

    String message = this.getMessage(eventType, context);

    if (message != null) {
        this.bridge.sendMessage(message);
    }

    // answer with 204 at all times
    response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    baseRequest.setHandled(true);
}

From source file:it.classhidra.core.controller.bsController.java

public static String getPropertyMultipart(String key, HttpServletRequest req) {

    try {/*from  ww w.  ja  v a  2s  . c om*/
        String file = (String) req.getAttribute("multipart/form-data");
        DataInputStream in = null;
        String contentType = req.getContentType();
        if (contentType != null && contentType.indexOf("multipart/form-data") != -1) {
            if (file == null) {
                in = new DataInputStream(req.getInputStream());
                int formDataLength = req.getContentLength();
                byte dataBytes[] = new byte[formDataLength];
                int bytesRead = 0;
                int totalBytesRead = 0;
                while (totalBytesRead < formDataLength) {
                    bytesRead = in.read(dataBytes, totalBytesRead, formDataLength);
                    totalBytesRead += bytesRead;
                }
                file = new String(dataBytes, 0, dataBytes.length, "ASCII");
                in.close();
                req.setAttribute("multipart/form-data", file);
            }

            String check = "Content-Disposition: form-data; name=\"" + key + "\"";

            int pos = file.indexOf(check);

            if (pos > -1) {
                int pos1 = file.indexOf("-----------------------------", pos);
                if (pos1 > -1) {
                    String result = file.substring(pos + check.length(), pos1);
                    result = result.replace('\n', ' ').replace('\r', ' ');
                    return result.trim();
                }
            }
        }

    } catch (Exception e) {
        new bsControllerException(e, iStub.log_DEBUG);

        return null;
    }
    return null;
}

From source file:it.classhidra.core.controller.bean.java

public boolean initJsonPart(HttpServletRequest request) throws bsControllerException {
    boolean isJson = false;
    HashMap parameters = new HashMap();
    DataInputStream in = null;/*from w w w. j a v  a 2  s.  c  o  m*/
    try {
        in = new DataInputStream(request.getInputStream());
        int formDataLength = request.getContentLength();

        byte dataBytes[] = new byte[formDataLength];
        int bytesRead = 0;
        int totalBytesRead = 0;
        while (totalBytesRead < formDataLength && totalBytesRead > -1) {
            bytesRead = in.read(dataBytes, totalBytesRead, formDataLength);
            totalBytesRead += bytesRead;
        }

        String json = new String(dataBytes, 0, dataBytes.length).trim();
        if (json.charAt(0) == '{' && json.charAt(json.length() - 1) == '}')
            isJson = true;
        if (isJson) {
            if (json.charAt(0) == '{' && json.length() > 0)
                json = json.substring(1, json.length());
            if (json.charAt(json.length() - 1) == '}' && json.length() > 0)
                json = json.substring(0, json.length() - 1);
            StringTokenizer st = new StringTokenizer(json, ",");
            while (st.hasMoreTokens()) {
                String pair = st.nextToken();
                StringTokenizer st1 = new StringTokenizer(pair, ":");
                String key = null;
                String value = null;
                if (st1.hasMoreTokens())
                    key = st1.nextToken();
                if (st1.hasMoreTokens())
                    value = st1.nextToken();
                if (key != null && value != null) {
                    key = key.trim();
                    if (key.charAt(0) == '"' && key.length() > 0)
                        key = key.substring(1, key.length());
                    if (key.charAt(key.length() - 1) == '"' && key.length() > 0)
                        key = key.substring(0, key.length() - 1);
                    value = value.trim();
                    if (value.charAt(0) == '"' && value.length() > 0)
                        value = value.substring(1, value.length());
                    if (value.charAt(value.length() - 1) == '"' && value.length() > 0)
                        value = value.substring(0, value.length() - 1);
                    parameters.put(key, value);
                }
            }
        }

    } catch (Exception e) {

    } finally {
        try {
            in.close();
        } catch (Exception ex) {
        }
    }

    if (isJson)
        initPartFromMap(parameters);

    return isJson;
}