void checkReports(final Map<String, ValidationReport> reports) throws RestLiServiceException { final StringBuffer errorMsgs = new StringBuffer(); for (final Map.Entry<String, ValidationReport> reportEntry : reports.entrySet()) { final ValidationReport report = reportEntry.getValue(); if (!report.getErrorMsgs().isEmpty()) { errorMsgs.append("Validator " + reportEntry.getKey() + " reports errors: "); for (final String msg : report.getErrorMsgs()) { errorMsgs.append(msg + System.getProperty("line.separator")); } } } if (errorMsgs.length() > 0) { throw new RestLiServiceException(HttpStatus.S_400_BAD_REQUEST, errorMsgs.toString()); } }
@Override public void run() { try { while (true) { RequestAndCallback requestAndCallback = MockRequester.this.requestAndCallbackQueue.take(); long nanoTime = System.nanoTime(); long delayNanos = requestAndCallback.getProcessAfterNanos() - nanoTime; if (delayNanos > 0) { Thread.sleep(TimeUnit.NANOSECONDS.toMillis(delayNanos)); } try { PermitAllocation allocation = MockRequester.this.limiterServer.getSync(new ComplexResourceKey<>(requestAndCallback.getRequest(), new EmptyRecord())); Response<PermitAllocation> response = Mockito.mock(Response.class); Mockito.when(response.getEntity()).thenReturn(allocation); requestAndCallback.getCallback().onSuccess(response); } catch (RestLiServiceException rexc) { RestLiResponseException returnException = Mockito.mock(RestLiResponseException.class); Mockito.when(returnException.getStatus()).thenReturn(rexc.getStatus().getCode()); requestAndCallback.getCallback().onError(returnException); } } } catch (Throwable t) { log.error("Error", t); throw new RuntimeException(t); } } }
URI leaderUri = this.leaderFinderOpt.get().getLeaderMetadata().getUri(); RestLiServiceException exception = new RestLiServiceException(HttpStatus.S_301_MOVED_PERMANENTLY, String.format("New leader <a href=\"%s\">%s</a>", leaderUri, leaderUri)); exception.setErrorDetails(new DataMap(ImmutableMap.of(LOCATION_301, leaderUri.toString()))); throw exception; } else { throw new RestLiServiceException(HttpStatus.S_422_UNPROCESSABLE_ENTITY, "No configuration for the requested resource."); } catch (IOException ioe) {
@Test public void test() throws Exception { try(Closer closer = Closer.create()) { Map<String, String> configMap = Maps.newHashMap(); TestingServer zkTestingServer = closer.register(new TestingServer(-1)); configMap.put(ThrottlingGuiceServletConfig.ZK_STRING_KEY, zkTestingServer.getConnectString()); configMap.put(ThrottlingGuiceServletConfig.HA_CLUSTER_NAME, TestFailover.class.getSimpleName() + "_cluster"); Config config = ConfigFactory.parseMap(configMap); ThrottlingGuiceServletConfig server2001 = createServerAtPort(config, 2001); PermitAllocation allocation = sendRequestToServer(server2001, 10); Assert.assertTrue(allocation.getPermits() >= 1); ThrottlingGuiceServletConfig server2002 = createServerAtPort(config, 2002); allocation = sendRequestToServer(server2001, 10); Assert.assertTrue(allocation.getPermits() >= 1); try { sendRequestToServer(server2002, 10); Assert.fail(); } catch (RestLiServiceException exc) { Assert.assertTrue(exc.hasErrorDetails()); Assert.assertTrue(exc.getErrorDetails().containsKey(LimiterServerResource.LOCATION_301)); Assert.assertEquals(new URI(exc.getErrorDetails().get(LimiterServerResource.LOCATION_301).toString()).getPort(), 2001); } server2001.close(); allocation = sendRequestToServer(server2002, 10); Assert.assertTrue(allocation.getPermits() >= 1); } }
/** * Test that an error message is attached to the exception on an error */ @Test public void testErrorMessageDeploy() { final ProjectManagerResource resource = new ProjectManagerResource(); final Map<String, ValidationReport> reports = new LinkedHashMap<>(); addMockError(reports, "This should show up."); // We expect that a RestLiServiceException is thrown given a // report with errors. Uncaught exceptions will result in failure try { resource.checkReports(reports); Assert.fail(); } catch (final RestLiServiceException e) { //Ensure we have the right status code and exit assertEquals(e.getStatus(), HttpStatus.S_400_BAD_REQUEST); assertEquals(e.getMessage(), "Validator Error reports errors: This should show up." + System.getProperty("line.separator")); } }
@Override public Greeting get(Long key) { try { String s = (new String[0])[42]; } catch (ArrayIndexOutOfBoundsException e) { Greeting details = new Greeting().setMessage("Hello, Sorry for the mess"); throw new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, "error processing request", e) .setServiceErrorCode(42).setErrorDetails(details.data()); } return null; }
throw new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, "Unexpected null encountered. Null Map found inside of the BatchUpdateResult returned by the resource method: " + routingResult.getResourceMethod()); if (serviceErrors == null) throw new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, "Unexpected null encountered. Null errors Map found inside of the BatchUpdateResult returned by the resource method: " + routingResult.getResourceMethod()); throw new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, "Unexpected null encountered. Null key inside of the Map returned inside of the BatchUpdateResult returned by the resource method: " + routingResult.getResourceMethod()); throw new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, "Unexpected null encountered. Null key or value inside of the Map returned inside of the BatchUpdateResult returned by the resource method: " + routingResult.getResourceMethod()); batchResponseMap.put(finalKey, new BatchResponseEntry(entry.getValue().getStatus(), entry.getValue())); batchResponseMap.put(finalKey, new BatchResponseEntry(entry.getValue().getStatus(), entry.getValue()));
if (errorResponseFormat.showStatusCodeInBody()) er.setStatus(result.getStatus().getCode()); if (errorResponseFormat.showMessage() && result.getMessage() != null) er.setMessage(result.getMessage()); if (errorResponseFormat.showServiceErrorCode() && result.hasServiceErrorCode()) er.setServiceErrorCode(result.getServiceErrorCode()); if (errorResponseFormat.showDetails() && result.hasErrorDetails()) er.setErrorDetails(new ErrorDetails(result.getErrorDetails())); result.printStackTrace(pw); er.setStackTrace(sw.toString());
protected RestLiResponseException buildPreRoutingError(Throwable throwable, Request request) { Map<String, String> requestHeaders = request.getHeaders(); Map<String, String> headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); headers.put(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, ProtocolVersionUtil.extractProtocolVersion(requestHeaders).toString()); headers.put(HeaderUtil.getErrorResponseHeaderName(requestHeaders), RestConstants.HEADER_VALUE_ERROR); RestLiServiceException restLiServiceException = RestLiServiceException.fromThrowable(throwable); ErrorResponse errorResponse = _errorResponseBuilder.buildErrorResponse(restLiServiceException); RestLiResponse restLiResponse = new RestLiResponse.Builder() .status(restLiServiceException.getStatus()) .entity(errorResponse) .headers(headers) .cookies(Collections.emptyList()) .build(); return new RestLiResponseException(throwable, restLiResponse); }
/** * Responds with an error for requests to create insulting greetings, responds * with 201 created for all other requests. */ @RestMethod.Create public CreateResponse create(Greeting g) { if(g.hasTone() && g.getTone() == Tone.INSULTING) { RestLiServiceException notAcceptableException = new RestLiServiceException(HttpStatus.S_406_NOT_ACCEPTABLE, "I will not tolerate your insolence!"); DataMap details = new DataMap(); details.put("reason", "insultingGreeting"); notAcceptableException.setErrorDetails(details); notAcceptableException.setServiceErrorCode(999); throw notAcceptableException; } else { return new CreateResponse(g.getId(), HttpStatus.S_201_CREATED); } }
private RestLiResponse buildErrorResponse(Throwable th, RestLiResponseData<?> responseData) { Map<String, String> responseHeaders = responseData.getHeaders(); responseHeaders.put(HeaderUtil.getErrorResponseHeaderName(responseHeaders), RestConstants.HEADER_VALUE_ERROR); RestLiServiceException ex; if (th instanceof RestLiServiceException) { ex = (RestLiServiceException) th; } else { ex = new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, th.getMessage(), th); } return new RestLiResponse.Builder().headers(responseHeaders).cookies(responseData.getCookies()) .status(ex.getStatus()) .entity(_errorResponseBuilder.buildErrorResponse(ex)) .build(); }
if (project == null) { final String errorMsg = "Project '" + projectName + "' not found."; throw new RestLiServiceException(HttpStatus.S_400_BAD_REQUEST, errorMsg); final String errorMsg = "Installation Failed. Project '" + projectName + "' was already removed."; throw new RestLiServiceException(HttpStatus.S_410_GONE, errorMsg); + " has no permission to write to project " + project.getName(); logger.error(errorMsg); throw new RestLiServiceException(HttpStatus.S_400_BAD_REQUEST, errorMsg); final String errorMsg = "URL " + packageUrl + " is malformed."; logger.error(errorMsg, e); throw new RestLiServiceException(HttpStatus.S_400_BAD_REQUEST, errorMsg); FileUtils.deleteDirectory(tempDir); throw new RestLiServiceException(HttpStatus.S_400_BAD_REQUEST, errorMsg, e);
URI leaderUri = this.leaderFinderOpt.get().getLeaderMetadata().getUri(); RestLiServiceException exception = new RestLiServiceException(HttpStatus.S_301_MOVED_PERMANENTLY, String.format("New leader <a href=\"%s\">%s</a>", leaderUri, leaderUri)); exception.setErrorDetails(new DataMap(ImmutableMap.of(LOCATION_301, leaderUri.toString()))); throw exception; } else { throw new RestLiServiceException(HttpStatus.S_422_UNPROCESSABLE_ENTITY, "No configuration for the requested resource."); } catch (IOException ioe) {
@Test public void testErrorDeploy() { final ProjectManagerResource resource = new ProjectManagerResource(); final Map<String, ValidationReport> reports = new LinkedHashMap<>(); for (int i = 0; i < 3; i++) { addMockError(reports, "Test error level info message."); } // We expect that a RestLiServiceException is thrown given a // report with errors. Uncaught exceptions will result in failure try { resource.checkReports(reports); Assert.fail(); } catch (final RestLiServiceException e) { //Ensure we have the right status code and exit assertEquals(e.getStatus(), HttpStatus.S_400_BAD_REQUEST); } }
@Override public Policy get(String resourceId) { try { ThrottlingPolicy throttlingPolicy = (ThrottlingPolicy) this.broker.getSharedResource(new ThrottlingPolicyFactory(), new SharedLimiterKey(resourceId)); Policy restliPolicy = new Policy(); restliPolicy.setPolicyName(throttlingPolicy.getClass().getSimpleName()); restliPolicy.setResource(resourceId); restliPolicy.setParameters(new StringMap(throttlingPolicy.getParameters())); restliPolicy.setPolicyDetails(throttlingPolicy.getDescription()); MetricContext resourceContext = (MetricContext) broker.getSharedResource(new MetricContextFactory(), new SubTaggedMetricContextKey(resourceId, ImmutableMap.of(RESOURCE_ID_TAG, resourceId))); StringMap metrics = new StringMap(); for (Map.Entry<String, Meter> meter : resourceContext.getMeters().entrySet()) { metrics.put(meter.getKey(), Double.toString(meter.getValue().getOneMinuteRate())); } restliPolicy.setMetrics(metrics); return restliPolicy; } catch (NotConfiguredException nce) { throw new RestLiServiceException(HttpStatus.S_404_NOT_FOUND, "Policy not found for resource " + resourceId); } } }
URI leaderUri = this.leaderFinderOpt.get().getLeaderMetadata().getUri(); RestLiServiceException exception = new RestLiServiceException(HttpStatus.S_301_MOVED_PERMANENTLY, String.format("New leader <a href=\"%s\">%s</a>", leaderUri, leaderUri)); exception.setErrorDetails(new DataMap(ImmutableMap.of(LOCATION_301, leaderUri.toString()))); throw exception; } else { throw new RestLiServiceException(HttpStatus.S_422_UNPROCESSABLE_ENTITY, "No configuration for the requested resource."); } catch (IOException ioe) {
@Test public void testWarnErrorDeploy() { final ProjectManagerResource resource = new ProjectManagerResource(); final Map<String, ValidationReport> reports = new LinkedHashMap<>(); for (int i = 0; i < 7; i++) { // If i is even, make an error report, otherwise make a warning report if (i % 2 == 0) { addMockError(reports, "Test error level info message."); } else { addMockWarning(reports, "Test warn level info message."); } } // We expect that a RestLiServiceException is thrown given a // report with errors. Uncaught exceptions will result in failure try { resource.checkReports(reports); Assert.fail(); } catch (final RestLiServiceException e) { //Ensure we have the right status code and exit assertEquals(e.getStatus(), HttpStatus.S_400_BAD_REQUEST); } }
@Override public PermitAllocation computePermitAllocation(PermitRequest request) { long permits = request.getPermits(); long allocated = 0; try { if (limiter.acquirePermits(permits) != null) { allocated = permits; } else { throw new RestLiServiceException(HttpStatus.S_403_FORBIDDEN, "Not enough permits."); } } catch (InterruptedException ie) { // return no permits } PermitAllocation allocation = new PermitAllocation(); allocation.setPermits(allocated); allocation.setExpiration(Long.MAX_VALUE); if (allocated <= 0) { allocation.setMinRetryDelayMillis(60000); } return allocation; }
private void validate() { if (_flashbackRunner == null) { throw new RestLiServiceException(HttpStatus.S_400_BAD_REQUEST, "FlashbackRunner is not started "); } } }