protected void throwServiceException(ClientResource service, Exception e) throws ServiceException { if (e instanceof ResourceException) { log.error("Unexpected HTTP status code returned: {}", service.getStatus().getCode()); throwServiceException(service.getResponse().getEntityAsText()); } else { log.error("Unexpected Exception", e); throw new ServiceException(e); } } }
/** * Gets authentication result from response entity. * * @param clientResource response container * @return map with user details * @throws org.jtalks.jcommune.plugin.api.exceptions.NoConnectionException * */ private Map<String, String> getAuthResult(ClientResource clientResource) throws NoConnectionException, JAXBException, IOException { if (clientResource.getStatus().getCode() == Status.SUCCESS_OK.getCode() && clientResource.getResponseEntity() != null) { return parseUserDetails(clientResource.getResponseEntity()); } else if (clientResource.getStatus().getCode() == Status.CLIENT_ERROR_NOT_FOUND.getCode()) { return Collections.emptyMap(); } else { throw new NoConnectionException(clientResource.getStatus().toString()); } }
public static void main(String[] args) throws Exception { // Prepare the request ClientResource resource = new ClientResource("http://localhost:8111/"); // Add the client authentication to the call ChallengeScheme scheme = ChallengeScheme.HTTP_BASIC; ChallengeResponse authentication = new ChallengeResponse(scheme, "scott", "tiger"); resource.setChallengeResponse(authentication); // Send the HTTP GET request resource.get(); if (resource.getStatus().isSuccess()) { // Output the response entity on the JVM console resource.getResponseEntity().write(System.out); } else if (resource.getStatus() .equals(Status.CLIENT_ERROR_UNAUTHORIZED)) { // Unauthorized access System.out .println("Access authorized by the server, check your credentials"); } else { // Unexpected status System.out.println("An unexpected status was returned: " + resource.getStatus()); } }
/** * Gets errors from response if request wasn't successful, otherwise return null. * * @param clientResource response container * @param locale locale * @return errors * @throws org.jtalks.jcommune.plugin.api.exceptions.NoConnectionException * * @throws java.io.IOException */ private Map<String, String> getRegistrationResult(ClientResource clientResource, Locale locale) throws NoConnectionException, IOException, JAXBException, UnexpectedErrorException { if (clientResource.getStatus().getCode() == Status.SUCCESS_OK.getCode() && clientResource.getResponseEntity() != null) { return Collections.emptyMap(); } else if (clientResource.getStatus().getCode() == Status.CLIENT_ERROR_BAD_REQUEST.getCode()) { return parseErrors(clientResource.getResponseEntity(), locale); } else if (clientResource.getStatus().getCode() == Status.SERVER_ERROR_INTERNAL.getCode()) { throw new UnexpectedErrorException(); } else { throw new NoConnectionException(clientResource.getStatus().toString()); } }
@Override public Object call(final Class<?> clazz, final String path) throws ServiceException { ClientResource service = createClient(path); try { Representation result = service.delete(); if (service.getStatus().equals(Status.SUCCESS_NO_CONTENT)) { LOGGER.info("Successfully deleted {}", path); } else { JsonRepresentation jsonRepresentation = new JsonRepresentation(result); JSONObject jsonResult = jsonRepresentation.getJsonObject(); LOGGER.error("Unexpected HTTP status code returned: {}", service.getStatus().getCode()); ResponseEntity response = JsonUtil.fromJson(jsonResult, ResponseEntity.class); throw new ServiceException(response); } } catch (JSONException | IOException e) { LOGGER.error("Unexpected Exception", e); throw new ServiceException(e); } return null; }
@Override public <T> String encodeMetadata(MetadataDataType metadataDataType, T instance) throws ServiceException { String encodedRawValue; ClientResource service = createClient(MetadataEndpoints.encodeMetadata(metadataDataType)); try { Representation result = service.post(new StringRepresentation(instance.toString())); JsonRepresentation jsonRepresentation = new JsonRepresentation(result); JSONObject jsonResult = jsonRepresentation.getJsonObject(); if (service.getStatus().equals(Status.SUCCESS_OK)) { encodedRawValue = jsonResult.getString(Field.RAW_VALUE_FIELD); } else { LOGGER.error("Unexpected HTTP status code returned: {}", service.getStatus().getCode()); ResponseEntity response = JsonUtil.fromJson(jsonResult, ResponseEntity.class); throw new ServiceException(response); } } catch (JSONException | IOException e) { LOGGER.error("Unexpected Exception", e); throw new ServiceException(e); } return encodedRawValue; }
@Override public boolean changePassword(String oldPassword, String newPassword) throws ServiceException { boolean wasChanged; ClientResource service = createClient(AccountEndpoints.changeMyPassword()); try { JSONObject jsonObject = new JSONObject() .put(Field.OLD_PASSWORD_FIELD, oldPassword) .put(Field.NEW_PASSWORD_FIELD, newPassword); Representation result = service.post(new JsonRepresentation(jsonObject)); JsonRepresentation jsonRepresentation = new JsonRepresentation(result); JSONObject jsonResult = jsonRepresentation.getJsonObject(); ResponseEntity responseEntity = JsonUtil.fromJson(jsonResult, ResponseEntity.class); if (!service.getStatus().equals(Status.SUCCESS_OK)) { LOGGER.error("Unexpected HTTP status code returned: " + service.getStatus().getCode()); throw new ServiceException(responseEntity); } else { LOGGER.debug(responseEntity.getMessage()); wasChanged = (responseEntity.getCode() == Result.OK.getCode()); } } catch (JSONException | IOException e) { LOGGER.error("Unexpected exception", e); throw new ServiceException(e); } return wasChanged; }
@Override public void sendPasswordResetEmail(String emailAddress) throws ServiceException { ClientResource service = createClient(AccountEndpoints.resetMyPassword()); try { Representation result = service .post(new StringRepresentation(emailAddress, MediaType.TEXT_PLAIN), MediaType.APPLICATION_JSON); JsonRepresentation jsonRepresentation = new JsonRepresentation(result); JSONObject jsonResult = jsonRepresentation.getJsonObject(); ResponseEntity responseEntity = JsonUtil.fromJson(jsonResult, ResponseEntity.class); if (!service.getStatus().equals(Status.SUCCESS_OK)) { LOGGER.error("Unexpected HTTP status code returned: " + service.getStatus().getCode()); throw new ServiceException(responseEntity); } else { LOGGER.debug(responseEntity.getMessage()); } } catch (JSONException | IOException e) { LOGGER.error("Unexpected exception", e); throw new ServiceException(e); } }
@Override public JSONObject decodeMetadata(MetadataDataType metadataDataType, JSONObject jsonObject) throws ServiceException { JSONObject jsonResult; ClientResource service = createClient(MetadataEndpoints.decodeMetadata(metadataDataType)); try { Representation result = service.post(new JsonRepresentation(jsonObject)); JsonRepresentation jsonRepresentation = new JsonRepresentation(result); jsonResult = jsonRepresentation.getJsonObject(); if (service.getStatus().equals(Status.SUCCESS_OK)) { return jsonResult; } else { LOGGER.error("Unexpected HTTP status code returned: {}", service.getStatus().getCode()); ResponseEntity response = JsonUtil.fromJson(jsonResult, ResponseEntity.class); throw new ServiceException(response); } } catch (JSONException | IOException e) { LOGGER.error("Unexpected Exception", e); throw new ServiceException(e); } }
@Override public IAccount fetch(ViewType viewType) throws ServiceException { IAccount account; ClientResource service = createClient(AccountEndpoints.view(viewType)); try { Representation result = service.get(); JsonRepresentation jsonRepresentation = new JsonRepresentation(result); JSONObject jsonResult = jsonRepresentation.getJsonObject(); if (!service.getStatus().equals(Status.SUCCESS_OK)) { ResponseEntity responseEntity = JsonUtil.fromJson(jsonResult, ResponseEntity.class); LOGGER.error("Unexpected HTTP status code returned: " + service.getStatus().getCode()); throw new ServiceException(responseEntity); } else { account = JsonUtil.fromJson(jsonResult, Account.class); } } catch (JSONException | IOException e) { LOGGER.error("Unexpected exception", e); throw new ServiceException(e); } return account; }
@Override public boolean isRealmAvailable(String realm) throws ServiceException { boolean isAvailable = false; ClientResource service = createClient(RegistrationEndpoints.checkRealmAvailability(realm)); try { Representation result = service.get(); JsonRepresentation jsonRepresentation = new JsonRepresentation(result); JSONObject jsonResult = jsonRepresentation.getJsonObject(); ResponseEntity responseEntity = JsonUtil.fromJson(jsonResult, ResponseEntity.class); if (!service.getStatus().equals(Status.SUCCESS_OK)) { LOGGER.error("Unexpected HTTP status code returned: " + service.getStatus().getCode()); throw new ServiceException(responseEntity); } else { isAvailable = (responseEntity.getCode() == Result.OK.getCode()); } } catch (JSONException | IOException e) { LOGGER.error("Unexpected exception", e); throw new ServiceException(e); } return isAvailable; }
/** * Prints the resource's representation. * * @param clientResource * The Restlet client resource. * @throws IOException * @throws ResourceException */ public static void get(ClientResource clientResource) throws IOException, ResourceException { clientResource.get(); if (clientResource.getStatus().isSuccess() && clientResource.getResponse().isEntityAvailable()) { clientResource.getResponseEntity().write(System.out); } }
public static void main(String[] args) throws Exception { ClientResource cr = new ClientResource("http://localhost:8182/path"); cr.addQueryParameter("q", "hello"); cr.get().write(System.out); cr = new ClientResource("http://localhost:8182/path"); cr.addQueryParameter("q", "bye"); cr.get().write(System.out); cr = new ClientResource("http://localhost:8182/path"); cr.addQueryParameter("q", "test"); try { cr.get(); } catch (Exception e) { if (Status.CLIENT_ERROR_NOT_FOUND.equals(cr.getStatus())) { System.out.println("fine."); } else { System.out.println("Should be 404 not found response."); } } } }
public static void main(String[] args) throws ResourceException, IOException { // Prepare the request ClientResource cr = new ClientResource("http://localhost:8182/"); ChallengeRequest c1 = null; // first try: unauthenticated request try { cr.get(); } catch (ResourceException re) { if (Status.CLIENT_ERROR_UNAUTHORIZED.equals(cr.getStatus())) { c1 = getDigestChallengeRequest(cr); } } // second try: authenticated request if (c1 != null) { ChallengeResponse c2 = new ChallengeResponse(c1, cr.getResponse(), "scott", "tiger".toCharArray()); cr.setChallengeResponse(c2); cr.get().write(System.out); } }
@Test public void testOntologyBrowserNoParameters() throws Exception { final ClientResource ontologyBrowserClientResource = new ClientResource(this.getUrl(this.propertyUtil.get(OasProps.PROP_ONTOLOGY_BROWSER_PATH, OasProps.DEF_ONTOLOGY_BROWSER_PATH))); try { ontologyBrowserClientResource.get(); Assert.fail("Expected exception when querying the ontology browser without an ontology URI"); } catch(final ResourceException e) { Assert.assertEquals(Status.CLIENT_ERROR_BAD_REQUEST.getCode(), ontologyBrowserClientResource.getStatus() .getCode()); } } }
@Test public void testOntologyBrowserDirectHtml() throws Exception { final ClientResource ontologyBrowserClientResource = new ClientResource(this.getUrl(this.propertyUtil.get(OasProps.PROP_ONTOLOGY_BROWSER_PATH, OasProps.DEF_ONTOLOGY_BROWSER_PATH))); ontologyBrowserClientResource.getReference().addQueryParameter("ontologyUri", this.ontologyUri); ontologyBrowserClientResource.getReference().addQueryParameter("ontologyVersionUri", this.ontologyVersionUri); ontologyBrowserClientResource.getReference().addQueryParameter("directChildrenOnly", "true"); final Representation representation = ontologyBrowserClientResource.get(MediaType.TEXT_HTML); Assert.assertNotNull(representation); Assert.assertEquals(Status.SUCCESS_OK.getCode(), ontologyBrowserClientResource.getStatus().getCode()); // this.log.trace("result={}", representation.getText()); final String resultsText = representation.getText(); this.assertFreemarker(resultsText); Assert.assertTrue(resultsText.contains("OAS-testwebsite test Ajaxified Ontology Browser template")); }
@Test public void testOntologyBrowserDirectJson() throws Exception { final ClientResource ontologyBrowserClientResource = new ClientResource(this.getUrl(this.propertyUtil.get(OasProps.PROP_ONTOLOGY_BROWSER_PATH, OasProps.DEF_ONTOLOGY_BROWSER_PATH))); ontologyBrowserClientResource.getReference().addQueryParameter("ontologyUri", this.ontologyUri); ontologyBrowserClientResource.getReference().addQueryParameter("ontologyVersionUri", this.ontologyVersionUri); ontologyBrowserClientResource.getReference().addQueryParameter("directChildrenOnly", "true"); final Representation representation = ontologyBrowserClientResource.get(MediaType.APPLICATION_JSON); Assert.assertNotNull(representation); Assert.assertEquals(Status.SUCCESS_OK.getCode(), ontologyBrowserClientResource.getStatus().getCode()); // this.log.trace("result={}", representation.getText()); }
@Test public void testOntologyBrowserDirectRdfXml() throws Exception { final ClientResource ontologyBrowserClientResource = new ClientResource(this.getUrl(this.propertyUtil.get(OasProps.PROP_ONTOLOGY_BROWSER_PATH, OasProps.DEF_ONTOLOGY_BROWSER_PATH))); ontologyBrowserClientResource.getReference().addQueryParameter("ontologyUri", this.ontologyUri); ontologyBrowserClientResource.getReference().addQueryParameter("ontologyVersionUri", this.ontologyVersionUri); ontologyBrowserClientResource.getReference().addQueryParameter("directChildrenOnly", "true"); final Representation representation = ontologyBrowserClientResource.get(MediaType.APPLICATION_RDF_XML); Assert.assertNotNull(representation); Assert.assertEquals(Status.SUCCESS_OK.getCode(), ontologyBrowserClientResource.getStatus().getCode()); // this.log.trace("result={}", representation.getText()); }