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:com.github.safrain.remotegsh.server.RgshFilter.java

private void performShellExecute(HttpServletRequest request, HttpServletResponse response) throws IOException {
    ShellSession session = getSession(request.getParameter("sid"));
    if (session == null) {
        response.setStatus(410);// Http status GONE
        return;/*from   w  w w .  ja v  a2  s  .  c o  m*/
    }
    ScriptEngine engine = session.getEngine();

    String action = request.getParameter("action");
    if (action == null) {
        StringWriter responseWriter = new StringWriter();
        engine.getContext().setWriter(responseWriter);
        engine.getContext().setErrorWriter(response.getWriter());
        String script = toString(request.getInputStream(), charset);
        JSONObject json = new JSONObject();
        try {
            try {
                Object result = engine.eval(script);
                json.put("result", String.valueOf(result));
                response.setStatus(200);
                json.put("response", responseWriter.getBuffer().toString());
            } catch (ScriptException e) {
                log.log(Level.SEVERE, "Error while running shell command:" + script, e);
                response.setStatus(500);
                e.getCause().printStackTrace(response.getWriter());
                return;
            }
        } catch (JSONException e) {
            log.log(Level.SEVERE, "Error while running shell command:" + script, e);
            response.setStatus(500);
            e.printStackTrace(response.getWriter());
            return;
        }
        response.getWriter().write(json.toString());
    } else {
        Invocable invocable = (Invocable) engine;
        try {
            invocable.invokeFunction("shellAction", action);
        } catch (ScriptException e) {
            response.setStatus(500);
            e.printStackTrace(response.getWriter());
        } catch (NoSuchMethodException e) {
            response.setStatus(500);
            response.getWriter().println("Action not supported");
        } catch (Exception e) {
            response.setStatus(500);
            e.printStackTrace(response.getWriter());
        }
    }

}

From source file:com.google.glassware.NotifyServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Respond with OK and status 200 in a timely fashion to prevent redelivery
    response.setContentType("text/html");
    Writer writer = response.getWriter();
    writer.append("OK");
    writer.close();// ww  w  .jav a  2 s. com

    // Get the notification object from the request body (into a string so we
    // can log it)
    BufferedReader notificationReader = new BufferedReader(new InputStreamReader(request.getInputStream()));
    String notificationString = "";

    String responseStringForFaceDetection = null;
    // Count the lines as a very basic way to prevent Denial of Service attacks
    int lines = 0;
    String line;
    while ((line = notificationReader.readLine()) != null) {
        notificationString += line;
        lines++;

        // No notification would ever be this long. Something is very wrong.
        if (lines > 1000) {
            throw new IOException("Attempted to parse notification payload that was unexpectedly long.");
        }
    }
    notificationReader.close();

    LOG.info("got raw notification " + notificationString);

    JsonFactory jsonFactory = new JacksonFactory();

    // If logging the payload is not as important, use
    // jacksonFactory.fromInputStream instead.
    Notification notification = jsonFactory.fromString(notificationString, Notification.class);

    LOG.info("Got a notification with ID: " + notification.getItemId());

    // Figure out the impacted user and get their credentials for API calls
    String userId = notification.getUserToken();
    Credential credential = AuthUtil.getCredential(userId);
    Mirror mirrorClient = MirrorClient.getMirror(credential);

    if (notification.getCollection().equals("locations")) {
        LOG.info("Notification of updated location");
        Mirror glass = MirrorClient.getMirror(credential);
        // item id is usually 'latest'
        Location location = glass.locations().get(notification.getItemId()).execute();

        LOG.info("New location is " + location.getLatitude() + ", " + location.getLongitude());
        MirrorClient.insertTimelineItem(credential, new TimelineItem()
                .setText("Java Quick Start says you are now at " + location.getLatitude() + " by "
                        + location.getLongitude())
                .setNotification(new NotificationConfig().setLevel("DEFAULT")).setLocation(location)
                .setMenuItems(Lists.newArrayList(new MenuItem().setAction("NAVIGATE"))));

        // This is a location notification. Ping the device with a timeline item
        // telling them where they are.
    } else if (notification.getCollection().equals("timeline")) {
        // Get the impacted timeline item
        TimelineItem timelineItem = mirrorClient.timeline().get(notification.getItemId()).execute();
        LOG.info("Notification impacted timeline item with ID: " + timelineItem.getId());

        // If it was a share, and contains a photo, update the photo's caption to
        // acknowledge that we got it.
        if (notification.getUserActions().contains(new UserAction().setType("SHARE"))
                && timelineItem.getAttachments() != null && timelineItem.getAttachments().size() > 0) {
            String finalresponseForCard = null;

            String questionString = timelineItem.getText();
            if (!questionString.isEmpty()) {
                String[] questionStringArray = questionString.split(" ");

                LOG.info(timelineItem.getText() + " is the questions asked by the user");
                LOG.info("A picture was taken");

                if (questionString.toLowerCase().contains("search")
                        || questionString.toLowerCase().contains("tag")
                        || questionString.toLowerCase().contains("train")
                        || questionString.toLowerCase().contains("mark")
                        || questionString.toLowerCase().contains("recognize")
                        || questionString.toLowerCase().contains("what is")) {

                    //Fetching the image from the timeline
                    InputStream inputStream = downloadAttachment(mirrorClient, notification.getItemId(),
                            timelineItem.getAttachments().get(0));

                    //converting the image to Base64
                    Base64 base64Object = new Base64(false);
                    String encodedImageToBase64 = base64Object.encodeToString(IOUtils.toByteArray(inputStream)); //byteArrayForOutputStream.toByteArray()
                    // byteArrayForOutputStream.close();
                    encodedImageToBase64 = java.net.URLEncoder.encode(encodedImageToBase64, "ISO-8859-1");

                    //sending the API request
                    LOG.info("Sending request to API");
                    //For initial protoype we're calling the Alchemy API for detecting the number of Faces using web API call
                    try {
                        String urlParameters = "";
                        String tag = "";

                        if (questionString.toLowerCase().contains("tag")
                                || questionString.toLowerCase().contains("mark")) {

                            tag = extractTagFromQuestion(questionString);
                            urlParameters = "api_key=gE4P9Mze0ewOa976&api_secret=96JJ4G1bBLPaWLhf&jobs=object_add&name_space=recognizeObject&user_id=user1&tag="
                                    + tag + "&base64=" + encodedImageToBase64;

                        } else if (questionString.toLowerCase().contains("train")) {
                            urlParameters = "api_key=gE4P9Mze0ewOa976&api_secret=96JJ4G1bBLPaWLhf&jobs=object_train&name_space=recognizeObject&user_id=user1";
                        } else if (questionString.toLowerCase().contains("search")) {
                            urlParameters = "api_key=gE4P9Mze0ewOa976&api_secret=96JJ4G1bBLPaWLhf&jobs=object_search&name_space=recognizeObject&user_id=user1&base64="
                                    + encodedImageToBase64;
                        } else if (questionString.toLowerCase().contains("recognize")
                                || questionString.toLowerCase().contains("what is")) {
                            urlParameters = "api_key=gE4P9Mze0ewOa976&api_secret=96JJ4G1bBLPaWLhf&jobs=object_recognize&name_space=recognizeObject&user_id=user1&base64="
                                    + encodedImageToBase64;
                        }
                        byte[] postData = urlParameters.getBytes(Charset.forName("UTF-8"));
                        int postDataLength = postData.length;
                        String newrequest = "http://rekognition.com/func/api/";
                        URL url = new URL(newrequest);
                        HttpURLConnection connectionFaceDetection = (HttpURLConnection) url.openConnection();

                        // Increase the timeout for reading the response
                        connectionFaceDetection.setReadTimeout(15000);

                        connectionFaceDetection.setDoOutput(true);
                        connectionFaceDetection.setDoInput(true);
                        connectionFaceDetection.setInstanceFollowRedirects(false);
                        connectionFaceDetection.setRequestMethod("POST");
                        connectionFaceDetection.setRequestProperty("Content-Type",
                                "application/x-www-form-urlencoded");
                        connectionFaceDetection.setRequestProperty("X-Mashape-Key",
                                "pzFbNRvNM4mshgWJvvdw0wpLp5N1p1X3AX9jsnOhjDUkn5Lvrp");
                        connectionFaceDetection.setRequestProperty("charset", "utf-8");
                        connectionFaceDetection.setRequestProperty("Accept", "application/json");
                        connectionFaceDetection.setRequestProperty("Content-Length",
                                Integer.toString(postDataLength));
                        connectionFaceDetection.setUseCaches(false);

                        DataOutputStream outputStreamForFaceDetection = new DataOutputStream(
                                connectionFaceDetection.getOutputStream());
                        outputStreamForFaceDetection.write(postData);

                        BufferedReader inputStreamForFaceDetection = new BufferedReader(
                                new InputStreamReader((connectionFaceDetection.getInputStream())));

                        StringBuilder responseForFaceDetection = new StringBuilder();

                        while ((responseStringForFaceDetection = inputStreamForFaceDetection
                                .readLine()) != null) {
                            responseForFaceDetection.append(responseStringForFaceDetection);
                        }

                        //closing all the connections
                        inputStreamForFaceDetection.close();
                        outputStreamForFaceDetection.close();
                        connectionFaceDetection.disconnect();

                        responseStringForFaceDetection = responseForFaceDetection.toString();
                        LOG.info(responseStringForFaceDetection);

                        JSONObject responseJSONObjectForFaceDetection = new JSONObject(
                                responseStringForFaceDetection);
                        if (questionString.toLowerCase().contains("train") || questionString.contains("tag")
                                || questionString.toLowerCase().contains("mark")) {
                            JSONObject usageKeyFromResponse = responseJSONObjectForFaceDetection
                                    .getJSONObject("usage");
                            finalresponseForCard = usageKeyFromResponse.getString("status");
                            if (!tag.equals(""))
                                finalresponseForCard = "Object is tagged as " + tag;
                        } else {
                            JSONObject sceneUnderstandingObject = responseJSONObjectForFaceDetection
                                    .getJSONObject("scene_understanding");
                            JSONArray matchesArray = sceneUnderstandingObject.getJSONArray("matches");
                            JSONObject firstResultFromArray = matchesArray.getJSONObject(0);

                            double percentSureOfObject;
                            //If an score has value 1, then the value type is Integer else the value type is double
                            if (firstResultFromArray.get("score") instanceof Integer) {
                                percentSureOfObject = (Integer) firstResultFromArray.get("score") * 100;
                            } else
                                percentSureOfObject = (Double) firstResultFromArray.get("score") * 100;

                            finalresponseForCard = "The object is " + firstResultFromArray.getString("tag")
                                    + ". Match score is" + percentSureOfObject;
                        }

                        //section where if it doesn't contain anything about tag or train

                    } catch (Exception e) {
                        LOG.warning(e.getMessage());
                    }

                }

                else
                    finalresponseForCard = "Could not understand your words";
            } else
                finalresponseForCard = "Could not understand your words";

            TimelineItem responseCardForSDKAlchemyAPI = new TimelineItem();

            responseCardForSDKAlchemyAPI.setText(finalresponseForCard);
            responseCardForSDKAlchemyAPI
                    .setMenuItems(Lists.newArrayList(new MenuItem().setAction("READ_ALOUD")));
            responseCardForSDKAlchemyAPI.setSpeakableText(finalresponseForCard);
            responseCardForSDKAlchemyAPI.setSpeakableType("Results are as follows");
            responseCardForSDKAlchemyAPI.setNotification(new NotificationConfig().setLevel("DEFAULT"));
            mirrorClient.timeline().insert(responseCardForSDKAlchemyAPI).execute();
            LOG.info("New card added to the timeline");

        } else if (notification.getUserActions().contains(new UserAction().setType("LAUNCH"))) {
            LOG.info("It was a note taken with the 'take a note' voice command. Processing it.");

            // Grab the spoken text from the timeline card and update the card with
            // an HTML response (deleting the text as well).
            String noteText = timelineItem.getText();
            String utterance = CAT_UTTERANCES[new Random().nextInt(CAT_UTTERANCES.length)];

            timelineItem.setText(null);
            timelineItem.setHtml(makeHtmlForCard(
                    "<p class='text-auto-size'>" + "Oh, did you say " + noteText + "? " + utterance + "</p>"));
            timelineItem.setMenuItems(Lists.newArrayList(new MenuItem().setAction("DELETE")));

            mirrorClient.timeline().update(timelineItem.getId(), timelineItem).execute();
        } else {
            LOG.warning("I don't know what to do with this notification, so I'm ignoring it.");
        }
    }
}

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

private void executePutObjectAcl(HttpServletRequest request, HttpServletResponse response) throws IOException {
    S3PutObjectRequest putRequest = null;

    // -> reuse the Access Control List parsing code that was added to support DIME
    String bucketName = (String) request.getAttribute(S3Constants.BUCKET_ATTR_KEY);
    String key = (String) request.getAttribute(S3Constants.OBJECT_ATTR_KEY);
    try {//from  ww w  .  jav  a  2s  .c om
        putRequest = S3RestServlet.toEnginePutObjectRequest(request.getInputStream());
    } catch (Exception e) {
        throw new IOException(e.toString());
    }

    // -> reuse the SOAP code to save the passed in ACLs
    S3SetObjectAccessControlPolicyRequest engineRequest = new S3SetObjectAccessControlPolicyRequest();
    engineRequest.setBucketName(bucketName);
    engineRequest.setKey(key);
    engineRequest.setAcl(putRequest.getAcl());

    S3Response engineResponse = ServiceProvider.getInstance().getS3Engine().handleRequest(engineRequest);
    response.setStatus(engineResponse.getResultCode());
}

From source file:com.mnt.base.web.servlets.AccessRouterServlet.java

@SuppressWarnings("unchecked")
@Override/*from   ww w  .  jav a 2s .c  o  m*/
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    WebUtils.setupContext(req, resp);

    if (!WebUtils.checkAuth(req, resp)) {
        return;
    }

    String reqMethod = req.getMethod();
    String requestUri = req.getRequestURI();
    Map<String, Object> parameterMap = null;

    String contentType = req.getHeader("content-type");

    if (HTTP_GET.equalsIgnoreCase(reqMethod) || HTTP_DELETE.equalsIgnoreCase(reqMethod)
            || HTTP_HEAD.equalsIgnoreCase(reqMethod) || !"application/json".equalsIgnoreCase(contentType)) {
        parameterMap = new LinkedHashMap<String, Object>();
        parameterMap.putAll(req.getParameterMap());
    } else {
        String requestContent = null;
        try {
            requestContent = HttpUtil.readData(req.getInputStream());
        } catch (IOException e) {
            log.error("Fail to read the http request content. SKIP the request.", e);
            resp.getOutputStream().close();
            return;
        }

        if (!CommonUtil.isEmpty(requestContent)) {
            try {
                parameterMap = (Map<String, Object>) JSONTool.convertJsonToObject(requestContent);
            } catch (Exception e) {
                if (log.isDebugEnabled()) {
                    log.debug("Fail to convert the json string to parameter map. SKIP the request: "
                            + requestContent, e);
                }

                InvalidPostHandler invalidPostHandler = null;

                try {
                    invalidPostHandler = BeanContext.getInstance().getBean("invalidPostHandler",
                            InvalidPostHandler.class);
                } catch (Exception skipe) {
                    // skip it
                }

                if (invalidPostHandler != null) {
                    try {
                        invalidPostHandler.handle(req, resp, requestContent);
                    } catch (Exception e1) {
                        log.error("error while handle invalid post request.", e);
                    }
                } else {
                    resp.getOutputStream().close();
                }
                return;
            }
        } else {
            parameterMap = new LinkedHashMap<String, Object>();
        }
    }

    actionControllerManager.dispatchRequest(requestUri, req.getMethod(), parameterMap,
            new HTMLResponseHandler(resp, BaseConfiguration.getResponseContentType()));
    CommonUtil.deepClear(parameterMap);

    WebUtils.clearContext();
}

From source file:com.kdab.daytona.Logger.java

@Override
public void doPut(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (m_error) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        PrintWriter out = response.getWriter();
        out.println("Daytona not operational. See server log for details.");
        out.flush();//from  www  . ja  va 2s.  c  o  m
        out.close();
        return;
    }

    String format = request.getParameter("format");
    if (format == null)
        format = "xml";

    if (!m_queuesByFormat.containsKey(format)) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        PrintWriter out = response.getWriter();
        out.println(String.format("Unknown format \'%s\'.", format));
        out.flush();
        out.close();
        return;
    }

    byte[] ba = IOUtils.toByteArray(request.getInputStream());
    try {
        m_queuesByFormat.get(format).put(ba);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }

    PrintWriter out = response.getWriter();
    out.println("Message received.");
    out.flush();
    out.close();
}

From source file:mapbuilder.ProxyRedirect.java

/***************************************************************************
 * Process the HTTP Post request//  w  ww  . j a v a  2  s.c  om
 */
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {
        if (log.isDebugEnabled()) {
            Enumeration e = request.getHeaderNames();
            while (e.hasMoreElements()) {
                String name = (String) e.nextElement();
                String value = request.getHeader(name);
                log.debug("request header:" + name + ":" + value);
            }
        }

        String serverUrl = request.getHeader("serverUrl");
        if (serverUrl.startsWith("http://") || serverUrl.startsWith("https://")) {
            PostMethod httppost = new PostMethod(serverUrl);

            // Transfer bytes from in to out
            log.info("HTTP POST transfering..." + serverUrl);
            String body = inputStreamAsString(request.getInputStream());

            HttpClient client = new HttpClient();

            httppost.setRequestBody(body);
            if (0 == httppost.getParameters().length) {
                log.debug("No Name/Value pairs found ... pushing as raw_post_data");
                httppost.setParameter("raw_post_data", body);
            }
            if (log.isDebugEnabled()) {
                log.debug("Body = " + body);
                NameValuePair[] nameValuePairs = httppost.getParameters();
                log.debug("NameValuePairs found: " + nameValuePairs.length);
                for (int i = 0; i < nameValuePairs.length; ++i) {
                    log.debug("parameters:" + nameValuePairs[i].toString());
                }
            }
            //httppost.setRequestContentLength(PostMethod.CONTENT_LENGTH_CHUNKED);

            client.executeMethod(httppost);
            if (log.isDebugEnabled()) {
                Header[] respHeaders = httppost.getResponseHeaders();
                for (int i = 0; i < respHeaders.length; ++i) {
                    String headerName = respHeaders[i].getName();
                    String headerValue = respHeaders[i].getValue();
                    log.debug("responseHeaders:" + headerName + "=" + headerValue);
                }
            }

            if (httppost.getStatusCode() == HttpStatus.SC_OK) {
                response.setContentType("text/xml");
                String responseBody = httppost.getResponseBodyAsString();
                // use encoding of the request or UTF8
                String encoding = request.getCharacterEncoding();
                if (encoding == null)
                    encoding = "UTF-8";
                response.setCharacterEncoding(encoding);
                log.info("responseEncoding:" + encoding);
                // do not set a content-length of the response (string length might not match the response byte size)
                //response.setContentLength(responseBody.length());
                log.info("responseBody:" + responseBody);
                PrintWriter out = response.getWriter();
                out.print(responseBody);
            } else {
                log.error("Unexpected failure: " + httppost.getStatusLine().toString());
            }
            httppost.releaseConnection();
        } else {
            throw new ServletException("only HTTP(S) protocol supported");
        }

    } catch (Throwable e) {
        throw new ServletException(e);
    }
}

From source file:io.ericwittmann.corsproxy.ProxyServlet.java

/**
 * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *///from   w  w w.j  a  va2s. c  o m
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String url = "https://issues.jboss.org" + req.getPathInfo();
    if (req.getQueryString() != null) {
        url += "?" + req.getQueryString();
    }

    System.out.println("Proxying to: " + url);
    boolean isWrite = req.getMethod().equalsIgnoreCase("post") || req.getMethod().equalsIgnoreCase("put");

    URL remoteUrl = new URL(url);
    HttpURLConnection remoteConn = (HttpURLConnection) remoteUrl.openConnection();
    if (isWrite) {
        remoteConn.setDoOutput(true);
    }

    String auth = req.getHeader("Authorization");
    if (auth != null) {
        remoteConn.setRequestProperty("Authorization", auth);
    }

    if (isWrite) {
        InputStream requestIS = null;
        OutputStream remoteOS = null;
        try {
            requestIS = req.getInputStream();
            remoteOS = remoteConn.getOutputStream();
            IOUtils.copy(requestIS, remoteOS);
            remoteOS.flush();
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendError(500, e.getMessage());
            return;
        } finally {
            IOUtils.closeQuietly(requestIS);
            IOUtils.closeQuietly(remoteOS);
        }
    }

    InputStream remoteIS = null;
    OutputStream responseOS = null;
    try {
        Map<String, List<String>> headerFields = remoteConn.getHeaderFields();
        for (String headerName : headerFields.keySet()) {
            if (headerName == null) {
                continue;
            }
            if (EXCLUDE_HEADERS.contains(headerName)) {
                continue;
            }
            String headerValue = remoteConn.getHeaderField(headerName);
            resp.setHeader(headerName, headerValue);
        }
        resp.setHeader("Cache-control", "no-cache, no-store, must-revalidate"); //$NON-NLS-2$
        remoteIS = remoteConn.getInputStream();
        responseOS = resp.getOutputStream();
        IOUtils.copy(remoteIS, responseOS);
        resp.flushBuffer();
    } catch (Exception e) {
        e.printStackTrace();
        resp.sendError(500, e.getMessage());
    } finally {
        IOUtils.closeQuietly(responseOS);
        IOUtils.closeQuietly(remoteIS);
    }
}