List of usage examples for javax.servlet.http HttpServletResponse SC_LENGTH_REQUIRED
int SC_LENGTH_REQUIRED
To view the source code for javax.servlet.http HttpServletResponse SC_LENGTH_REQUIRED.
Click Source Link
Content-Length
. From source file:com.netscape.cms.servlet.connector.ConnectorServlet.java
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean running_state = CMS.isInRunningState(); if (!running_state) throw new IOException("CMS server is not ready to serve."); HttpServletRequest req = request;/*from ww w. jav a 2 s .co m*/ HttpServletResponse resp = response; CMSRequest cmsRequest = newCMSRequest(); // set argblock cmsRequest.setHttpParams(CMS.createArgBlock(toHashtable(request))); // set http request cmsRequest.setHttpReq(request); // set http response cmsRequest.setHttpResp(response); // set servlet config. cmsRequest.setServletConfig(mConfig); // set servlet context. cmsRequest.setServletContext(mConfig.getServletContext()); char[] content = null; String encodedreq = null; String method = null; int len = -1; IPKIMessage msg = null; IPKIMessage replymsg = null; // NOTE must read all bufer before redoing handshake for // ssl client auth for client auth to work. // get request method method = req.getMethod(); // get content length len = request.getContentLength(); // get content, a base 64 encoded serialized request. if (len > 0) { InputStream in = request.getInputStream(); InputStreamReader inreader = new InputStreamReader(in, "UTF8"); BufferedReader reader = new BufferedReader(inreader, len); content = new char[len]; int done = reader.read(content, 0, len); int total = done; while (done >= 0 && total < len) { done = reader.read(content, total, len - total); total += done; } reader.close(); encodedreq = new String(content); } // force client auth handshake, validate RA and get RA's Id. // NOTE must do this after all contents are read for ssl // redohandshake to work X509Certificate peerCert; try { peerCert = getPeerCert(req); } catch (EBaseException e) { mAuthority.log(ILogger.LL_SECURITY, CMS.getLogMessage("CMSGW_HAS_NO_CLIENT_CERT")); resp.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } if (peerCert == null) { // XXX log something here. resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } // authenticate RA String RA_Id = null; String raUserId = null; IAuthToken token = null; try { token = authenticate(request); raUserId = token.getInString("userid"); RA_Id = peerCert.getSubjectDN().toString(); } catch (EInvalidCredentials e) { // already logged. resp.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } catch (EBaseException e) { // already logged. resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } mAuthority.log(ILogger.LL_INFO, "Remote Authority authenticated: " + peerCert.getSubjectDN()); // authorize AuthzToken authzToken = null; try { authzToken = authorize(mAclMethod, token, mAuthzResourceName, "submit"); } catch (Exception e) { // do nothing for now } if (authzToken == null) { cmsRequest.setStatus(ICMSRequest.UNAUTHORIZED); return; } // after cert validated, check http request. if (!method.equalsIgnoreCase("POST")) { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } if (len <= 0) { resp.sendError(HttpServletResponse.SC_LENGTH_REQUIRED); return; } // now process request. CMS.debug("ConnectorServlet: process request RA_Id=" + RA_Id); try { // decode request. msg = (IPKIMessage) mReqEncoder.decode(encodedreq); // process request replymsg = processRequest(RA_Id, raUserId, msg, token); } catch (IOException e) { CMS.debug("ConnectorServlet: service " + e.toString()); CMS.debug(e); mAuthority.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_IO_ERROR_REMOTE_REQUEST", e.toString())); resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } catch (EBaseException e) { CMS.debug("ConnectorServlet: service " + e.toString()); CMS.debug(e); mAuthority.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_IO_ERROR_REMOTE_REQUEST", e.toString())); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } catch (Exception e) { CMS.debug("ConnectorServlet: service " + e.toString()); CMS.debug(e); } CMS.debug("ConnectorServlet: done processRequest"); // encode reply try { String encodedrep = mReqEncoder.encode(replymsg); resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType("text/html"); resp.setContentLength(encodedrep.length()); // send reply OutputStream out = response.getOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(out, "UTF8"); writer.write(encodedrep); writer.flush(); writer.close(); out.flush(); } catch (Exception e) { CMS.debug("ConnectorServlet: error writing e=" + e.toString()); } CMS.debug("ConnectorServlet: send response RA_Id=" + RA_Id); }
From source file:com.jpeterson.littles3.StorageEngine.java
/** * Write/*from w w w . j a va2s . 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; } } }
From source file:org.osaf.cosmo.cmp.CmpServlet.java
private boolean checkPutPreconditions(HttpServletRequest req, HttpServletResponse resp) { if (req.getContentLength() <= 0) { resp.setStatus(HttpServletResponse.SC_LENGTH_REQUIRED); return false; }/*from ww w . j a v a 2s .c o m*/ if (req.getContentType() == null || !req.getContentType().startsWith("text/xml")) { resp.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); return false; } if (req.getHeader("Content-Transfer-Encoding") != null || req.getHeader("Content-Encoding") != null || req.getHeader("Content-Base") != null || req.getHeader("Content-Location") != null || req.getHeader("Content-MD5") != null || req.getHeader("Content-Range") != null) { resp.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED); return false; } return true; }
From source file:org.osaf.cosmo.mc.MorseCodeServlet.java
private boolean checkWritePreconditions(HttpServletRequest req, HttpServletResponse resp) { if (req.getContentLength() <= 0) { resp.setStatus(HttpServletResponse.SC_LENGTH_REQUIRED); return false; }/*from w w w . j ava 2 s . c o m*/ if (req.getContentType() == null || !req.getContentType().startsWith(MEDIA_TYPE_EIMML)) { resp.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); return false; } if (req.getHeader("Content-Transfer-Encoding") != null || req.getHeader("Content-Encoding") != null || req.getHeader("Content-Base") != null || req.getHeader("Content-Location") != null || req.getHeader("Content-MD5") != null || req.getHeader("Content-Range") != null) { resp.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED); return false; } return true; }
From source file:org.springframework.integration.http.DefaultInboundRequestMapper.java
private byte[] createPayloadFromInputStream(HttpServletRequest request) throws Exception { InputStream stream = request.getInputStream(); int length = request.getContentLength(); if (length == -1) { throw new ResponseStatusCodeException(HttpServletResponse.SC_LENGTH_REQUIRED); }/* w w w. j a v a2 s. c o m*/ if (logger.isDebugEnabled()) { logger.debug("received " + request.getMethod() + " request, " + "creating byte array payload with content lenth: " + length); } byte[] bytes = new byte[length]; stream.read(bytes, 0, length); return bytes; }