Java Code Examples for io.netty.handler.codec.http.HttpResponseStatus#FORBIDDEN
The following examples show how to use
io.netty.handler.codec.http.HttpResponseStatus#FORBIDDEN .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ManagementRequestHandler.java From serve with Apache License 2.0 | 6 votes |
private void handleUnregisterModel( ChannelHandlerContext ctx, String modelName, String modelVersion) throws ModelNotFoundException, InternalServerException, RequestTimeoutException, ModelVersionNotFoundException { ModelManager modelManager = ModelManager.getInstance(); HttpResponseStatus httpResponseStatus = modelManager.unregisterModel(modelName, modelVersion); if (httpResponseStatus == HttpResponseStatus.NOT_FOUND) { throw new ModelNotFoundException("Model not found: " + modelName); } else if (httpResponseStatus == HttpResponseStatus.BAD_REQUEST) { throw new ModelVersionNotFoundException( String.format( "Model version: %s does not exist for model: %s", modelVersion, modelName)); } else if (httpResponseStatus == HttpResponseStatus.INTERNAL_SERVER_ERROR) { throw new InternalServerException("Interrupted while cleaning resources: " + modelName); } else if (httpResponseStatus == HttpResponseStatus.REQUEST_TIMEOUT) { throw new RequestTimeoutException("Timed out while cleaning resources: " + modelName); } else if (httpResponseStatus == HttpResponseStatus.FORBIDDEN) { throw new InvalidModelVersionException( "Cannot remove default version for model " + modelName); } String msg = "Model \"" + modelName + "\" unregistered"; NettyUtils.sendJsonResponse(ctx, new StatusResponse(msg)); }
Example 2
Source File: ManagementRequestHandler.java From serve with Apache License 2.0 | 6 votes |
private void setDefaultModelVersion( ChannelHandlerContext ctx, String modelName, String newModelVersion) throws ModelNotFoundException, InternalServerException, RequestTimeoutException, ModelVersionNotFoundException { ModelManager modelManager = ModelManager.getInstance(); HttpResponseStatus httpResponseStatus = modelManager.setDefaultVersion(modelName, newModelVersion); if (httpResponseStatus == HttpResponseStatus.NOT_FOUND) { throw new ModelNotFoundException("Model not found: " + modelName); } else if (httpResponseStatus == HttpResponseStatus.FORBIDDEN) { throw new ModelVersionNotFoundException( "Model version " + newModelVersion + " does not exist for model " + modelName); } String msg = "Default vesion succsesfully updated for model \"" + modelName + "\" to \"" + newModelVersion + "\""; SnapshotManager.getInstance().saveSnapshot(); NettyUtils.sendJsonResponse(ctx, new StatusResponse(msg)); }
Example 3
Source File: HttpUploadHandlerTest.java From bazel with Apache License 2.0 | 6 votes |
/** Test that the handler correctly supports http error codes i.e. 404 (NOT FOUND). */ @Test public void httpErrorsAreSupported() { EmbeddedChannel ch = new EmbeddedChannel(new HttpUploadHandler(null, ImmutableList.of())); ByteArrayInputStream data = new ByteArrayInputStream(new byte[] {1, 2, 3, 4, 5}); ChannelPromise writePromise = ch.newPromise(); ch.writeOneOutbound(new UploadCommand(CACHE_URI, true, "abcdef", data, 5), writePromise); HttpRequest request = ch.readOutbound(); assertThat(request).isInstanceOf(HttpRequest.class); HttpChunkedInput content = ch.readOutbound(); assertThat(content).isInstanceOf(HttpChunkedInput.class); FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN); response.headers().set(HttpHeaders.CONNECTION, HttpHeaderValues.CLOSE); ch.writeInbound(response); assertThat(writePromise.isDone()).isTrue(); assertThat(writePromise.cause()).isInstanceOf(HttpException.class); assertThat(((HttpException) writePromise.cause()).response().status()) .isEqualTo(HttpResponseStatus.FORBIDDEN); assertThat(ch.isOpen()).isFalse(); }
Example 4
Source File: ServerResponses.java From Kepler with GNU Lesser General Public License v3.0 | 6 votes |
@Override public FullHttpResponse getResponse(HttpResponseStatus status, WebConnection webConnection) { webConnection.session().set("page", ""); if (status == HttpResponseStatus.FORBIDDEN) { return ResponseBuilder.create(HttpResponseStatus.FORBIDDEN, "\n" + "<html>\n" + "<head>\n" + "</head>\n" + "<body>\n" + " <h1>Forbidden</h1>\n" + "<body>\n" + "</html>"); } if (status == HttpResponseStatus.NOT_FOUND) { TwigTemplate twigTemplate = new TwigTemplate(webConnection); twigTemplate.start("overrides/default"); return ResponseBuilder.create(HttpResponseStatus.NOT_FOUND, twigTemplate.renderHTML());//"\n" + "<html>\n" + "<head>\n" + "</head>\n" + "<body>\n" + " <h1>Not Found</h1>\n" + "<body>\n" + "</html>"); } //if (status == HttpResponseStatus.BAD_REQUEST) { return ResponseBuilder.create(HttpResponseStatus.BAD_REQUEST, "\n" + "<html>\n" + "<head>\n" + "</head>\n" + "<body>\n" + " <h1>Bad Request</h1>\n" + "<body>\n" + "</html>"); //} //return null; }
Example 5
Source File: AdminJsonService.java From glowroot with Apache License 2.0 | 6 votes |
@POST(path = "/backend/admin/analyze-h2-disk-space", permission = "") String analyzeH2DiskSpace(@BindAuthentication Authentication authentication) throws Exception { if (!offlineViewer && !authentication.isAdminPermitted("admin:edit:storage")) { throw new JsonServiceException(HttpResponseStatus.FORBIDDEN); } long h2DataFileSize = repoAdmin.getH2DataFileSize(); List<H2Table> tables = repoAdmin.analyzeH2DiskSpace(); StringBuilder sb = new StringBuilder(); JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb)); try { jg.writeStartObject(); jg.writeNumberField("h2DataFileSize", h2DataFileSize); jg.writeObjectField("tables", orderingByBytesDesc.sortedCopy(tables)); jg.writeEndObject(); } finally { jg.close(); } return sb.toString(); }
Example 6
Source File: ModelManager.java From serve with Apache License 2.0 | 6 votes |
public HttpResponseStatus setDefaultVersion(String modelName, String newModelVersion) throws ModelVersionNotFoundException { HttpResponseStatus httpResponseStatus = HttpResponseStatus.OK; ModelVersionedRefs vmodel = modelsNameMap.get(modelName); if (vmodel == null) { logger.warn("Model not found: " + modelName); return HttpResponseStatus.NOT_FOUND; } try { vmodel.setDefaultVersion(newModelVersion); } catch (ModelVersionNotFoundException e) { logger.warn("Model version {} does not exist for model {}", newModelVersion, modelName); httpResponseStatus = HttpResponseStatus.FORBIDDEN; } return httpResponseStatus; }
Example 7
Source File: AdminJsonService.java From glowroot with Apache License 2.0 | 5 votes |
@POST(path = "/backend/admin/compact-h2-data", permission = "") void compactH2Data(@BindAuthentication Authentication authentication) throws Exception { if (!offlineViewer && !authentication.isAdminPermitted("admin:edit:storage")) { throw new JsonServiceException(HttpResponseStatus.FORBIDDEN); } repoAdmin.compactH2Data(); }
Example 8
Source File: IncidentJsonService.java From glowroot with Apache License 2.0 | 5 votes |
@GET(path = "/backend/incidents", permission = "") String getIncidents(@BindAuthentication Authentication authentication) throws Exception { if (!central && !authentication.isPermitted(EMBEDDED_AGENT_ID, "agent:incident")) { throw new JsonServiceException(HttpResponseStatus.FORBIDDEN); } ImmutableIncidentResponse.Builder response = ImmutableIncidentResponse.builder(); // seems better to read all incidents and then filter by permission, instead of reading // individually for every agentRollupId that user has permission to read List<OpenIncident> openIncidents = new BySeverityOrdering().compound(new ByOpenTimeOrdering()) .sortedCopy(incidentRepository.readAllOpenIncidents()); for (OpenIncident openIncident : openIncidents) { if (authentication.isPermittedForAgentRollup(openIncident.agentRollupId(), "agent:incident")) { response.addOpenIncidents(createDisplayedIncident(openIncident)); } } List<ResolvedIncident> resolvedIncidents = incidentRepository .readResolvedIncidents(clock.currentTimeMillis() - DAYS.toMillis(30)); for (ResolvedIncident resolvedIncident : resolvedIncidents) { if (authentication.isPermittedForAgentRollup(resolvedIncident.agentRollupId(), "agent:incident")) { response.addResolvedIncidents(createDisplayedIncident(resolvedIncident)); } } return mapper.writeValueAsString(response.build()); }
Example 9
Source File: ReportJsonService.java From glowroot with Apache License 2.0 | 5 votes |
private static void checkPermissions(List<String> agentRollupIds, String permission, Authentication authentication) throws Exception { for (String agentRollupId : agentRollupIds) { if (!authentication.isPermittedForAgentRollup(agentRollupId, permission)) { throw new JsonServiceException(HttpResponseStatus.FORBIDDEN); } } }
Example 10
Source File: AdminJsonService.java From glowroot with Apache License 2.0 | 5 votes |
@POST(path = "/backend/admin/analyze-trace-counts", permission = "") String analyzeTraceCounts(@BindAuthentication Authentication authentication) throws Exception { if (!offlineViewer && !authentication.isAdminPermitted("admin:edit:storage")) { throw new JsonServiceException(HttpResponseStatus.FORBIDDEN); } return mapper.writeValueAsString(repoAdmin.analyzeTraceCounts()); }
Example 11
Source File: AdminJsonService.java From glowroot with Apache License 2.0 | 5 votes |
@POST(path = "/backend/admin/defrag-h2-data", permission = "") void defragH2Data(@BindAuthentication Authentication authentication) throws Exception { if (!offlineViewer && !authentication.isAdminPermitted("admin:edit:storage")) { throw new JsonServiceException(HttpResponseStatus.FORBIDDEN); } repoAdmin.defragH2Data(); }
Example 12
Source File: WebSocketServerProtocolHandler.java From netty4.0.27Learn with Apache License 2.0 | 5 votes |
static ChannelHandler forbiddenHttpRequestResponder() { return new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpRequest) { ((FullHttpRequest) msg).release(); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.FORBIDDEN); ctx.channel().writeAndFlush(response); } else { ctx.fireChannelRead(msg); } } }; }
Example 13
Source File: ProxyTunnelInitHandlerTest.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
@Test public void unsuccessfulResponse_failsPromise() { Promise<Channel> promise = GROUP.next().newPromise(); ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise); DefaultHttpResponse resp = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN); handler.channelRead(mockCtx, resp); assertThat(promise.awaitUninterruptibly().isSuccess()).isFalse(); }
Example 14
Source File: LProxy.java From k3pler with GNU General Public License v3.0 | 5 votes |
private HttpResponseStatus getResponseStatus(int ID){ switch (ID){ case 0: return HttpResponseStatus.BAD_GATEWAY; case 1: return HttpResponseStatus.BAD_REQUEST; case 2: return HttpResponseStatus.FORBIDDEN; case 3: return HttpResponseStatus.NOT_FOUND; default: return HttpResponseStatus.BAD_GATEWAY; } }
Example 15
Source File: WebSocketServerProtocolHandler.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
static ChannelHandler forbiddenHttpRequestResponder() { return new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpRequest) { ((FullHttpRequest) msg).release(); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.FORBIDDEN); ctx.channel().writeAndFlush(response); } else { ctx.fireChannelRead(msg); } } }; }
Example 16
Source File: NettyResponseChannel.java From ambry with Apache License 2.0 | 4 votes |
/** * Converts a {@link ResponseStatus} into a {@link HttpResponseStatus}. * @param responseStatus {@link ResponseStatus} that needs to be mapped to a {@link HttpResponseStatus}. * @return the {@link HttpResponseStatus} that maps to the {@link ResponseStatus}. */ private HttpResponseStatus getHttpResponseStatus(ResponseStatus responseStatus) { HttpResponseStatus status; switch (responseStatus) { case Ok: nettyMetrics.okCount.inc(); status = HttpResponseStatus.OK; break; case Created: nettyMetrics.createdCount.inc(); status = HttpResponseStatus.CREATED; break; case Accepted: nettyMetrics.acceptedCount.inc(); status = HttpResponseStatus.ACCEPTED; break; case PartialContent: nettyMetrics.partialContentCount.inc(); status = HttpResponseStatus.PARTIAL_CONTENT; break; case NotModified: nettyMetrics.notModifiedCount.inc(); status = HttpResponseStatus.NOT_MODIFIED; break; case BadRequest: nettyMetrics.badRequestCount.inc(); status = HttpResponseStatus.BAD_REQUEST; break; case Unauthorized: nettyMetrics.unauthorizedCount.inc(); status = HttpResponseStatus.UNAUTHORIZED; break; case NotFound: nettyMetrics.notFoundCount.inc(); status = HttpResponseStatus.NOT_FOUND; break; case Conflict: nettyMetrics.conflictCount.inc(); status = HttpResponseStatus.CONFLICT; break; case Gone: nettyMetrics.goneCount.inc(); status = HttpResponseStatus.GONE; break; case Forbidden: nettyMetrics.forbiddenCount.inc(); status = HttpResponseStatus.FORBIDDEN; break; case ProxyAuthenticationRequired: nettyMetrics.proxyAuthRequiredCount.inc(); status = HttpResponseStatus.PROXY_AUTHENTICATION_REQUIRED; break; case RangeNotSatisfiable: nettyMetrics.rangeNotSatisfiableCount.inc(); status = HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE; break; case TooManyRequests: nettyMetrics.tooManyRequests.inc(); status = HttpResponseStatus.TOO_MANY_REQUESTS; break; case RequestTooLarge: nettyMetrics.requestTooLargeCount.inc(); status = HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE; break; case InternalServerError: nettyMetrics.internalServerErrorCount.inc(); status = HttpResponseStatus.INTERNAL_SERVER_ERROR; break; case ServiceUnavailable: nettyMetrics.serviceUnavailableErrorCount.inc(); status = HttpResponseStatus.SERVICE_UNAVAILABLE; break; case InsufficientCapacity: nettyMetrics.insufficientCapacityErrorCount.inc(); status = HttpResponseStatus.INSUFFICIENT_STORAGE; break; case PreconditionFailed: nettyMetrics.preconditionFailedErrorCount.inc(); status = HttpResponseStatus.PRECONDITION_FAILED; break; case MethodNotAllowed: nettyMetrics.methodNotAllowedErrorCount.inc(); status = HttpResponseStatus.METHOD_NOT_ALLOWED; break; default: nettyMetrics.unknownResponseStatusCount.inc(); status = HttpResponseStatus.INTERNAL_SERVER_ERROR; break; } return status; }
Example 17
Source File: NettyResponseChannelTest.java From ambry with Apache License 2.0 | 4 votes |
/** * @param code the {@link RestServiceErrorCode} whose {@link HttpResponseStatus} equivalent is required. * @return the {@link HttpResponseStatus} equivalent of {@code code}. */ private HttpResponseStatus getExpectedHttpResponseStatus(RestServiceErrorCode code) { switch (code) { case RequestTooLarge: return HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE; case Conflict: return HttpResponseStatus.CONFLICT; case Deleted: return HttpResponseStatus.GONE; case NotFound: return HttpResponseStatus.NOT_FOUND; case BadRequest: case InvalidArgs: case InvalidAccount: case InvalidContainer: case InvalidRequestState: case MalformedRequest: case MissingArgs: case UnsupportedHttpMethod: return HttpResponseStatus.BAD_REQUEST; case ResourceDirty: case AccessDenied: return HttpResponseStatus.FORBIDDEN; case Unauthorized: return HttpResponseStatus.UNAUTHORIZED; case ResourceScanInProgress: return HttpResponseStatus.PROXY_AUTHENTICATION_REQUIRED; case RangeNotSatisfiable: return HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE; case ServiceUnavailable: return HttpResponseStatus.SERVICE_UNAVAILABLE; case TooManyRequests: return HttpResponseStatus.TOO_MANY_REQUESTS; case InsufficientCapacity: return HttpResponseStatus.INSUFFICIENT_STORAGE; case IdConverterServiceError: case InternalServerError: case RequestChannelClosed: case RequestResponseQueuingFailure: case UnsupportedRestMethod: return HttpResponseStatus.INTERNAL_SERVER_ERROR; case PreconditionFailed: return HttpResponseStatus.PRECONDITION_FAILED; case NotAllowed: return HttpResponseStatus.METHOD_NOT_ALLOWED; default: throw new IllegalArgumentException("Unrecognized RestServiceErrorCode - " + code); } }
Example 18
Source File: SQLExceptions.java From crate with Apache License 2.0 | 4 votes |
/** * Create a {@link SQLActionException} out of a {@link Throwable}. * If concrete {@link ElasticsearchException} is found, first transform it * to a {@link CrateException} */ public static SQLActionException createSQLActionException(Throwable e, Consumer<Throwable> maskSensitiveInformation) { // ideally this method would be a static factory method in SQLActionException, // but that would pull too many dependencies for the client if (e instanceof SQLActionException) { return (SQLActionException) e; } Throwable unwrappedError = SQLExceptions.unwrap(e); e = esToCrateException(unwrappedError); try { maskSensitiveInformation.accept(e); } catch (Exception mpe) { e = mpe; } int errorCode = 5000; HttpResponseStatus httpStatus = HttpResponseStatus.INTERNAL_SERVER_ERROR; if (e instanceof CrateException) { CrateException crateException = (CrateException) e; if (e instanceof ValidationException) { errorCode = 4000 + crateException.errorCode(); httpStatus = HttpResponseStatus.BAD_REQUEST; } else if (e instanceof UnauthorizedException) { errorCode = 4010 + crateException.errorCode(); httpStatus = HttpResponseStatus.UNAUTHORIZED; } else if (e instanceof ReadOnlyException) { errorCode = 4030 + crateException.errorCode(); httpStatus = HttpResponseStatus.FORBIDDEN; } else if (e instanceof ResourceUnknownException) { errorCode = 4040 + crateException.errorCode(); httpStatus = HttpResponseStatus.NOT_FOUND; } else if (e instanceof ConflictException) { errorCode = 4090 + crateException.errorCode(); httpStatus = HttpResponseStatus.CONFLICT; } else if (e instanceof UnhandledServerException) { errorCode = 5000 + crateException.errorCode(); } } else if (e instanceof ParsingException) { errorCode = 4000; httpStatus = HttpResponseStatus.BAD_REQUEST; } else if (e instanceof MapperParsingException) { errorCode = 4000; httpStatus = HttpResponseStatus.BAD_REQUEST; } String message = e.getMessage(); if (message == null) { if (e instanceof CrateException && e.getCause() != null) { e = e.getCause(); // use cause because it contains a more meaningful error in most cases } StackTraceElement[] stackTraceElements = e.getStackTrace(); if (stackTraceElements.length > 0) { message = String.format(Locale.ENGLISH, "%s in %s", e.getClass().getSimpleName(), stackTraceElements[0]); } else { message = "Error in " + e.getClass().getSimpleName(); } } else { message = e.getClass().getSimpleName() + ": " + message; } StackTraceElement[] usefulStacktrace = e instanceof MissingPrivilegeException ? e.getStackTrace() : unwrappedError.getStackTrace(); return new SQLActionException(message, errorCode, httpStatus, usefulStacktrace); }
Example 19
Source File: StaticSite.java From crate with Apache License 2.0 | 4 votes |
public static FullHttpResponse serveSite(Path siteDirectory, FullHttpRequest request, ByteBufAllocator alloc) throws IOException { if (request.method() != HttpMethod.GET) { return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN); } String sitePath = request.uri(); while (sitePath.length() > 0 && sitePath.charAt(0) == '/') { sitePath = sitePath.substring(1); } // we default to index.html, or what the plugin provides (as a unix-style path) // this is a relative path under _site configured by the plugin. if (sitePath.length() == 0) { sitePath = "index.html"; } final String separator = siteDirectory.getFileSystem().getSeparator(); // Convert file separators. sitePath = sitePath.replace("/", separator); Path file = siteDirectory.resolve(sitePath); // return not found instead of forbidden to prevent malicious requests to find out if files exist or don't exist if (!Files.exists(file) || FileSystemUtils.isHidden(file) || !file.toAbsolutePath().normalize().startsWith(siteDirectory.toAbsolutePath().normalize())) { return Responses.contentResponse( HttpResponseStatus.NOT_FOUND, alloc, "Requested file [" + file + "] was not found"); } BasicFileAttributes attributes = readAttributes(file, BasicFileAttributes.class); if (!attributes.isRegularFile()) { // If it's not a regular file, we send a 403 final String msg = "Requested file [" + file + "] is not a valid file."; return Responses.contentResponse(HttpResponseStatus.NOT_FOUND, alloc, msg); } try { byte[] data = Files.readAllBytes(file); var resp = Responses.contentResponse(HttpResponseStatus.OK, alloc, data); resp.headers().set(HttpHeaderNames.CONTENT_TYPE, guessMimeType(file.toAbsolutePath().toString())); return resp; } catch (IOException e) { return Responses.contentResponse(HttpResponseStatus.INTERNAL_SERVER_ERROR, alloc, e.getMessage()); } }