下面列出了javax.ws.rs.core.Response.Status#SERVICE_UNAVAILABLE 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Check if the cluster exists and redirect the call to the owning cluster
*
* @param cluster
* Cluster name
* @throws Exception
* In case the redirect happens
*/
protected void validateClusterOwnership(String cluster) throws WebApplicationException {
try {
ClusterData differentClusterData = getClusterDataIfDifferentCluster(pulsar(), cluster, clientAppId()).get();
if (differentClusterData != null) {
URI redirect = getRedirectionUrl(differentClusterData);
// redirect to the cluster requested
if (log.isDebugEnabled()) {
log.debug("[{}] Redirecting the rest call to {}: cluster={}", clientAppId(), redirect, cluster);
}
throw new WebApplicationException(Response.temporaryRedirect(redirect).build());
}
} catch (WebApplicationException wae) {
throw wae;
} catch (Exception e) {
if (e.getCause() instanceof WebApplicationException) {
throw (WebApplicationException) e.getCause();
}
throw new RestException(Status.SERVICE_UNAVAILABLE, String
.format("Failed to validate Cluster configuration : cluster=%s emsg=%s", cluster, e.getMessage()));
}
}
@Override
public void doFilter(
final ServletRequest request, final ServletResponse response, final FilterChain chain
) throws IOException, ServletException {
if (!stopping.get()) {
chain.doFilter(request, response);
return;
}
final HttpServletResponse httpResponse = (HttpServletResponse) response;
final InternalErrorMessage info =
new InternalErrorMessage("Heroic is shutting down", Status.SERVICE_UNAVAILABLE);
httpResponse.setStatus(Status.SERVICE_UNAVAILABLE.getStatusCode());
httpResponse.setContentType(CONTENT_TYPE);
// intercept request
try (final ByteArrayOutputStream output = new ByteArrayOutputStream(4096)) {
final OutputStreamWriter writer = new OutputStreamWriter(output, Charsets.UTF_8);
mapper.writeValue(writer, info);
response.setContentLength(output.size());
output.writeTo(httpResponse.getOutputStream());
}
}
@GET
@Path("ping")
public Response ping() {
Service.Status status = enclave.status();
Status httpStatus;
if (status == Service.Status.STARTED) {
httpStatus = Status.OK;
} else {
httpStatus = Status.SERVICE_UNAVAILABLE;
}
return Response.status(httpStatus).entity(status.name()).build();
}
@PostMapping(path = "/sayhello/{name}")
public String sayHello(@PathVariable("name") String name) {
if ("exception".equals(name)) {
throw new InvocationException(Status.SERVICE_UNAVAILABLE, "");
}
return "hello " + name;
}
@GetMapping(path = "/retrySuccess")
public int retrySuccess(@RequestParam("a") int a, @RequestParam("b") int b) {
if (firstInovcation.getAndDecrement() > 0) {
throw new InvocationException(Status.SERVICE_UNAVAILABLE, "try again later.");
}
return a + b;
}
private void ensureStatusUp() {
if (scbEngine == null) {
if (SCBEngine.getInstance() == null) {
String message =
"The request is rejected. Cannot process the request due to SCBEngine not ready.";
LOGGER.warn(message);
throw new InvocationException(Status.SERVICE_UNAVAILABLE, message);
}
this.scbEngine = SCBEngine.getInstance();
this.appId = scbEngine.parseAppId(microserviceName);
}
scbEngine.ensureStatusUp();
}
public void ensureStatusUp() {
SCBStatus currentStatus = getStatus();
if (!SCBStatus.UP.equals(currentStatus)) {
String message =
"The request is rejected. Cannot process the request due to STATUS = " + currentStatus;
LOGGER.warn(message);
throw new InvocationException(Status.SERVICE_UNAVAILABLE, message);
}
}
/**
* Find next broker url in round-robin
*
* @return
*/
LoadManagerReport nextBroker() {
List<LoadManagerReport> availableBrokers = zkCache.getAvailableBrokers();
if (availableBrokers.isEmpty()) {
throw new RestException(Status.SERVICE_UNAVAILABLE, "No active broker is available");
} else {
int brokersCount = availableBrokers.size();
int nextIdx = signSafeMod(counter.getAndIncrement(), brokersCount);
return availableBrokers.get(nextIdx);
}
}
protected ProxyService proxyService() {
if (service == null) {
service = (ProxyService) servletContext.getAttribute(ATTRIBUTE_PULSAR_PROXY_NAME);
if (service == null) {
throw new RestException(Status.SERVICE_UNAVAILABLE, "Proxy service is not initialized");
}
}
return service;
}
@Override
public Response toResponse(UncategorizedMongoDbException exception) {
Status errorStatus = Status.SERVICE_UNAVAILABLE;
LOG.error("Could not access database", exception);
return Response
.status(errorStatus)
.entity(new ErrorResponse(errorStatus.getStatusCode(), errorStatus.getReasonPhrase(),
"Could not access database:" + exception.getMessage())).build();
}
private void throwStateStoreUnvailableResponse() {
throw new RestException(Status.SERVICE_UNAVAILABLE,
"State storage client is not done initializing. " + "Please try again in a little while.");
}
@GET
@Path("localnode/health")
@Produces(MediaType.TEXT_PLAIN)
public String getLocalNodeHealth() throws MalformedObjectNameException
{
// Local service only - not enabled when running on top of Tomcat & co.
if (n == null)
{
throw new ErrorDto("can only retrieve local node health when the web app runs on top of JQM", "", 7, Status.BAD_REQUEST);
}
if (n.getJmxServerPort() == null || n.getJmxServerPort() == 0)
{
throw new ErrorDto("JMX is not enabled on this server", "", 8, Status.BAD_REQUEST);
}
// Connect to JMX server
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
ObjectName nodeBean = new ObjectName("com.enioka.jqm:type=Node,name=" + n.getName());
Set<ObjectName> names = server.queryNames(nodeBean, null);
if (names.isEmpty())
{
throw new ErrorDto("could not find the JMX Mbean of the local JQM node", "", 8, Status.INTERNAL_SERVER_ERROR);
}
ObjectName localNodeBean = names.iterator().next();
// Query bean
Object result;
try
{
result = server.getAttribute(localNodeBean, "AllPollersPolling");
}
catch (Exception e)
{
throw new ErrorDto("Issue when querying JMX server", 12, e, Status.INTERNAL_SERVER_ERROR);
}
if (!(result instanceof Boolean))
{
throw new ErrorDto("JMX bean answered with wrong datatype - answer was " + result.toString(), "", 9,
Status.INTERNAL_SERVER_ERROR);
}
// Analyze output
boolean res = (Boolean) result;
if (!res)
{
throw new ErrorDto("JQM node has is not working as expected", "", 11, Status.SERVICE_UNAVAILABLE);
}
return "Pollers are polling";
}
/**
* Creates a builder for a unavailable service
*
* @return the exception builder
*/
public static ExceptionBuilder unavailable() {
return new ExceptionBuilder(Status.SERVICE_UNAVAILABLE);
}