Example usage for javax.servlet ServletInputStream read

List of usage examples for javax.servlet ServletInputStream read

Introduction

In this page you can find the example usage for javax.servlet ServletInputStream read.

Prototype

public int read(byte b[], int off, int len) throws IOException 

Source Link

Document

Reads up to len bytes of data from the input stream into an array of bytes.

Usage

From source file:es.tid.cep.esperanza.Events.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from w  w w  . j a v a 2s  .  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, IOException {
    logger.debug("events doPost");
    PrintWriter out = response.getWriter();
    try {
        response.setContentType("application/json;charset=UTF-8");
        ServletInputStream sis = request.getInputStream();
        byte[] b = new byte[request.getContentLength()];
        sis.read(b, 0, b.length);
        sis.close();
        String eventText = new String(b);
        logger.debug("event as text:" + eventText);
        org.json.JSONObject jo = new JSONObject(eventText);
        logger.debug("event as JSONObject: " + jo);
        Map<String, Object> otro = Utils.JSONObject2Map(jo);
        logger.debug("event as map: " + otro);
        epService.getEPRuntime().sendEvent(otro, "iotEvent");
        logger.debug("event was sent: " + otro);
    } catch (JSONException je) {
        logger.debug("error: " + je.getMessage());
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        out.printf("{\"error\":\"%s\"}\n", je.getMessage());

    } finally {
        out.close();
    }
}

From source file:es.tid.cep.esperanza.Rules.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from  w  ww.  j ava  2 s  .co  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, IOException {
    PrintWriter out = response.getWriter();
    response.setContentType("application/json;charset=UTF-8");
    try {
        ServletInputStream sis = request.getInputStream();
        byte[] b = new byte[request.getContentLength()];
        sis.read(b, 0, b.length);
        String expression = new String(b);
        logger.debug("rule text: ", expression);
        EPStatement statement = epService.getEPAdministrator().createEPL(expression);
        logger.debug("statement json: " + Utils.Statement2JSONObject(statement));
        statement.addListener(new GenericListener());
        out.println(Utils.Statement2JSONObject(statement));
    } catch (EPException epe) {
        logger.error("creating statement", epe);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        out.printf("{\"error\":%s}\n", JSONObject.valueToString(epe.getMessage()));
    } finally {
        out.close();
    }
}

From source file:org.vuphone.vandyupon.media.incoming.event.ImageParser.java

public Notification parse(HttpServletRequest req) {
    if (req.getParameter("type").equalsIgnoreCase("eventimagepost")) {
        //get data from request

        String response = null;/*  ww w . ja va2s. co  m*/
        String callback = null;
        long time, eventId = 0;
        time = System.currentTimeMillis();
        byte[] imageData = null;

        eventId = Long.parseLong(req.getParameter(EVENTID));

        response = req.getParameter("resp");
        callback = req.getParameter("callback");
        if (ServletFileUpload.isMultipartContent(req)) {
            //process the multipart request

            File temp = new File("/temp");
            if (!temp.exists()) {
                temp.mkdir();
            }

            DiskFileItemFactory factory = new DiskFileItemFactory(5000000, temp);

            ServletFileUpload ul = new ServletFileUpload(factory);
            Iterator iter = null;

            HashMap<String, String> params = new HashMap<String, String>();

            try {
                iter = ul.parseRequest(req).iterator();

                while (iter.hasNext()) {

                    FileItem item = (FileItem) iter.next();

                    if (item.isFormField())
                        params.put(item.getFieldName(), item.getString());
                    else
                        //file upload
                        imageData = item.get();
                }

            } catch (FileUploadException e) {
                e.printStackTrace();
                return null;
            }

        } else {

            eventId = Long.parseLong(req.getParameter(EVENTID));

            response = req.getParameter("resp");
            callback = req.getParameter("callback");
            imageData = new byte[req.getContentLength() + 1];
            try {
                ServletInputStream sis = req.getInputStream();
                int read = 0;
                int readSoFar = 0;
                while ((read = sis.read(imageData, readSoFar, imageData.length - readSoFar)) != -1) {
                    readSoFar += read;
                    //logger_.log(Level.SEVERE, "Read " + String.valueOf(read) + " bytes this time. So Far " + String.valueOf(readSoFar));
                }
            } catch (IOException excp) {
                logger_.log(Level.SEVERE, "Got IOException:" + excp.getMessage());
            }

        }
        ImageNotification in = new ImageNotification();
        in.setEventId(eventId);
        in.setTime(time);
        in.setBytes(imageData);
        in.setResponseType(response);
        in.setCallback(callback);
        return in;
    } else {
        return null;
    }
}

From source file:org.gcaldaemon.core.servlet.ServletListener.java

private final void processRequest(HttpServletRequest req, HttpServletResponse rsp, boolean getMethod)
        throws ServletException, IOException {
    try {//from  w w  w . j a va  2 s .  com

        // Transform HttpServletRequest to Request
        Request request = new Request();
        request.method = getMethod ? GET_METHOD : PUT_METHOD;

        // Transform URL
        request.url = req.getPathInfo();
        int i = request.url.indexOf('@');
        if (i != -1) {
            request.url = request.url.substring(0, i) + "%40" + request.url.substring(i + 1);
        }

        // Get the properties of the request
        HashMap properties = new HashMap();
        Enumeration names = req.getHeaderNames();
        String header;
        while (names.hasMoreElements()) {
            header = (String) names.nextElement();
            properties.put(formatString(header.toCharArray()), req.getHeader(header));
        }

        // Transform username and password
        header = (String) properties.get(AUTHORIZATION);
        if (header != null && header.startsWith(BASIC)) {
            header = StringUtils.decodeBASE64(header.substring(6));
            int n = header.indexOf(COLON);
            if (n != 0) {
                request.username = header.substring(0, n);
            }
            if (n != header.length() - 1) {
                request.password = header.substring(n + 1);
            }
        }

        // Get Content-Length header
        int contentLength = 0;
        header = (String) properties.get(CONTENT_LENGTH);
        if (header != null && header.length() != 0) {
            contentLength = Integer.parseInt(header);
        }

        // Read body
        if (contentLength != 0) {
            int packet, readed = 0;
            request.body = new byte[contentLength];
            ServletInputStream in = req.getInputStream();
            while (readed != contentLength) {
                packet = in.read(request.body, readed, contentLength - readed);
                if (packet == -1) {
                    throw new EOFException();
                }
                readed += packet;
            }
        }

        // Redirect request to superclass
        Response response;
        if (getMethod) {
            response = doGet(request);
        } else {
            response = doPut(request);
        }

        // Set response status
        rsp.setStatus(response.status);

        // Add unauthorized header and realm
        if (response.status == STATUS_UNAUTHORIZED) {
            String realm = null;
            int s, e = request.url.indexOf("%40");
            if (e != -1) {
                s = request.url.lastIndexOf('/', e);
                if (s != -1) {
                    realm = request.url.substring(s + 1, e).replace('.', ' ');
                }
            }
            if (realm == null) {
                s = request.url.indexOf("private");
                if (s != -1) {
                    e = request.url.indexOf('/', s + 7);
                    if (e != -1) {
                        realm = request.url.substring(s + 8, e);
                    }
                }
            }
            if (realm == null || realm.length() == 0) {
                realm = "Google Account";
            }
            rsp.addHeader("WWW-Authenticate", "Basic realm=\"" + realm + '\"');
        }

        // Write body
        ServletOutputStream out = null;
        try {
            out = rsp.getOutputStream();
            out.write(response.body);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (Exception ignored) {
                }
            }
        }

    } catch (Exception processingError) {
        throw new ServletException("Unable to process " + req.getMethod() + " request!", processingError);
    }
}

From source file:helma.servlet.AbstractServletClient.java

protected void parseParameters(HttpServletRequest request, RequestTrans reqtrans, String encoding)
        throws IOException {
    // check if there are any parameters before we get started
    String queryString = request.getQueryString();
    String contentType = request.getContentType();
    boolean isFormPost = "post".equals(request.getMethod().toLowerCase()) && contentType != null
            && contentType.toLowerCase().startsWith("application/x-www-form-urlencoded");

    if (queryString == null && !isFormPost) {
        return;/*from  ww  w .  j  a va 2  s. c o  m*/
    }

    HashMap parameters = new HashMap();

    // Parse any query string parameters from the request
    if (queryString != null) {
        parseParameters(parameters, queryString.getBytes(), encoding, false);
        if (!parameters.isEmpty()) {
            reqtrans.setParameters(parameters, false);
            parameters.clear();
        }
    }

    // Parse any posted parameters in the input stream
    if (isFormPost) {
        int max = request.getContentLength();
        if (max > totalUploadLimit * 1024) {
            throw new IOException("Exceeded Upload limit");
        }
        int len = 0;
        byte[] buf = new byte[max];
        ServletInputStream is = request.getInputStream();

        while (len < max) {
            int next = is.read(buf, len, max - len);

            if (next < 0) {
                break;
            }

            len += next;
        }

        // is.close();
        parseParameters(parameters, buf, encoding, true);
        if (!parameters.isEmpty()) {
            reqtrans.setParameters(parameters, true);
            parameters.clear();
        }
    }
}

From source file:axiom.servlet.AbstractServletClient.java

protected void parseParameters(HttpServletRequest request, RequestTrans reqtrans, String encoding)
        throws Exception {

    HashMap parameters = new HashMap();

    try {/*from   w ww.  j a v  a  2s .co  m*/
        Context cx = Context.enter();
        cx.setClassShutter(new ClassShutter() {
            public boolean visibleToScripts(String fullClassName) {
                return false;
            }
        });

        ImporterTopLevel scope = new ImporterTopLevel(cx, true);

        // Parse any posted parameters in the input stream
        String contentType;
        boolean isPost = false, isForm = false, isJson = false, isXml = false;
        if ("POST".equals(request.getMethod())) {
            isPost = true;
        }
        if (isPost && (contentType = request.getContentType()) != null) {
            contentType = contentType.split(";")[0];
            if ("application/x-www-form-urlencoded".equals(contentType)) {
                isForm = true;
            } else if ("text/json".equals(contentType)) {
                isJson = true;
            } else if ("text/xml".equals(contentType)) {
                isXml = true;
            }
        }

        // Parse any query string parameters from the request
        String queryString = request.getQueryString();
        if (queryString != null) {
            try {
                parseParameters(parameters, queryString.getBytes(), encoding, isPost);

                Scriptable sqparam = cx.newObject(scope);
                for (Iterator i = parameters.entrySet().iterator(); i.hasNext();) {
                    Map.Entry entry = (Map.Entry) i.next();
                    String key = (String) entry.getKey();
                    String[] values = (String[]) entry.getValue();

                    if ((values != null) && (values.length > 0)) {
                        if (values.length == 1) {
                            sqparam.put(key, sqparam, values[0]);
                        } else {
                            NativeArray na = new NativeArray(values);
                            ScriptRuntime.setObjectProtoAndParent(na, scope);
                            sqparam.put(key, sqparam, na);
                        }
                    }
                }
                reqtrans.setQueryParams(sqparam);
            } catch (Exception e) {
                System.err.println("Error parsing query string: " + e);
            }
        }

        if (isForm || isJson || isXml) {
            try {
                int max = request.getContentLength();
                int len = 0;
                byte[] buf = new byte[max];
                ServletInputStream is = request.getInputStream();

                while (len < max) {
                    int next = is.read(buf, len, max - len);

                    if (next < 0) {
                        break;
                    }

                    len += next;
                }

                if (isForm) {
                    HashMap formMap = new HashMap();
                    parseParameters(formMap, buf, encoding, isPost);
                    Scriptable spparam = cx.newObject(scope);
                    for (Iterator i = formMap.entrySet().iterator(); i.hasNext();) {
                        Map.Entry entry = (Map.Entry) i.next();
                        String key = (String) entry.getKey();
                        String[] values = (String[]) entry.getValue();
                        if (values.length > 0) {
                            if (values.length == 1) {
                                spparam.put(key, spparam, values[0]);
                            } else {
                                NativeArray na = new NativeArray(values);
                                ScriptRuntime.setObjectProtoAndParent(na, scope);
                                spparam.put(key, spparam, na);
                            }
                        }
                    }

                    reqtrans.setPostBody(new String(buf, encoding));
                    reqtrans.setPostParams(spparam);
                    parameters.putAll(formMap);
                } else if (isJson) {
                    String json = new String(buf, encoding);
                    Scriptable post = (Scriptable) cx.evaluateString(scope, "eval(" + json + ")", "", 0, null);
                    reqtrans.setPostBody(post);
                    Object[] ids = post.getIds();
                    int idslen = ids.length;
                    for (int i = 0; i < idslen; i++) {
                        parameters.put(ids[i], post.get((String) ids[i], post));
                    }
                } else if (isXml) {
                    String xml = new String(buf, encoding);
                    int startProlog = xml.indexOf("<?xml version="), endProlog;
                    if (startProlog > -1 && (endProlog = xml.indexOf(">", startProlog + 1)) > -1) {
                        xml = new StringBuffer(xml).replace(startProlog, endProlog + 1, "").toString();
                    }
                    xml = xml.replaceAll("\\\"", "\\\\\"").replaceAll("\n", "").replaceAll("\r", "");
                    Scriptable post = (Scriptable) cx.evaluateString(scope, "new XML(\"" + xml + "\");", "", 0,
                            null);
                    reqtrans.setPostBody(post);
                }
            } catch (Exception e) {
                throw e;
            }
        }

        Scriptable sreqdata = cx.newObject(scope);
        for (Iterator i = parameters.entrySet().iterator(); i.hasNext();) {
            Map.Entry entry = (Map.Entry) i.next();
            String key = (String) entry.getKey();
            Object val = entry.getValue();

            if (val != null) {
                if (val instanceof String[]) {
                    String[] values = (String[]) val;
                    if (values.length > 0) {
                        if (values.length == 1) {
                            sreqdata.put(key, sreqdata, values[0]);
                        } else {
                            NativeArray na = new NativeArray(values);
                            ScriptRuntime.setObjectProtoAndParent(na, scope);
                            sreqdata.put(key, sreqdata, na);
                        }
                    }
                } else {
                    sreqdata.put(key, sreqdata, val);
                }
            }

        }
        reqtrans.setData(sreqdata);

    } catch (Exception ex) {
        ex.printStackTrace();
        throw ex;
    } finally {
        Context.exit();
    }
}

From source file:com.jpeterson.littles3.StorageEngine.java

/**
 * Write/* www.j av a2  s .c  o m*/
 * 
 * @param req
 *            the HttpServletRequest object that contains the request the
 *            client made of the servlet
 * @param resp
 *            the HttpServletResponse object that contains the response the
 *            servlet returns to the client
 * @throws IOException
 *             if an input or output error occurs while the servlet is
 *             handling the PUT request
 * @throws ServletException
 *             if the request for the PUT cannot be handled
 */
@SuppressWarnings("unchecked")
public void methodPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    OutputStream out = null;

    try {
        S3ObjectRequest or;

        try {
            or = S3ObjectRequest.create(req, resolvedHost(),
                    (Authenticator) getWebApplicationContext().getBean(BEAN_AUTHENTICATOR));
        } catch (InvalidAccessKeyIdException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidAccessKeyId");
            return;
        } catch (InvalidSecurityException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidSecurity");
            return;
        } catch (RequestTimeTooSkewedException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "RequestTimeTooSkewed");
            return;
        } catch (SignatureDoesNotMatchException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "SignatureDoesNotMatch");
            return;
        } catch (AuthenticatorException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidSecurity");
            return;
        }
        logger.debug("S3ObjectRequest: " + or);

        CanonicalUser requestor = or.getRequestor();

        if (or.getKey() != null) {
            String value;
            long contentLength;
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            DigestOutputStream digestOutputStream = null;
            S3Object oldS3Object = null;
            S3Object s3Object;
            StorageService storageService;
            Bucket bucket;
            String bucketName = or.getBucket();
            String key = or.getKey();

            if (!isValidKey(key)) {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "KeyTooLong");
                return;
            }

            storageService = (StorageService) getWebApplicationContext().getBean(BEAN_STORAGE_SERVICE);

            if (req.getParameter(PARAMETER_ACL) != null) {
                // write access control policy
                Acp acp;
                CanonicalUser owner;
                s3Object = storageService.load(bucketName, key);

                if (s3Object == null) {
                    resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchKey");
                    return;
                }

                acp = s3Object.getAcp();
                try {
                    acp.canWrite(requestor);
                } catch (AccessControlException e) {
                    resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied");
                    return;
                }

                // save owner
                owner = acp.getOwner();

                try {
                    acp = Acp.decode(req.getInputStream());
                } catch (IOException e) {
                    e.printStackTrace();
                    resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "MalformedACLError");
                    return;
                }

                // maintain owner
                acp.setOwner(owner);

                s3Object.setAcp(acp);

                storageService.store(s3Object);
            } else {
                // make sure requestor can "WRITE" to the bucket
                try {
                    bucket = storageService.loadBucket(bucketName);
                    bucket.canWrite(requestor);
                } catch (AccessControlException e) {
                    resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied");
                    return;
                } catch (DataAccessException e) {
                    resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchBucket");
                    return;
                }

                try {
                    oldS3Object = storageService.load(bucket.getName(), key);
                } catch (DataRetrievalFailureException e) {
                    // ignore
                }

                // create a new S3Object for this request to store an object
                try {
                    s3Object = storageService.createS3Object(bucket, key, requestor);
                } catch (DataAccessException e) {
                    resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchBucket");
                    return;
                }

                out = s3Object.getOutputStream();
                digestOutputStream = new DigestOutputStream(out, messageDigest);

                // Used instead of req.getContentLength(); because Amazon
                // limit is 5 gig, which is bigger than an int
                value = req.getHeader("Content-Length");
                if (value == null) {
                    resp.sendError(HttpServletResponse.SC_LENGTH_REQUIRED, "MissingContentLength");
                    return;
                }
                contentLength = Long.valueOf(value).longValue();

                if (contentLength > 5368709120L) {
                    resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "EntityTooLarge");
                    return;
                }

                long written = 0;
                int count;
                byte[] b = new byte[4096];
                ServletInputStream in = req.getInputStream();

                while (((count = in.read(b, 0, b.length)) > 0) && (written < contentLength)) {
                    digestOutputStream.write(b, 0, count);
                    written += count;
                }
                digestOutputStream.flush();

                if (written != contentLength) {
                    // transmission truncated
                    if (out != null) {
                        out.close();
                        out = null;
                    }
                    if (digestOutputStream != null) {
                        digestOutputStream.close();
                        digestOutputStream = null;
                    }
                    // clean up
                    storageService.remove(s3Object);
                    resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "IncompleteBody");
                    return;
                }

                s3Object.setContentDisposition(req.getHeader("Content-Disposition"));
                s3Object.setContentLength(contentLength);
                s3Object.setContentMD5(req.getHeader("Content-MD5"));
                value = req.getContentType();
                logger.debug("Put - Content-Type: " + value);
                if (value == null) {
                    value = S3Object.DEFAULT_CONTENT_TYPE;
                }
                s3Object.setContentType(value);
                logger.debug("Put - get content-type: " + s3Object.getContentType());
                s3Object.setLastModified(System.currentTimeMillis());

                // metadata
                int prefixLength = HEADER_PREFIX_USER_META.length();
                String name;
                for (Enumeration headerNames = req.getHeaderNames(); headerNames.hasMoreElements();) {
                    String headerName = (String) headerNames.nextElement();
                    if (headerName.startsWith(HEADER_PREFIX_USER_META)) {
                        name = headerName.substring(prefixLength).toLowerCase();
                        for (Enumeration headers = req.getHeaders(headerName); headers.hasMoreElements();) {
                            value = (String) headers.nextElement();
                            s3Object.addMetadata(name, value);
                        }
                    }
                }

                // calculate ETag, hex encoding of MD5
                value = new String(Hex.encodeHex(digestOutputStream.getMessageDigest().digest()));
                resp.setHeader("ETag", value);
                s3Object.setETag(value);

                grantCannedAccessPolicies(req, s3Object.getAcp(), requestor);

                // NOTE: This could be reengineered to have a two-phase
                // commit.
                if (oldS3Object != null) {
                    storageService.remove(oldS3Object);
                }
                storageService.store(s3Object);
            }
        } else if (or.getBucket() != null) {
            StorageService storageService;
            Bucket bucket;

            storageService = (StorageService) getWebApplicationContext().getBean(BEAN_STORAGE_SERVICE);

            if (req.getParameter(PARAMETER_ACL) != null) {
                // write access control policy
                Acp acp;
                CanonicalUser owner;

                logger.debug("User is providing new ACP for bucket " + or.getBucket());

                try {
                    bucket = storageService.loadBucket(or.getBucket());
                } catch (DataAccessException e) {
                    resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchBucket");
                    return;
                }

                acp = bucket.getAcp();
                try {
                    acp.canWrite(requestor);
                } catch (AccessControlException e) {
                    resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied");
                    return;
                }

                // save owner
                owner = acp.getOwner();

                try {
                    acp = Acp.decode(req.getInputStream());
                } catch (IOException e) {
                    e.printStackTrace();
                    resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "MalformedACLError");
                    return;
                }

                // maintain owner
                acp.setOwner(owner);

                bucket.setAcp(acp);

                logger.debug("Saving bucket ACP");
                logger.debug("ACP: " + Acp.encode(bucket.getAcp()));

                storageService.storeBucket(bucket);
            } else {
                // validate bucket
                String bucketName = or.getBucket();

                if (!isValidBucketName(bucketName)) {
                    resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "InvalidBucketName");
                    return;
                }

                try {
                    bucket = storageService.createBucket(bucketName, requestor);
                } catch (BucketAlreadyExistsException e) {
                    resp.sendError(HttpServletResponse.SC_CONFLICT, "BucketAlreadyExists");
                    return;
                }

                grantCannedAccessPolicies(req, bucket.getAcp(), requestor);

                storageService.storeBucket(bucket);
            }
        }
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        logger.error("Unable to use MD5", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "InternalError");
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    } finally {
        if (out != null) {
            out.close();
            out = null;
        }
    }
}