io.netty.handler.codec.http.HttpResponseStatus # FORBIDDEN 源码实例Demo

下面列出了 io.netty.handler.codec.http.HttpResponseStatus # FORBIDDEN 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: serve   文件: ModelManager.java

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;
}
 
源代码2 项目: serve   文件: ManagementRequestHandler.java

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));
}
 
源代码3 项目: serve   文件: ManagementRequestHandler.java

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));
}
 
源代码4 项目: Kepler   文件: ServerResponses.java

@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;
}
 
源代码5 项目: glowroot   文件: AdminJsonService.java

@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();
}
 
源代码6 项目: bazel   文件: HttpUploadHandlerTest.java

/** 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();
}
 

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);
            }
        }
    };
}
 
源代码8 项目: k3pler   文件: LProxy.java

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;
    }
}
 

@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();
}
 

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);
            }
        }
    };
}
 
源代码11 项目: glowroot   文件: AdminJsonService.java

@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();
}
 
源代码12 项目: glowroot   文件: AdminJsonService.java

@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();
}
 
源代码13 项目: glowroot   文件: AdminJsonService.java

@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());
}
 
源代码14 项目: glowroot   文件: ReportJsonService.java

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);
        }
    }
}
 
源代码15 项目: glowroot   文件: IncidentJsonService.java

@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());
}
 
源代码16 项目: ambry   文件: NettyResponseChannel.java

/**
 * 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;
}
 
源代码17 项目: ambry   文件: NettyResponseChannelTest.java

/**
 * @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);
  }
}
 
源代码18 项目: crate   文件: SQLExceptions.java

/**
 * 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);
}
 
源代码19 项目: crate   文件: StaticSite.java

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());
    }
}