private static UserException handleException(Exception e, ElasticAction2<?> action, ContextListenerImpl listener) { if (e instanceof ResponseProcessingException) { throw addResponseInfo( listener.addContext(UserException.dataReadError(e) .message("Failure consuming response from Elastic cluster during %s.", action.getAction())), ((ResponseProcessingException) e).getResponse()).build(logger); } if (e instanceof WebApplicationException) { throw addResponseInfo( listener.addContext( UserException.dataReadError(e).message("Failure executing Elastic request %s.", action.getAction())), ((WebApplicationException) e).getResponse()).build(logger); } else { return listener .addContext( UserException.dataReadError(e).message("Failure executing Elastic request %s.", action.getAction())) .build(logger); } }
public static <T> T checkResponse( Response response, Class<T> clazz ) throws PeerException { checkResponse( response, false ); try { return response.readEntity( clazz ); } catch ( ResponseProcessingException e ) { throw new PeerException( "Error parsing response", e ); } finally { close( response ); } }
static void checkResponse( Response response, boolean close ) throws PeerException { try { if ( response == null ) { throw new PeerException( "No response to parse" ); } else if ( response.getStatus() == Response.Status.INTERNAL_SERVER_ERROR.getStatusCode() ) { throw new PeerException( response.readEntity( String.class ) ); } } catch ( ResponseProcessingException e ) { throw new PeerException( "Error parsing response", e ); } finally { if ( close ) { close( response ); } } }
/** * Change the status of a user's response * * @param userResponse the new response * @param person the attendee * @param event the event * @return the navigation case */ public String changeStatus(ResponseEnum userResponse, Person person, Event event) { String navigation; try { logger.log(Level.INFO, "changing status to {0} for {1} {2} for event ID {3}.", new Object[]{userResponse, person.getFirstName(), person.getLastName(), event.getId().toString()}); client.target(baseUri) .path(event.getId().toString()) .path(person.getId().toString()) .request(MediaType.APPLICATION_XML) .post(Entity.xml(userResponse.getLabel())); navigation = "changedStatus"; } catch (ResponseProcessingException ex) { logger.log(Level.WARNING, "couldn''t change status for {0} {1}", new Object[]{person.getFirstName(), person.getLastName()}); logger.log(Level.WARNING, ex.getMessage()); navigation = "error"; } return navigation; }
@Override public InstitutionBean getInstitution(long uniqueId) { Institution institution = institutionService.getInstitution(uniqueId); if( institution == null ) { Response response = Response.status(Status.NOT_FOUND).entity(uniqueId).build(); throw new ResponseProcessingException(response, uniqueId + " not found"); } InstitutionBean bean = serialize(institution); return bean; }
@Test(expected = ResponseProcessingException.class) public void shouldHandleError() { CompletableResource resource = resource(CompletableResource.class); boolean completed = resource.error().await(5, TimeUnit.SECONDS); assertEquals(completed, true); }
@Test(expected = ResponseProcessingException.class) public void shouldHandleError() { ObservableResource resource = resource(ObservableResource.class); String message = resource.error().toBlocking().first(); assertEquals("", message); }
@Test(expected = ResponseProcessingException.class) public void shouldHandleError() { SingleResource resource = resource(SingleResource.class); String message = resource.error().toBlocking().value(); assertEquals("", message); }
@Test public void should_return_works_when_clear_applications_caches() { try { withoutAuth("/cache/applications") .delete(); } catch (ResponseProcessingException e) { fail("Le service devrait fonctionner"); } }
@Test public void should_return_works_when_clear_modules_caches() { try { withAuth("/cache/modules") .delete(); } catch (ResponseProcessingException e) { fail("Le service devrait fonctionner"); } }
@Test public void should_return_works_when_clear_templates_packages_caches() { try { withAuth("/cache/templates/packages") .delete(); } catch (ResponseProcessingException e) { fail("Le service devrait fonctionner"); } }
@Test public void should_return_works_when_clear_applications_caches() { try { withoutAuth("/indexation/perform_reindex") .post(Entity.json(null)); } catch (ResponseProcessingException e) { fail("Le service devrait fonctionner"); } }
/** * This method encapsulates a basic way of making most POST calls to the Jam OData API under the JSON format. * * @param oDataPath API end point to call * @param payload a JSON request body */ private void postToOData(final String oDataPath, final String payload) { System.out.printf("Making Jam OData POST call to %s with payload: %n%s", oDataPath, payload); httpClient .target(JAM_BASE_URL) .path("/api/v1/OData/" + oDataPath) .queryParam("$format", "json") .request(MediaType.APPLICATION_JSON) .header("Authorization", "Bearer " + JAM_OAUTH_TOKEN) .header("Content-Type", MediaType.APPLICATION_JSON) .header("Accept", MediaType.APPLICATION_JSON) .async() .post(Entity.json(payload), new InvocationCallback<String>() { @Override public void completed(final String response) { System.out.println("Received response: " + response); } @Override public void failed(final Throwable throwable) { final ResponseProcessingException exception = (ResponseProcessingException)throwable; final String responseString = exception.getResponse().readEntity(String.class); System.out.println("Received error response: " + responseString); throwable.printStackTrace(); } }); }
/** * Update the player's location. The new location will always be returned * from the service, in the face of a conflict between updates for the * player across devices, we'll get back the one that won. * * @param playerId * The player id * @param jwt * The server jwt for this player id. * @param oldRoomId * The old room's id * @param newRoomId * The new room's id * @return The id of the selected new room, taking contention into account. * @throws IOException * @throws JsonProcessingException */ public String updatePlayerLocation(String playerId, String jwt, String oldRoomId, String newRoomId) { WebTarget target = this.root.path("{playerId}/location").resolveTemplate("playerId", playerId).queryParam("jwt", jwt); JsonObject parameter = Json.createObjectBuilder().add("oldLocation", oldRoomId).add("newLocation", newRoomId).build(); Log.log(Level.INFO, this, "updating location using {0} with putdata {1}", target.getUri().toString(), parameter.toString()); try { // Make PUT request using the specified target, get result as a // string containing JSON String resultString = target.request(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON) .header("Content-type", "application/json").put(Entity.json(parameter), String.class); Log.log(Level.INFO, this, "response was {0}", resultString); JsonReader r = Json.createReader(new StringReader(resultString)); JsonObject result = r.readObject(); String location = result.getString("location"); Log.log(Level.INFO, this, "response location {0}", location); //location should match the 'newRoomId' unless we didn't win the race to change the location. return location; } catch (ResponseProcessingException rpe) { Response response = rpe.getResponse(); Log.log(Level.WARNING, this, "Exception changing player location, uri: {0} resp code: {1}", target.getUri().toString(), response.getStatusInfo().getStatusCode() + " " + response.getStatusInfo().getReasonPhrase() ); Log.log(Level.WARNING, this, "Exception changing player location", rpe); } catch (ProcessingException | WebApplicationException ex) { Log.log(Level.WARNING, this, "Exception changing player location (" + target.getUri().toString() + ")", ex); } // Sadly, badness happened while trying to set the new room location // return to old room return oldRoomId; }
/** * Get shared secret for player * @param playerId * @param jwt * @param oldRoomId * @param newRoomId * @return */ public String getSharedSecret(String playerId, String jwt) { WebTarget target = this.root.path("{playerId}").resolveTemplate("playerId", playerId); Log.log(Level.FINER, this, "requesting shared secret using {0}", target.getUri().toString()); try { // Make PUT request using the specified target, get result as a // string containing JSON Invocation.Builder builder = target.request(MediaType.APPLICATION_JSON); builder.header("Content-type", "application/json"); builder.header("gameon-jwt", jwt); String result = builder.get(String.class); JsonReader p = Json.createReader(new StringReader(result)); JsonObject j = p.readObject(); JsonObject creds = j.getJsonObject("credentials"); return creds.getString("sharedSecret"); } catch (ResponseProcessingException rpe) { Response response = rpe.getResponse(); Log.log(Level.FINER, this, "Exception obtaining shared secret for player, uri: {0} resp code: {1} data: {2}", target.getUri().toString(), response.getStatusInfo().getStatusCode() + " " + response.getStatusInfo().getReasonPhrase(), response.readEntity(String.class)); Log.log(Level.FINEST, this, "Exception obtaining shared secret for player", rpe); } catch (ProcessingException | WebApplicationException ex) { Log.log(Level.FINEST, this, "Exception obtaining shared secret for player (" + target.getUri().toString() + ")", ex); } // Sadly, badness happened while trying to get the shared secret return null; }
/** * Construct an outbound {@code WebTarget} that builds on the root * {@code WebTarget#path(String)} to add the path segment required to * request the deletion of a given room (<code>{roomId}</code> * ). * * @param roomId * The specific room to delete * @param secret * @param userid * * @return The list of available endpoints returned from the concierge. This * may be null if the list could not be retrieved. * * @see #getRoomList(WebTarget) * @see WebTarget#resolveTemplate(String, Object) */ public boolean deleteSite(String roomId, String userid, String secret) { Log.log(Level.FINER, this, "Asked to delete room id {0} for user {1} with secret(first2chars) {2}",roomId,userid,secret.substring(0,2)); Client client = ClientBuilder.newClient().register(JsonProvider.class); // use the player's shared secret for this operation, not ours SignedClientRequestFilter apikey = new SignedClientRequestFilter(userid, secret); client.register(apikey); WebTarget target = client.target(mapLocation).path(roomId); Log.log(Level.FINER, this, "making request to {0} for room", target.getUri().toString()); Response r = null; try { r = target.request().delete(); // if (r.getStatus() == 204) { Log.log(Level.FINER, this, "delete reported success (204)", target.getUri().toString()); return true; } Log.log(Level.FINER, this, "delete failed reason:{0} entity:{1}", r.getStatusInfo().getReasonPhrase(),r.readEntity(String.class)); //delete failed. return false; } catch (ResponseProcessingException rpe) { Response response = rpe.getResponse(); Log.log(Level.SEVERE, this, "Exception deleting room uri: {0} resp code: {1} ", target.getUri().toString(), response.getStatusInfo().getStatusCode() + " " + response.getStatusInfo().getReasonPhrase()); Log.log(Level.SEVERE, this, "Exception deleting room ", rpe); } catch (ProcessingException e) { Log.log(Level.SEVERE, this, "Exception deleting room ", e); } catch (WebApplicationException ex) { Log.log(Level.SEVERE, this, "Exception deleting room ", ex); } // Sadly, badness happened while trying to do the delete return false; }
/** * * @param target * {@code WebTarget} that includes the required parameters to * retrieve information about available or specified exits. All * of the REST requests that find or work with exits return the * same result structure * @return A populated {@code List<Site>}. Never null */ protected List<Site> getSites(WebTarget target) { Log.log(Level.FINER, this, "making request to {0} for room", target.getUri().toString()); Response r = null; try { r = target.request(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).get(); int statusCode = r.getStatusInfo().getStatusCode(); if (statusCode == Response.Status.OK.getStatusCode() ) { List<Site> list = r.readEntity(new GenericType<List<Site>>() { }); if (list == null) { Log.log(Level.FINER, this, "Could not find rooms in the repsonse from uri: {0}", target.getUri().toString()); return Collections.emptyList(); } return list; } else if (statusCode == Response.Status.NO_CONTENT.getStatusCode()) { // If there was no content returned but there is no error, then we don't want to return a null return Collections.emptyList(); } // The return code indicates something went wrong, but it wasn't bad enough to cause an exception return Collections.emptyList(); } catch (ResponseProcessingException rpe) { Response response = rpe.getResponse(); Log.log(Level.FINER, this, "Exception fetching room list uri: {0} resp code: {1} ", target.getUri().toString(), response.getStatusInfo().getStatusCode() + " " + response.getStatusInfo().getReasonPhrase()); Log.log(Level.FINEST, this, "Exception fetching room list", rpe); } catch (ProcessingException e) { Log.log(Level.FINEST, this, "Exception fetching room list (" + target.getUri().toString() + ")", e); } catch (WebApplicationException ex) { Log.log(Level.FINEST, this, "Exception fetching room list (" + target.getUri().toString() + ")", ex); } // Sadly, badness happened while trying to get the endpoints return Collections.emptyList(); }
/** * Invoke the provided {@code WebTarget}, and resolve/parse the result into * a {@code Site} that the caller can use to create a new * connection to the target room. * * @param target * {@code WebTarget} that includes the required parameters to * retrieve information about available or specified exits. All * of the REST requests that find or work with exits return the * same result structure * @return A populated {@code Site}, or null if the request * failed. */ protected Site getSite(String roomId, WebTarget target) { Log.log(Level.FINER, this, "making request to {0} for room", target.getUri().toString()); Response r = null; try { r = target.request(MediaType.APPLICATION_JSON).get(); // .accept(MediaType.APPLICATION_JSON).get(); if (r.getStatusInfo().getFamily().equals(Response.Status.Family.SUCCESSFUL)) { Site site = r.readEntity(Site.class); return site; } if ( r.getStatus() == 404 ) { // The room doesn't exist anymore. roomCache.remove(roomId); } return null; } catch (ResponseProcessingException rpe) { Response response = rpe.getResponse(); Log.log(Level.FINER, this, "Exception fetching room list uri: {0} resp code: {1} ", target.getUri().toString(), response.getStatusInfo().getStatusCode() + " " + response.getStatusInfo().getReasonPhrase()); Log.log(Level.FINEST, this, "Exception fetching room list", rpe); } catch (ProcessingException e) { Log.log(Level.FINEST, this, "Exception fetching room list (" + target.getUri().toString() + ")", e); } catch (WebApplicationException ex) { Log.log(Level.FINEST, this, "Exception fetching room list (" + target.getUri().toString() + ")", ex); } // Sadly, badness happened while trying to get the endpoints return null; }
public void handleAndRethrowException(final RuntimeException x) { Response response = null; if (x instanceof WebApplicationException) response = ((WebApplicationException)x).getResponse(); else if (x instanceof ResponseProcessingException) response = ((ResponseProcessingException)x).getResponse(); if (response == null) throw x; Error error = null; try { response.bufferEntity(); if (response.hasEntity()) error = response.readEntity(Error.class); if (error != null && DeferredCompletionException.class.getName().equals(error.getClassName())) logger.debug("handleException: " + x, x); else logger.error("handleException: " + x, x); } catch (final Exception y) { logger.error("handleException: " + x, x); logger.error("handleException: " + y, y); } if (error != null) { RemoteExceptionUtil.throwOriginalExceptionIfPossible(error); throw new RemoteException(error); } throw x; }
@Test public void exceptionsShouldMapTimeouts() throws AuthenticationException { Optional<Integer> responseStatus; try { final TenacityConfiguration timeoutConfiguration = new TenacityConfiguration(); timeoutConfiguration.setExecutionIsolationThreadTimeoutInMillis(1); new TenacityPropertyRegister( ImmutableMap.of(DependencyKey.TENACITY_AUTH_TIMEOUT, timeoutConfiguration), new BreakerboxConfiguration()) .register(); when(mockAuthenticator.authenticate(anyString())).thenAnswer((invocation) -> { Thread.sleep(100); return Optional.empty(); }); final Response response = resources.client() .target("/") .request() .header(HttpHeaders.AUTHORIZATION, "Bearer TEST") .get(Response.class); responseStatus = Optional.of(response.getStatus()); } catch (ResponseProcessingException err) { responseStatus = Optional.of(err.getResponse().getStatus()); } assertThat(responseStatus).contains(statusCode); }
@Test(expected = ResponseProcessingException.class) public void testParsingBadResponse() { final Response response = createProxy().createBadJson(); response.readEntity(Person.class); }
@Override public Response toResponse(ResponseProcessingException exception) { ClientErrorException clientErrorException = (ClientErrorException) exception.getCause(); return clientErrorException.getResponse(); }
@Test(expectedExceptions = ResponseProcessingException.class) public void testLoginWithIncorrectCredentials() { client.login(new LoginRequest("incorrect", "account")); }