javax.ws.rs.ServiceUnavailableException Java Examples

The following examples show how to use javax.ws.rs.ServiceUnavailableException. 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: CommonHandlers.java    From devicehive-java-server with Apache License 2.0 6 votes vote down vote up
@HiveWebsocketAuth
@PreAuthorize("permitAll")
public void processRefresh(JsonObject request, WebSocketSession session) throws IOException {
    if (request.get("refreshToken") == null) {
        logger.warn("JwtToken: payload was not found");
        throw new HiveException(Messages.PAYLOAD_NOT_FOUND, SC_BAD_REQUEST);
    }

    JwtRefreshTokenVO refreshTokenVO = new JwtRefreshTokenVO();
    refreshTokenVO.setRefreshToken(request.get("refreshToken").getAsString());

    String refreshTokenStr = gson.toJson(refreshTokenVO);

    JwtTokenVO jwtToken = null;
    try {
        jwtToken = httpRestHelper.post(authBaseUrl + "/token/refresh", refreshTokenStr, JwtTokenVO.class, null);
    } catch (ServiceUnavailableException e) {
        throw new HiveException(e.getMessage(), SC_SERVICE_UNAVAILABLE);
    }

    WebSocketResponse response = new WebSocketResponse();
    response.addValue("accessToken", jwtToken.getAccessToken());
    clientHandler.sendMessage(request, response, session);
}
 
Example #2
Source File: CommonHandlers.java    From devicehive-java-server with Apache License 2.0 6 votes vote down vote up
@HiveWebsocketAuth
@PreAuthorize("isAuthenticated() and hasPermission(null, 'MANAGE_TOKEN')")
public void processTokenCreate(JsonObject request, WebSocketSession session) throws IOException {
    JsonObject payload = request.get(Constants.PAYLOAD).getAsJsonObject();
    if (payload == null) {
        logger.warn("JwtToken: payload was not found");
        throw new HiveException(Messages.PAYLOAD_NOT_FOUND, SC_BAD_REQUEST);
    }
    hiveValidator.validate(payload);
    
    String jwtTokenStr = (String) session.getAttributes().get(WebSocketAuthenticationManager.SESSION_ATTR_JWT_TOKEN);
    
    JwtTokenVO jwtToken = null;
    try {
        jwtToken = httpRestHelper.post(authBaseUrl + "/token/create", payload.toString(), JwtTokenVO.class, jwtTokenStr);
    } catch (ServiceUnavailableException e) {
        throw new HiveException(e.getMessage(), SC_SERVICE_UNAVAILABLE);
    }
    
    WebSocketResponse response = new WebSocketResponse();
    response.addValue("accessToken", jwtToken.getAccessToken());
    response.addValue("refreshToken", jwtToken.getRefreshToken());
    clientHandler.sendMessage(request, response, session);
}
 
Example #3
Source File: CommonHandlers.java    From devicehive-java-server with Apache License 2.0 6 votes vote down vote up
@HiveWebsocketAuth
@PreAuthorize("permitAll")
public void processLogin(JsonObject request, WebSocketSession session) throws IOException {
    JwtRequestVO loginRequest = new JwtRequestVO();
    if (request.get("login") != null) {
        loginRequest.setLogin(request.get("login").getAsString());
    }
    if (request.get("password") != null) {
        loginRequest.setPassword(request.get("password").getAsString());
    }
    
    String loginRequestStr = gson.toJson(loginRequest);

    JwtTokenVO jwtToken = null;
    try {
        jwtToken = httpRestHelper.post(authBaseUrl + "/token", loginRequestStr, JwtTokenVO.class, null);
    } catch (ServiceUnavailableException e) {
        throw new HiveException(e.getMessage(), SC_SERVICE_UNAVAILABLE);
    }
    
    WebSocketResponse response = new WebSocketResponse();
    response.addValue("accessToken", jwtToken.getAccessToken());
    response.addValue("refreshToken", jwtToken.getRefreshToken());
    clientHandler.sendMessage(request, response, session);
}
 
Example #4
Source File: AccountAuthenticator.java    From pay-publicapi with MIT License 6 votes vote down vote up
@Override
public Optional<Account> authenticate(String bearerToken) {

    Response response = client.target(publicAuthUrl).request()
            .header(AUTHORIZATION, "Bearer " + bearerToken)
            .accept(MediaType.APPLICATION_JSON)
            .get();

    if (response.getStatus() == OK.getStatusCode()) {
        return readAccountFromResponse(response);
    } else if (response.getStatus() == UNAUTHORIZED.getStatusCode()) {
        response.close();
        return Optional.empty();
    } else {
        response.close();
        logger.warn("Unexpected status code " + response.getStatus() + " from auth.");
        throw new ServiceUnavailableException();
    }
}
 
Example #5
Source File: ServiceUnavailableExceptionMapper.java    From sinavi-jfw with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Response toResponse(final ServiceUnavailableException exception) {
    if (L.isDebugEnabled()) {
        L.debug(R.getString("D-REST-JERSEY-MAPPER#0011"));
    }
    ErrorMessage error = ErrorMessages.create(exception)
        .id()
        .code(ErrorCode.SERVICE_UNAVAILABLE.code())
        .resolve()
        .get();
    L.error(error.log(), exception);
    return Response.status(exception.getResponse().getStatusInfo())
        .entity(error)
        .type(MediaType.APPLICATION_JSON)
        .build();
}
 
Example #6
Source File: PluginRegisterService.java    From devicehive-java-server with Apache License 2.0 5 votes vote down vote up
private JwtTokenVO createPluginTokens(String topicName, String authorization) {
    JwtPluginPayload jwtPluginPayload = new JwtPluginPayload(Collections.singleton(MANAGE_PLUGIN.getId()), topicName, null, null);
    
    JwtTokenVO jwtToken = null;
    try {
        jwtToken = httpRestHelper.post(authBaseUrl + "/token/plugin/create", gson.toJson(jwtPluginPayload), JwtTokenVO.class, authorization);
    } catch (ServiceUnavailableException e) {
        logger.error("Authentication service is not available");
        throw new HiveException(e.getMessage(), SERVICE_UNAVAILABLE.getStatusCode());
    }
    
    return jwtToken;
}
 
Example #7
Source File: LoadDetectFilter.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext context) {
    if (LoadDetectFilter.isWhiteAPI(context)) {
        return;
    }

    HugeConfig config = this.configProvider.get();

    int maxWorkerThreads = config.get(ServerOptions.MAX_WORKER_THREADS);
    WorkLoad load = this.loadProvider.get();
    // There will be a thread doesn't work, dedicated to statistics
    if (load.incrementAndGet() >= maxWorkerThreads) {
        throw new ServiceUnavailableException(String.format(
                  "The server is too busy to process the request, " +
                  "you can config %s to adjust it or try again later",
                  ServerOptions.MAX_WORKER_THREADS.name()));
    }

    long minFreeMemory = config.get(ServerOptions.MIN_FREE_MEMORY);
    long allocatedMem = Runtime.getRuntime().totalMemory() -
                        Runtime.getRuntime().freeMemory();
    long presumableFreeMem = (Runtime.getRuntime().maxMemory() -
                              allocatedMem) / Bytes.MB;
    if (presumableFreeMem < minFreeMemory) {
        gcIfNeeded();
        throw new ServiceUnavailableException(String.format(
                  "The server available memory %s(MB) is below than " +
                  "threshold %s(MB) and can't process the request, " +
                  "you can config %s to adjust it or try again later",
                  presumableFreeMem, minFreeMemory,
                  ServerOptions.MIN_FREE_MEMORY.name()));
    }
}
 
Example #8
Source File: PluginResourceImpl.java    From devicehive-java-server with Apache License 2.0 5 votes vote down vote up
@Override
public void register(PluginReqisterQuery pluginReqisterQuery, PluginUpdate pluginUpdate, String authorization,
        @Suspended final AsyncResponse asyncResponse) {
    hiveValidator.validate(pluginUpdate);
    try {
        HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        pluginRegisterService.register(principal.getUser().getId(), pluginReqisterQuery, pluginUpdate, authorization)
                .thenAccept(asyncResponse::resume);
    } catch (ServiceUnavailableException e) {
        logger.warn(HEALTH_CHECK_FAILED);
        asyncResponse.resume(ResponseFactory.response(BAD_REQUEST,
                new ErrorResponse(BAD_REQUEST.getStatusCode(), HEALTH_CHECK_FAILED)));
    }
}
 
Example #9
Source File: DateHeaderProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testToFromSimpleString() {
    Date retry = new Date();
    ServiceUnavailableException ex = new ServiceUnavailableException(retry);
    Date retry2 = ex.getRetryTime(new Date());
    assertEquals(HttpUtils.toHttpDate(retry), HttpUtils.toHttpDate(retry2));
}
 
Example #10
Source File: AsyncResponseImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
public synchronized void handleTimeout() {
    if (!resumedByApplication) {
        if (pendingTimeout != null) {
            setAsyncResponseOnExchange();
            cont.suspend(pendingTimeout);
            pendingTimeout = null;
        } else if (timeoutHandler != null) {
            timeoutHandler.handleTimeout(this);
        } else {
            cont.setObject(new ServiceUnavailableException());
        }
    }
}
 
Example #11
Source File: FailoverBookStore.java    From cxf with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/unavailable")
public Book getBookRootUnavailable() {
    if (unavailableCounter++ < 4) {
        throw new ServiceUnavailableException();
    }
    return new Book("root", 124L);
}
 
Example #12
Source File: DebugEndpointImpl.java    From pnc with Apache License 2.0 5 votes vote down vote up
@Override
public void sendDummyMessageToQueue(String type) {
    Optional<MessageSender> messageSender = messageSenderProvider.getMessageSender();
    if (!messageSender.isPresent()) {
        throw new ServiceUnavailableException();
    } else {
        if (type != null && type.equals("status")) {
            buildStatusChangedEventNotifier.fire(
                    new DefaultBuildStatusChangedEvent(newBuild(), BuildStatus.CANCELLED, BuildStatus.CANCELLED));
        } else {
            messageSender.get().sendToTopic("Test Message.");
        }
    }
}
 
Example #13
Source File: BaseResource.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public PulsarAdminException getApiException(Throwable e) {
    if (e instanceof PulsarAdminException) {
        return (PulsarAdminException) e;
    } else if (e instanceof ServiceUnavailableException) {
        if (e.getCause() instanceof java.net.ConnectException) {
            return new ConnectException(e.getCause());
        } else {
            return new PulsarAdminException((ServerErrorException) e);
        }
    } else if (e instanceof WebApplicationException) {
        // Handle 5xx exceptions
        if (e instanceof ServerErrorException) {
            ServerErrorException see = (ServerErrorException) e;
            return new ServerSideErrorException(see, e.getMessage());
        } else if (e instanceof ClientErrorException) {
            // Handle 4xx exceptions
            ClientErrorException cee = (ClientErrorException) e;
            int statusCode = cee.getResponse().getStatus();
            switch (statusCode) {
                case 401:
                case 403:
                    return new NotAuthorizedException(cee);
                case 404:
                    return new NotFoundException(cee);
                case 405:
                    return new NotAllowedException(cee);
                case 409:
                    return new ConflictException(cee);
                case 412:
                    return new PreconditionFailedException(cee);
                default:
                    return new PulsarAdminException(cee);
            }
        } else {
            return new PulsarAdminException((WebApplicationException) e);
        }
    } else {
        return new PulsarAdminException(e);
    }
}
 
Example #14
Source File: InvestingSessionTest.java    From robozonky with Apache License 2.0 5 votes vote down vote up
@Test
void failedDueToUnknownError() {
    final Zonky z = harmlessZonky();
    final PowerTenant auth = mockTenant(z, false);
    final RecommendedLoan r = mockLoanDescriptor().recommend(Money.from(200))
        .get();
    final Exception thrown = new ServiceUnavailableException();
    doThrow(thrown).when(z)
        .invest(notNull(), anyInt());
    final InvestingSession t = new InvestingSession(Collections.emptySet(), auth);
    assertThatThrownBy(() -> t.accept(r)).isSameAs(thrown);
    verify(auth, never()).setKnownBalanceUpperBound(any());
}
 
Example #15
Source File: ProductApiClient.java    From microservices-springboot with MIT License 5 votes vote down vote up
private URI getProductServiceUri() {

        ServiceInstance serviceInstance = loadBalancer.choose(PRODUCT_SERVICE);
        if (serviceInstance == null) {
            throw new ServiceUnavailableException("Service unavailable");
        }

        return serviceInstance.getUri();
    }
 
Example #16
Source File: VertxHttpRequest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
protected void handleTimeout() {
    if (timeoutHandler != null) {
        timeoutHandler.handleTimeout(this);
    }
    if (done)
        return;
    resume(new ServiceUnavailableException());
}
 
Example #17
Source File: ServiceUnavailableExceptionResourceTest.java    From sinavi-jfw with Apache License 2.0 4 votes vote down vote up
@GET
public EmptyTest exception() {
    throw new ServiceUnavailableException("service");
}
 
Example #18
Source File: ServerGracefulShutdownIT.java    From digdag with Apache License 2.0 4 votes vote down vote up
@Test
public void gracefulShutdown()
        throws Exception
{
    Id attemptId = startSleepTask();

    server.terminateProcess();
    Instant terminateStartedAt = Instant.now();

    // server started termination but it should be alive at most 5 seconds.

    int aliveCount = 0;
    while (true) {
        Instant loopStartedAt = Instant.now();
        if (loopStartedAt.isAfter(terminateStartedAt.plus(Duration.ofMinutes(10)))) {
            throw new IllegalStateException("Server didn't shutdown within 10 minutes");
        }

        try {
            client.getSessionAttempt(attemptId);
            aliveCount++;
        }
        catch (Exception ex) {
            // if REST API fails, the cause should be 503 Service Unavailable or
            // connection refused.
            if (ex instanceof ProcessingException) {
                assertThat(ex.getCause(), instanceOf(ConnectException.class));
                break;
            }
            else {
                assertThat(ex, instanceOf(ServiceUnavailableException.class));
                break;
            }
        }

        // sleep for 1 second
        long sleepMillis = Duration.between(Instant.now(), loopStartedAt.plusSeconds(1)).toMillis();
        if (sleepMillis > 0) {
            Thread.sleep(sleepMillis);
        }
    }

    // all running tasks should be done
    assertThat(Files.exists(root().resolve("done.out")), is(true));

    // but waiting tasks should not start
    assertThat(Files.exists(root().resolve("after_sleep.out")), is(false));

    // REST API should be alive for a while
    assertThat(aliveCount, greaterThan(3));

    assertThat(server.outUtf8(), containsString("Waiting for completion of 2 running tasks..."));
    assertThat(server.outUtf8(), containsString("Closing HTTP listening sockets"));

    TestUtils.expect(Duration.ofMinutes(5), () -> !server.isProcessAlive());

    assertThat(server.outUtf8(), containsString("Shutting down HTTP worker threads"));
    assertThat(server.outUtf8(), containsString("Shutting down system"));
    assertThat(server.outUtf8(), containsString("Shutdown completed"));
}
 
Example #19
Source File: AccountAuthenticatorTest.java    From pay-publicapi with MIT License 4 votes vote down vote up
@Test(expected = ServiceUnavailableException.class)
public void shouldThrow_ifUnknownResponse() {
    when(mockResponse.getStatus()).thenReturn(NOT_FOUND.getStatusCode());
    accountAuthenticator.authenticate(bearerToken);
}
 
Example #20
Source File: StandardExceptionBoundary.java    From microprofile-sandbox with Apache License 2.0 4 votes vote down vote up
@Path("/plain-service-unavailable")
@POST public void plainServiceUnavailable() {
    throw new ServiceUnavailableException();
}