List of usage examples for java.net HttpURLConnection HTTP_ENTITY_TOO_LARGE
int HTTP_ENTITY_TOO_LARGE
To view the source code for java.net HttpURLConnection HTTP_ENTITY_TOO_LARGE.
Click Source Link
From source file:org.hyperic.hq.plugin.netservices.HTTPCollector.java
private double getAvail(int code) { // There are too many options to list everything that is // successful. So, instead we are going to call out the // things that should be considered failure, everything else // is OK./*w w w .j av a 2s. c o m*/ switch (code) { case HttpURLConnection.HTTP_BAD_REQUEST: case HttpURLConnection.HTTP_FORBIDDEN: case HttpURLConnection.HTTP_NOT_FOUND: case HttpURLConnection.HTTP_BAD_METHOD: case HttpURLConnection.HTTP_CLIENT_TIMEOUT: case HttpURLConnection.HTTP_CONFLICT: case HttpURLConnection.HTTP_PRECON_FAILED: case HttpURLConnection.HTTP_ENTITY_TOO_LARGE: case HttpURLConnection.HTTP_REQ_TOO_LONG: case HttpURLConnection.HTTP_INTERNAL_ERROR: case HttpURLConnection.HTTP_NOT_IMPLEMENTED: case HttpURLConnection.HTTP_UNAVAILABLE: case HttpURLConnection.HTTP_VERSION: case HttpURLConnection.HTTP_BAD_GATEWAY: case HttpURLConnection.HTTP_GATEWAY_TIMEOUT: return Metric.AVAIL_DOWN; default: } if (hasCredentials()) { if (code == HttpURLConnection.HTTP_UNAUTHORIZED) { return Metric.AVAIL_DOWN; } } return Metric.AVAIL_UP; }
From source file:org.bonitasoft.console.common.server.servlet.FileUploadServlet.java
@Override @SuppressWarnings("unchecked") public void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException { defineUploadDirectoryPath(request);/*from w ww . j ava2s . c o m*/ response.setContentType("text/plain;charset=UTF-8"); PrintWriter responsePW = null; try { if (!ServletFileUpload.isMultipartContent(request)) { return; } final File targetDirectory = new File(uploadDirectoryPath); if (!targetDirectory.exists()) { targetDirectory.mkdirs(); } responsePW = response.getWriter(); final FileItemFactory fileItemFactory = new DiskFileItemFactory(); final ServletFileUpload serviceFileUpload = createServletFileUpload(fileItemFactory); final List<FileItem> items = serviceFileUpload.parseRequest(request); for (final FileItem item : items) { if (item.isFormField()) { continue; } final String fileName = item.getName(); if (checkUploadedFileSize) { checkUploadSize(request, item); } // Check if extension is allowed if (!isSupportedExtention(fileName)) { outputMediaTypeError(response, responsePW); return; } // Make unique file name final File uploadedFile = makeUniqueFilename(targetDirectory, fileName); // Upload file item.write(uploadedFile); if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "File uploaded : " + uploadedFile.getPath()); } uploadedFile.deleteOnExit(); // Response final String responseString; if (JSON_CONTENT_TYPE.equals(responseContentType)) { responseString = generateResponseJson(request, fileName, uploadedFile); } else if (TEXT_CONTENT_TYPE.equals(responseContentType)) { responseString = generateResponseString(request, fileName, uploadedFile); } else { throw new ServletException( "Unsupported content type in servlet configuration : " + responseContentType); } responsePW.print(responseString); responsePW.flush(); } } catch (final FileTooBigException e) { LOGGER.log(Level.SEVERE, "File is Too Big", e); response.setStatus(HttpURLConnection.HTTP_ENTITY_TOO_LARGE); if (JSON_CONTENT_TYPE.equals(responseContentType)) { final Map<String, Serializable> errorResponse = new HashMap<>(); errorResponse.put("type", "EntityTooLarge"); errorResponse.put("message", e.getFileName() + " is too large, limit is set to " + e.getMaxSize() + "Mb"); errorResponse.put("statusCode", HttpURLConnection.HTTP_ENTITY_TOO_LARGE); responsePW.print(new JSONObject(errorResponse).toString()); responsePW.flush(); } } catch (final Exception e) { final String theErrorMessage = "Exception while uploading file."; if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, theErrorMessage, e); } throw new ServletException(theErrorMessage, e); } }
From source file:org.languagetool.server.LanguageToolHttpHandler.java
@Override public void handle(HttpExchange httpExchange) throws IOException { long startTime = System.currentTimeMillis(); String remoteAddress = null;// w w w. ja v a 2s.c o m Map<String, String> parameters = new HashMap<>(); int reqId = reqCounter.incrementRequestCount(); ServerMetricsCollector.getInstance().logRequest(); boolean incrementHandleCount = false; try { URI requestedUri = httpExchange.getRequestURI(); if (requestedUri.getRawPath().startsWith("/v2/")) { // healthcheck should come before other limit checks (requests per time etc.), to be sure it works: String pathWithoutVersion = requestedUri.getRawPath().substring("/v2/".length()); if (pathWithoutVersion.equals("healthcheck")) { if (workQueueFull(httpExchange, parameters, "Healthcheck failed: There are currently too many parallel requests.")) { ServerMetricsCollector.getInstance().logFailedHealthcheck(); return; } else { String ok = "OK"; httpExchange.getResponseHeaders().set("Content-Type", "text/plain"); httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, ok.getBytes(ENCODING).length); httpExchange.getResponseBody().write(ok.getBytes(ENCODING)); ServerMetricsCollector.getInstance().logResponse(HttpURLConnection.HTTP_OK); return; } } } String referrer = httpExchange.getRequestHeaders().getFirst("Referer"); String origin = httpExchange.getRequestHeaders().getFirst("Origin"); // Referer can be turned off with meta tags, so also check this for (String ref : config.getBlockedReferrers()) { String errorMessage = null; if (ref != null && !ref.isEmpty()) { if (referrer != null && siteMatches(referrer, ref)) { errorMessage = "Error: Access with referrer " + referrer + " denied."; } else if (origin != null && siteMatches(origin, ref)) { errorMessage = "Error: Access with origin " + origin + " denied."; } } if (errorMessage != null) { sendError(httpExchange, HttpURLConnection.HTTP_FORBIDDEN, errorMessage); logError(errorMessage, HttpURLConnection.HTTP_FORBIDDEN, parameters, httpExchange); ServerMetricsCollector.getInstance().logResponse(HttpURLConnection.HTTP_FORBIDDEN); return; } } String origAddress = httpExchange.getRemoteAddress().getAddress().getHostAddress(); String realAddressOrNull = getRealRemoteAddressOrNull(httpExchange); remoteAddress = realAddressOrNull != null ? realAddressOrNull : origAddress; reqCounter.incrementHandleCount(remoteAddress, reqId); incrementHandleCount = true; // According to the Javadoc, "Closing an exchange without consuming all of the request body is // not an error but may make the underlying TCP connection unusable for following exchanges.", // so we consume the request now, even before checking for request limits: parameters = getRequestQuery(httpExchange, requestedUri); if (requestLimiter != null) { try { requestLimiter.checkAccess(remoteAddress, parameters, httpExchange.getRequestHeaders()); } catch (TooManyRequestsException e) { String errorMessage = "Error: Access from " + remoteAddress + " denied: " + e.getMessage(); int code = HttpURLConnection.HTTP_FORBIDDEN; sendError(httpExchange, code, errorMessage); // already logged vai DatabaseAccessLimitLogEntry logError(errorMessage, code, parameters, httpExchange, false); return; } } if (errorRequestLimiter != null && !errorRequestLimiter.wouldAccessBeOkay(remoteAddress, parameters, httpExchange.getRequestHeaders())) { String textSizeMessage = getTextOrDataSizeMessage(parameters); String errorMessage = "Error: Access from " + remoteAddress + " denied - too many recent timeouts. " + textSizeMessage + " Allowed maximum timeouts: " + errorRequestLimiter.getRequestLimit() + " per " + errorRequestLimiter.getRequestLimitPeriodInSeconds() + " seconds"; int code = HttpURLConnection.HTTP_FORBIDDEN; sendError(httpExchange, code, errorMessage); logError(errorMessage, code, parameters, httpExchange); return; } if (workQueueFull(httpExchange, parameters, "Error: There are currently too many parallel requests. Please try again later.")) { ServerMetricsCollector.getInstance() .logRequestError(ServerMetricsCollector.RequestErrorType.QUEUE_FULL); return; } if (allowedIps == null || allowedIps.contains(origAddress)) { if (requestedUri.getRawPath().startsWith("/v2/")) { ApiV2 apiV2 = new ApiV2(textCheckerV2, config.getAllowOriginUrl()); String pathWithoutVersion = requestedUri.getRawPath().substring("/v2/".length()); apiV2.handleRequest(pathWithoutVersion, httpExchange, parameters, errorRequestLimiter, remoteAddress, config); } else if (requestedUri.getRawPath().endsWith("/Languages")) { throw new IllegalArgumentException( "You're using an old version of our API that's not supported anymore. Please see https://languagetool.org/http-api/migration.php"); } else if (requestedUri.getRawPath().equals("/")) { throw new IllegalArgumentException( "Missing arguments for LanguageTool API. Please see " + API_DOC_URL); } else if (requestedUri.getRawPath().contains("/v2/")) { throw new IllegalArgumentException( "You have '/v2/' in your path, but not at the root. Try an URL like 'http://server/v2/...' "); } else if (requestedUri.getRawPath().equals("/favicon.ico")) { sendError(httpExchange, HttpURLConnection.HTTP_NOT_FOUND, "Not found"); } else { throw new IllegalArgumentException( "This is the LanguageTool API. You have not specified any parameters. Please see " + API_DOC_URL); } } else { String errorMessage = "Error: Access from " + StringTools.escapeXML(origAddress) + " denied"; sendError(httpExchange, HttpURLConnection.HTTP_FORBIDDEN, errorMessage); throw new RuntimeException(errorMessage); } } catch (Exception e) { String response; int errorCode; boolean textLoggingAllowed = false; boolean logStacktrace = true; Throwable rootCause = ExceptionUtils.getRootCause(e); if (e instanceof TextTooLongException || rootCause instanceof TextTooLongException) { errorCode = HttpURLConnection.HTTP_ENTITY_TOO_LARGE; response = e.getMessage(); logStacktrace = false; } else if (e instanceof ErrorRateTooHighException || rootCause instanceof ErrorRateTooHighException) { errorCode = HttpURLConnection.HTTP_BAD_REQUEST; response = ExceptionUtils.getRootCause(e).getMessage(); logStacktrace = false; } else if (hasCause(e, AuthException.class)) { errorCode = HttpURLConnection.HTTP_FORBIDDEN; response = e.getMessage(); logStacktrace = false; } else if (e instanceof IllegalArgumentException || rootCause instanceof IllegalArgumentException) { errorCode = HttpURLConnection.HTTP_BAD_REQUEST; response = e.getMessage(); } else if (e instanceof PathNotFoundException || rootCause instanceof PathNotFoundException) { errorCode = HttpURLConnection.HTTP_NOT_FOUND; response = e.getMessage(); } else if (e instanceof TimeoutException || rootCause instanceof TimeoutException) { errorCode = HttpURLConnection.HTTP_INTERNAL_ERROR; response = "Checking took longer than " + config.getMaxCheckTimeMillis() / 1000.0f + " seconds, which is this server's limit. " + "Please make sure you have selected the proper language or consider submitting a shorter text."; } else { response = "Internal Error: " + e.getMessage(); errorCode = HttpURLConnection.HTTP_INTERNAL_ERROR; textLoggingAllowed = true; } long endTime = System.currentTimeMillis(); logError(remoteAddress, e, errorCode, httpExchange, parameters, textLoggingAllowed, logStacktrace, endTime - startTime); sendError(httpExchange, errorCode, "Error: " + response); } finally { httpExchange.close(); if (incrementHandleCount) { reqCounter.decrementHandleCount(reqId); } } }