Java Code Examples for io.netty.handler.codec.http.HttpResponseStatus#NOT_FOUND

The following examples show how to use io.netty.handler.codec.http.HttpResponseStatus#NOT_FOUND . 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 vote down vote up
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 vote down vote up
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: ServerResponses.java    From Kepler with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 4
Source File: JsonServiceExceptionTest.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    // given
    JsonServiceException exception = new JsonServiceException(HttpResponseStatus.NOT_FOUND);
    // then
    assertThat(exception.getStatus()).isEqualTo(HttpResponseStatus.NOT_FOUND);
}
 
Example 5
Source File: AlertConfigJsonService.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@GET(path = "/backend/config/alerts", permission = "agent:config:view:alert")
String getAlert(@BindAgentRollupId String agentRollupId,
        @BindRequest AlertConfigRequest request) throws Exception {
    Optional<String> version = request.version();
    if (version.isPresent()) {
        AlertConfig alertConfig = configRepository.getAlertConfig(agentRollupId, version.get());
        if (alertConfig == null) {
            throw new JsonServiceException(HttpResponseStatus.NOT_FOUND);
        }
        return getAlertResponse(agentRollupId, alertConfig);
    } else {
        return getAlertList(agentRollupId);
    }
}
 
Example 6
Source File: HttpDownloadHandlerTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Test that the handler correctly supports http error codes i.e. 404 (NOT FOUND) with a
 * Content-Length header.
 */
@Test
public void httpErrorsWithContentAreSupported() throws IOException {
  EmbeddedChannel ch = new EmbeddedChannel(new HttpDownloadHandler(null, ImmutableList.of()));
  ByteArrayOutputStream out = Mockito.spy(new ByteArrayOutputStream());
  DownloadCommand cmd = new DownloadCommand(CACHE_URI, true, DIGEST, out);
  ChannelPromise writePromise = ch.newPromise();
  ch.writeOneOutbound(cmd, writePromise);

  HttpResponse response =
      new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);
  ByteBuf errorMessage = ByteBufUtil.writeAscii(ch.alloc(), "Error message");
  response.headers().set(HttpHeaders.HOST, "localhost");
  response
      .headers()
      .set(HttpHeaders.CONTENT_LENGTH, String.valueOf(errorMessage.readableBytes()));
  response.headers().set(HttpHeaders.CONNECTION, HttpHeaderValues.CLOSE);

  ch.writeInbound(response);
  // The promise must not be done because we haven't received the error message yet.
  assertThat(writePromise.isDone()).isFalse();

  ch.writeInbound(new DefaultHttpContent(errorMessage));
  ch.writeInbound(LastHttpContent.EMPTY_LAST_CONTENT);
  assertThat(writePromise.isDone()).isTrue();
  assertThat(writePromise.cause()).isInstanceOf(HttpException.class);
  assertThat(((HttpException) writePromise.cause()).response().status())
      .isEqualTo(HttpResponseStatus.NOT_FOUND);
  // No data should have been written to the OutputStream and it should have been closed.
  assertThat(out.size()).isEqualTo(0);
  // The caller is responsible for closing the stream.
  verify(out, never()).close();
  assertThat(ch.isOpen()).isFalse();
}
 
Example 7
Source File: UserConfigJsonService.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private String getUserConfigInternal(String username) throws Exception {
    UserConfig userConfig = configRepository.getUserConfig(username);
    if (userConfig == null) {
        throw new JsonServiceException(HttpResponseStatus.NOT_FOUND);
    }
    return mapper.writeValueAsString(ImmutableUserConfigResponse.builder()
            .config(UserConfigDto.create(userConfig))
            .allRoles(getAllRoleNamesInternal())
            .ldapAvailable(!configRepository.getLdapConfig().host().isEmpty())
            .build());
}
 
Example 8
Source File: ManagementRequestHandler.java    From multi-model-server with Apache License 2.0 5 votes vote down vote up
private void handleUnregisterModel(ChannelHandlerContext ctx, String modelName)
        throws ModelNotFoundException, InternalServerException, RequestTimeoutException {
    ModelManager modelManager = ModelManager.getInstance();
    HttpResponseStatus httpResponseStatus = modelManager.unregisterModel(modelName);
    if (httpResponseStatus == HttpResponseStatus.NOT_FOUND) {
        throw new ModelNotFoundException("Model not found: " + 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);
    }
    String msg = "Model \"" + modelName + "\" unregistered";
    NettyUtils.sendJsonResponse(ctx, new StatusResponse(msg));
}
 
Example 9
Source File: MesosClientTest.java    From mesos-rxjava with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetUriFromRedirectResponse_404() throws Exception {
    final URI mesosUri = URI.create("http://127.1.0.1:5050/api/v1/scheduler");
    final DefaultHttpResponse nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);
    final HttpClientResponse<ByteBuf> response = new HttpClientResponse<>(
        nettyResponse,
        UnicastContentSubject.create(1000, TimeUnit.MILLISECONDS)
    );
    final URI uri = MesosClient.getUriFromRedirectResponse(mesosUri, response);
    assertThat(uri).isEqualTo(URI.create("http://127.1.0.1:5050/api/v1/scheduler"));
}
 
Example 10
Source File: RoleConfigJsonService.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private String getRoleConfigInternal(String name) throws Exception {
    RoleConfig roleConfig = configRepository.getRoleConfig(name);
    if (roleConfig == null) {
        throw new JsonServiceException(HttpResponseStatus.NOT_FOUND);
    }
    ImmutableRoleConfigResponse.Builder response = ImmutableRoleConfigResponse.builder()
            .config(RoleConfigDto.create(roleConfig, central));
    if (central) {
        response.allActiveAgentRollups(getFlattenedAgentRollups());
    }
    return mapper.writeValueAsString(response.build());
}
 
Example 11
Source File: GetInvoiceRESTHandler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private FullHttpResponse extractInvoice(Invoices invoices, String invoiceNumber, BilleeInfo billeeInfo) throws HttpException {
   Iterator<Invoice> it = invoices.iterator();
   while (it.hasNext()) {
      Invoice invoice = it.next();
      if (invoice.getInvoiceNumber().equals(invoiceNumber)) {
         return createInvoice(invoice, billeeInfo);
      }
   }
   throw new HttpException(HttpResponseStatus.NOT_FOUND, "No invoice with number " + invoiceNumber + " exists");
}
 
Example 12
Source File: GatewayNoRouteException.java    From api-gateway-core with Apache License 2.0 4 votes vote down vote up
public GatewayNoRouteException() {
    super(HttpResponseStatus.NOT_FOUND, "no route found");
}
 
Example 13
Source File: NettyResponseChannelTest.java    From ambry with Apache License 2.0 4 votes vote down vote up
/**
 * @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 14
Source File: SQLExceptions.java    From crate with Apache License 2.0 4 votes vote down vote up
/**
 * 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 15
Source File: HttpBridge.java    From strimzi-kafka-bridge with Apache License 2.0 4 votes vote down vote up
private void ready(RoutingContext routingContext) {
    HttpResponseStatus httpResponseStatus = this.healthChecker.isReady() ? HttpResponseStatus.OK : HttpResponseStatus.NOT_FOUND;
    HttpUtils.sendResponse(routingContext, httpResponseStatus.code(), null, null);
}
 
Example 16
Source File: StaleElementReferenceException.java    From appium-uiautomator2-server with Apache License 2.0 4 votes vote down vote up
@Override
public HttpResponseStatus getHttpStatus() {
    return HttpResponseStatus.NOT_FOUND;
}
 
Example 17
Source File: NoAlertOpenException.java    From appium-uiautomator2-server with Apache License 2.0 4 votes vote down vote up
public HttpResponseStatus getHttpStatus() {
    return HttpResponseStatus.NOT_FOUND;
}
 
Example 18
Source File: ElementNotFoundException.java    From appium-uiautomator2-server with Apache License 2.0 4 votes vote down vote up
@Override
public HttpResponseStatus getHttpStatus() {
    return HttpResponseStatus.NOT_FOUND;
}
 
Example 19
Source File: InstrumentationConfigJsonService.java    From glowroot with Apache License 2.0 4 votes vote down vote up
private String getInstrumentationConfigInternal(String agentId, String version)
        throws Exception {
    InstrumentationConfig config = configRepository.getInstrumentationConfig(agentId, version);
    if (config == null) {
        throw new JsonServiceException(HttpResponseStatus.NOT_FOUND);
    }
    List<MethodSignature> methodSignatures = null;
    if (liveWeavingService != null) {
        try {
            methodSignatures = liveWeavingService.getMethodSignatures(agentId,
                    config.getClassName(), config.getMethodName());
        } catch (AgentNotConnectedException e) {
            logger.debug(e.getMessage(), e);
        }
    }

    ImmutableInstrumentationConfigResponse.Builder builder =
            ImmutableInstrumentationConfigResponse.builder()
                    .agentNotConnected(methodSignatures == null)
                    .config(InstrumentationConfigDto.create(config));
    if (methodSignatures == null) {
        // agent not connected
        List<String> modifiers = Lists.newArrayList();
        if (!isSignatureAll(config)) {
            for (MethodModifier modifier : config.getMethodModifierList()) {
                modifiers.add(modifier.name());
            }
            builder.addMethodSignatures(ImmutableMethodSignatureDto.builder()
                    .name(config.getMethodName())
                    .parameterTypes(config.getMethodParameterTypeList())
                    .returnType(config.getMethodReturnType())
                    .modifiers(modifiers)
                    .build());
        }
    } else {
        for (MethodSignature methodSignature : methodSignatures) {
            builder.addMethodSignatures(MethodSignatureDto.create(methodSignature));
        }
    }
    return mapper.writeValueAsString(builder.build());
}
 
Example 20
Source File: NettyResponseChannel.java    From ambry with Apache License 2.0 4 votes vote down vote up
/**
 * 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;
}