private ToStateTransitions load( LoginData loginData, ProjectGroupConfig boardConfig, Issue issue, String toState) throws IOException { final UriBuilder builder = UriBuilder.fromUri(boardConfig.getJiraUrl()) .path("rest") .path("api") .path("2") .path("issue") .path(issue.getKey()) .path("transitions") .queryParam("issueIdOrKey", issue.getKey()); final WebTarget target = loginData.getClient().target(builder); final Response response = target.request(MediaType.APPLICATION_JSON_TYPE).get(); if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) { throw new IOException( "Error looking up the transitions for issue " + issue.getKey() + ": " + response.readEntity(String.class)); } Map<String, Transition> states = new HashMap<>(); ModelNode modelNode = ModelNode.fromJSONString(response.readEntity(String.class)); for (ModelNode transitionNode : modelNode.get("transitions").asList()) { Transition transition = new Transition(transitionNode.get("id").asInt(), transitionNode.get("name").asString()); states.put(transition.toState, transition); } ToStateTransitions toStateTransitions = new ToStateTransitions(issue.getState(), states); return toStateTransitions; }
private void testResumeException(final String path, final String entity) throws Exception { final WebTarget errorResource = target("errorResource"); final Future<Response> suspended = errorResource.path("suspend").request().async().get(); final Response response = errorResource.path(path).request().get(); assertThat(response.getStatus(), equalTo(200)); assertThat(response.readEntity(String.class), equalTo("ok")); final Response suspendedResponse = suspended.get(); assertThat(suspendedResponse.getStatus(), equalTo(500)); if (entity != null) { assertThat(suspendedResponse.readEntity(String.class), equalTo(entity)); } suspendedResponse.close(); // Check there is no NPE. for (final LogRecord record : getLoggedRecords()) { final Throwable thrown = record.getThrown(); if (thrown != null && thrown instanceof NullPointerException) { fail("Unexpected NPE."); } } }
public Post fetch(Session session, NextRequest next) { LOGGER.debug( ((next == null) ? "Initial request" : "next request: " + next) + "/n Session: " + session.toString()); WebTarget target = createInitialFetchTarget(); if (next != null) { target = fillNextParameters(next, target); } Invocation.Builder request = target.request(); request = appendCookies(session, request); Response response = request.post( Entity.entity( new NextToken.NextTokenBuilder().createNextToken(), MediaType.APPLICATION_JSON_TYPE)); response.bufferEntity(); try { String responseJson = response.readEntity(String.class); LOGGER.debug("Full response: " + responseJson); } catch (Exception ex) { ex.printStackTrace(); } Post post = response.readEntity(Post.class); response.close(); return post; }
public String getSting(String uri) throws BeeterClientException { WebTarget target = client.target(uri); Response response = target.request().get(); if (response.getStatus() == Response.Status.OK.getStatusCode()) return response.readEntity(String.class); else throw new BeeterClientException(response.readEntity(String.class)); }
@Test public void testUpdateNote() { final Note newNote = new Note(); newNote.setBody("updateme"); Response responseMsg = target .path("notes") .request(MediaType.APPLICATION_JSON_TYPE) .post(Entity.entity(newNote, MediaType.APPLICATION_JSON_TYPE)); Note testNote = responseMsg.readEntity(Note.class); Assert.assertTrue("Note should have id greater than 0.", testNote.getId() > 0); final int testId = testNote.getId(); final String testBody = "updated"; testNote.setBody(testBody); responseMsg = target .path("notes/" + testId) .request(MediaType.APPLICATION_JSON_TYPE) .put(Entity.entity(testNote, MediaType.APPLICATION_JSON_TYPE)); testNote = responseMsg.readEntity(Note.class); Assert.assertEquals("Note has unexpected id.", testId, testNote.getId()); Assert.assertEquals("Note has unexpected body.", testBody, testNote.getBody()); }
private static void removeBook() { ResteasyClient client = new ResteasyClientBuilder().build(); Response response = client .target("http://localhost:8080/v1/api") .path("bookstore/book") .path("1") .request() .header("Authorization", "Basic " + getBasicAuthenticationEncoding()) .accept(MediaType.APPLICATION_JSON) .delete(); System.out.println(response.getStatus()); System.out.println(response.readEntity(String.class)); System.out.println("---------------------------------------"); response = client .target("http://localhost:8080/v1/api") .path("bookstore/book") .path("1") .request() .header("Authorization", "Basic " + getBasicAuthenticationEncoding()) .accept(MediaType.APPLICATION_XML) .delete(); System.out.println(response.getStatus()); System.out.println(response.readEntity(String.class)); }
private static void updateBook() { ResteasyClient client = new ResteasyClientBuilder().build(); Publisher publisher = new Publisher(1, "陕西师范大学出版社"); Book book = new Book(1, "金庸", "987634556", "书剑恩仇录", publisher); Response response = client .target("http://localhost:8080/v1/api") .path("bookstore/book") .request() .header("Authorization", "Basic " + getBasicAuthenticationEncoding()) .accept(MediaType.APPLICATION_JSON) .put(Entity.entity(book, MediaType.APPLICATION_JSON)); System.out.println(response.getStatus()); System.out.println(response.readEntity(String.class)); System.out.println("---------------------------------------"); response = client .target("http://localhost:8080/v1/api") .path("bookstore/book") .request() .header("Authorization", "Basic " + getBasicAuthenticationEncoding()) .accept(MediaType.APPLICATION_XML) .put(Entity.entity(book, MediaType.APPLICATION_XML)); System.out.println(response.getStatus()); System.out.println(response.readEntity(String.class)); }
private static void getBooksSet() { ResteasyClient client = new ResteasyClientBuilder().build(); System.out.println("----------------JSON-----------------------"); Response response = client .target("http://localhost:8080/v1/api") .path("bookstore/set") .request() .accept(MediaType.APPLICATION_JSON) .get(); System.out.println(response.getStatus()); System.out.println(response.readEntity(String.class)); System.out.println("----------------JSNOP-----------------------"); response = client .target("http://localhost:8080/v1/api") .path("bookstore/set") .queryParam("callback", "books") .request() .accept(MediaType.APPLICATION_JSON) .get(); System.out.println(response.getStatus()); System.out.println(response.readEntity(String.class)); System.out.println("----------------XML-----------------------"); response = client .target("http://localhost:8080/v1/api") .path("bookstore/set") .request() .accept(MediaType.APPLICATION_XML) .get(); System.out.println(response.getStatus()); System.out.println(response.readEntity(String.class)); }
private static void addBooksMap() { ResteasyClient client = new ResteasyClientBuilder().build(); Publisher publisher = new Publisher(1, "陕西师范大学出版社"); Map<String, Book> books = new HashMap<String, Book>(); Book book; for (int i = 1; i <= 20; i++) { book = new Book(i, "金庸", "987634556", "书剑恩仇录", publisher); books.put(String.valueOf(i), book); } Response response = client .target("http://localhost:8080/v1/api") .path("bookstore/map") .request() .header("Authorization", "Basic " + getBasicAuthenticationEncoding()) .accept(MediaType.APPLICATION_JSON) .post(Entity.entity(books, MediaType.APPLICATION_JSON)); System.out.println(response.getStatus()); System.out.println(response.readEntity(String.class)); System.out.println("---------------------------------------"); response = client .target("http://localhost:8080/v1/api") .path("bookstore/map") .request() .header("Authorization", "Basic " + getBasicAuthenticationEncoding()) .accept(MediaType.APPLICATION_XML) .post(Entity.entity(books, MediaType.APPLICATION_JSON)); System.out.println(response.getStatus()); System.out.println(response.readEntity(String.class)); }
@Test public void testAppLoad() throws Exception { clearCache(); startDeployment(); init(); stopDeployment(); startDeployment(); ResteasyClient client = new ResteasyClientBuilder().build(); WebTarget target = client.target(generateBaseUrl()); SkeletonKeyAdminClient admin = new SkeletonKeyClientBuilder().username("wburke").password("geheim").idp(target).admin(); StoredUser newUser = new StoredUser(); newUser.setName("John Smith"); newUser.setUsername("jsmith"); newUser.setEnabled(true); Map creds = new HashMap(); creds.put("password", "foobar"); newUser.setCredentials(creds); Response response = admin.users().create(newUser); User user = response.readEntity(User.class); response = admin.roles().create("user"); Role role = response.readEntity(Role.class); Projects projects = admin.projects().query("Skeleton Key"); Project project = projects.getList().get(0); admin.projects().addUserRole(project.getId(), user.getId(), role.getId()); admin = new SkeletonKeyClientBuilder().username("jsmith").password("foobar").idp(target).admin(); response = admin.roles().create("error"); Assert.assertEquals(403, response.getStatus()); stopDeployment(); }
public String createEdit(Curso curso) { if (curso == null) { // Curso ainda não criado. GenericBean.resetSessionScopedBean("editarCursoBean"); GenericBean.sendRedirect(PathRedirect.cadastrarCurso); } else { Response response = service.consultarCurso(curso.getIdCurso()); // Código de resposta do serviço. int statusCode = response.getStatus(); if (statusCode == HttpStatus.SC_OK) { // Http Code: 200. Resposta para cadastro realizado com sucesso. Curso cursoResponse = response.readEntity(Curso.class); // Curso encontrado. this.curso = cursoResponse; } else { // Http Code: 404. Curso inexistente. Erro erro = response.readEntity(Erro.class); GenericBean.setMessage("erro.cursoInexistente", FacesMessage.SEVERITY_ERROR); } } return PathRedirect.cadastrarCurso; }
private FileData<PatientVisitDTO> doPut(FileData<PatientVisitDTO> entity) throws RestLoaderException { Response response = hbRestClient.doPut(entity.getEntity()); try { switch (response.getStatus()) { case 200: PayloadStatus result = response.readEntity(PayloadStatus.class); String id = HBUtil.getIdFromURI(result.getIdentifier()); entity.setSuccess(true); entity.setResult(DataLoaderConstants.SUCCESS_MSG + id); break; case 400: RestApiError badRequestError = response.readEntity(RestApiError.class); entity.setSuccess(false); entity.setResult(DataLoaderConstants.ERROR_MSG + badRequestError.toString()); break; case 404: RestApiError notFoundError = response.readEntity(RestApiError.class); entity.setSuccess(false); entity.setResult(DataLoaderConstants.ERROR_MSG + notFoundError.toString()); break; default: } } catch (MessageBodyProviderNotFoundException e) { log.warning(e.getMessage()); entity.setSuccess(false); entity.setResult(DataLoaderConstants.UNKNOWN_ERROR_MSG); } return entity; }
@Test public void testShouldReturnTwoRegionNamesInEssex() throws OpenStackException { // given OpenStackRegionImpl openStackRegion = new OpenStackRegionImpl(); Client client = mock(Client.class); openStackRegion.setClient(client); SystemPropertiesProvider systemPropertiesProvider = mock(SystemPropertiesProvider.class); openStackRegion.setSystemPropertiesProvider(systemPropertiesProvider); String token = "123456789"; String responseError = "{\n" + " \"error\": {\n" + " \"message\": \"The action you have requested has not been implemented.\",\n" + " \"code\": 501,\n" + " \"title\": null\n" + " }\n" + "}"; String url = "http://domain.com/v2.0/tokens/" + token + "/endpoints"; String urlEssex = "http://domain.com/v2.0/tokens"; WebTarget webResource = mock(WebTarget.class); WebTarget webResourceEssex = mock(WebTarget.class); Invocation.Builder builder = mock(Invocation.Builder.class); Invocation.Builder builderEssex = mock(Invocation.Builder.class); Response clientResponse = mock(Response.class); Response clientResponseEssex = mock(Response.class); // when when(systemPropertiesProvider.getProperty(SystemPropertiesProvider.KEYSTONE_URL)) .thenReturn("http://domain.com/v2.0/"); when(client.target(url)).thenReturn(webResource); when(webResource.request(MediaType.APPLICATION_JSON)).thenReturn(builder); when(builder.get()).thenReturn(clientResponse); when(clientResponse.getStatus()).thenReturn(501); when(clientResponse.readEntity(String.class)).thenReturn(responseError); when(client.target(urlEssex)).thenReturn(webResourceEssex); when(webResourceEssex.request(MediaType.APPLICATION_JSON)).thenReturn(builderEssex); when(builderEssex.accept(MediaType.APPLICATION_JSON)).thenReturn(builderEssex); when(builderEssex.header("Content-type", MediaType.APPLICATION_JSON)).thenReturn(builderEssex); when(builderEssex.post(Entity.entity(anyString(), MediaType.APPLICATION_JSON))) .thenReturn(clientResponseEssex); when(clientResponseEssex.getStatus()).thenReturn(200); when(clientResponseEssex.readEntity(String.class)).thenReturn(RESPONSE_ESSEX); List<String> result = openStackRegion.getRegionNames(token); // then assertNotNull(result); assertEquals(2, result.size()); assertEquals("RegionOne", result.get(0)); assertEquals("RegionTwo", result.get(1)); }
private EmoticonListResponse requestEmoticons(WebTarget emoticonTarget) { Response response = emoticonTarget.request().get(); if (response.getStatus() != Response.Status.OK.getStatusCode()) { throw new RuntimeException(response.readEntity(String.class)); } return response.readEntity(EmoticonListResponse.class); }
public String getStings(String uri) throws BeeterClientException { if (uri == null) { uri = getLink(authToken.getLinks(), "current-stings").getUri().toString(); } WebTarget target = client.target(uri); Response response = target.request().get(); if (response.getStatus() == Response.Status.OK.getStatusCode()) return response.readEntity(String.class); else throw new BeeterClientException(response.readEntity(String.class)); }
private void assertSHA1(String path, Response dataResponse) { String sha1Path = path + ".sha1"; Response sha1Response = context.client().target(sha1Path).request().get(); assertResponse(sha1Path, sha1Response, MediaType.TEXT_PLAIN); try (InputStream is = dataResponse.readEntity(InputStream.class)) { byte[] data = IOUtils.toByteArray(is); String sha1 = sha1Response.readEntity(String.class); assertEquals("SHA-1 " + path, sha1, DigestUtils.sha1Hex(data)); } catch (IOException ex) { throw new RuntimeException("Error checking SHA-1 of " + path, ex); } }
@Test public void createTransactionReturnsOk() { // create "cars" transaction Response response = client .path("/transactionservice/transaction/10") .request() .put(Entity.json(new Transaction("cars", new BigDecimal(5000), 0l))); assertEquals(200, response.getStatus()); assertEquals( TransactionService.OperationResult.OK, response.readEntity(TransactionService.OperationResult.class)); // create "shopping" transaction response = client .path("/transactionservice/transaction/11") .request() .put(Entity.json(new Transaction("shopping", new BigDecimal(10000), 10l))); assertEquals(200, response.getStatus()); assertEquals( TransactionService.OperationResult.OK, response.readEntity(TransactionService.OperationResult.class)); // get "cars" transactions response = client.path("/transactionservice/type/cars").request().get(); assertEquals(200, response.getStatus()); @SuppressWarnings("unchecked") List<Integer> ids = response.readEntity(List.class); assertEquals(1, ids.size()); assertEquals(10, ids.get(0).intValue()); // get "sum" for transaction 10 response = client.path("/transactionservice/sum/10").request().get(); assertEquals(200, response.getStatus()); AggregatorService.Sum sum = response.readEntity(AggregatorService.Sum.class); assertEquals(15000, sum.getSum().intValue()); // get "sum" for transaction 11 response = client.path("/transactionservice/sum/11").request().get(); assertEquals(200, response.getStatus()); sum = response.readEntity(AggregatorService.Sum.class); assertEquals(10000, sum.getSum().intValue()); }
private InputStream download(UUID sessionId, String dataId) throws FileBrokerException { String datasetPath = "sessions/" + sessionId.toString() + "/datasets/" + dataId; WebTarget datasetTarget = fileBrokerTarget.path(datasetPath); Response response = datasetTarget.request().get(Response.class); if (!RestUtils.isSuccessful(response.getStatus())) { throw new FileBrokerException( "get input stream failed: " + response.getStatus() + " " + response.readEntity(String.class) + " " + datasetTarget.getUri()); } return response.readEntity(InputStream.class); }
/** * Ensures that the response has a "success" status code {@code 2xx}. * * @throws HttpResponseException if the response does not have a {@code 2xx} status code * @throws IOException if the response entity parsing has failed */ public void ensure2xxStatus() throws HttpResponseException, IOException { if (response.getStatus() / 100 != 2) { final String message; if (MediaType.TEXT_PLAIN_TYPE.equals(response.getMediaType())) { message = response.readEntity(String.class); } else if (MediaType.TEXT_XML_TYPE.equals(response.getMediaType()) || MediaType.APPLICATION_XML_TYPE.equals(response.getMediaType()) || MediaType.APPLICATION_JSON_TYPE.equals(response.getMediaType())) { message = response.readEntity(AcknowlegementType.class).getMessage(); } else { message = response.toString(); } throw new HttpResponseException(response.getStatus(), message); } }
@Test public void testOverride() throws Exception { final Response response = target().path("/").request("text/plain").post(Entity.text("content")); assertEquals("content", response.readEntity(String.class)); assertEquals(HEADER_VALUE_SERVER, response.getHeaderString(HEADER_NAME)); }
@Test public void testBoolean() { Response response = client.target(generateURL("/boolean")).request().post(Entity.text("true")); Assert.assertEquals(response.getStatus(), 200); Assert.assertEquals(response.readEntity(String.class), "true"); response.close(); }
/** * Get apps. * * <p>URL (GET): * {scheme}://{host}:{port}/{contextRoot}/appstore/apps?namespace={namespace}&categoryid={categoryid} * * @param namespace * @param categoryId * @return * @throws ClientException */ public List<AppManifestDTO> getApps(String namespace, String categoryId) throws ClientException { List<AppManifestDTO> apps = null; Response response = null; try { WebTarget target = getRootPath().path("appstore/apps"); if (categoryId != null) { target.queryParam("namespace", namespace); } if (categoryId != null) { target.queryParam("categoryId", categoryId); } Builder builder = target.request(MediaType.APPLICATION_JSON); response = updateHeaders(builder).get(); checkResponse(response); apps = response.readEntity(new GenericType<List<AppManifestDTO>>() {}); } catch (ClientException e) { handleException(e); } finally { IOUtil.closeQuietly(response, true); } if (apps == null) { apps = Collections.emptyList(); } return apps; }
/** * Get an app. * * <p>URL (GET): {scheme}://{host}:{port}/{contextRoot}/appstore/apps/{appid} * * @param appId * @return * @throws ClientException */ public boolean appExists(String appId) throws ClientException { Response response = null; try { Builder builder = getRootPath() .path("appstore/apps") .path(appId) .path("exists") .request(MediaType.APPLICATION_JSON); response = updateHeaders(builder).get(); checkResponse(response); String responseString = response.readEntity(String.class); ObjectMapper mapper = createObjectMapper(false); Map<?, ?> result = mapper.readValue(responseString, Map.class); if (result != null && result.containsKey("exists")) { // $NON-NLS-1$ Object value = result.get("exists"); // $NON-NLS-1$ if (value instanceof Boolean) { return (boolean) value; } } } catch (ClientException | IOException e) { handleException(e); } finally { IOUtil.closeQuietly(response, true); } return false; }
@Test // @Ignore public void shouldGetDoctors() throws IOException { URI uri = UriBuilder.fromUri("http://localhost/").port(8282).build(); // Create an HTTP server listening at port 8282 HttpServer server = HttpServer.create(new InetSocketAddress(uri.getPort()), 0); // Create a handler wrapping the JAX-RS application HttpHandler handler = RuntimeDelegate.getInstance() .createEndpoint(new TestApplicationConfig01(), HttpHandler.class); // Map JAX-RS handler to the server root server.createContext(uri.getPath(), handler); // Start the server server.start(); Client client = ClientBuilder.newClient(); // Valid URIs Response response = client.target("http://localhost:8282/doctor").request().get(); assertEquals(200, response.getStatus()); System.out.println(response.readEntity(String.class)); // Stop HTTP server server.stop(0); }
@Test public void AddBookNoTitle() { Response response = addBook("author1", null, new Date(), "1234"); assertEquals(400, response.getStatus()); String message = response.readEntity(String.class); assertTrue(message.contains("title is a required field")); }
private void _testInflectorInjection(final String path) { final Response response = target("resource").path(path).request().get(); assertEquals(200, response.getStatus()); assertEquals( "requestProvider_request_responseProvider_response", response.readEntity(String.class)); }
/** * Tests SecurityContext in filter. * * @throws Exception Thrown when request processing fails in the application. */ @Test public void testContainerSecurityContext() throws Exception { Response response = target().path("test").request().header(SKIP_FILTER, "true").get(); assertEquals(200, response.getStatus()); String entity = response.readEntity(String.class); Assert.assertTrue(!entity.equals(PRINCIPAL_NAME)); }
/** * Tests SecurityContext in filter. * * @throws Exception Thrown when request processing fails in the application. */ @Test public void testSecurityContextFilter() throws Exception { Response response = target().path("test").request().get(); assertEquals(200, response.getStatus()); String entity = response.readEntity(String.class); assertEquals(PRINCIPAL_NAME, entity); }
@Before public void setUp() { RegionCache regionCache = new RegionCache(); regionCache.clear(); openStackRegion = new OpenStackRegionImpl(); Client client = mock(Client.class); WebTarget webResource = mock(WebTarget.class); builder = mock(Invocation.Builder.class); clientResponse = mock(Response.class); Response clientResponseAdmin = mock(Response.class); // when when(webResource.request(MediaType.APPLICATION_JSON)).thenReturn(builder); when(builder.accept(MediaType.APPLICATION_JSON)).thenReturn(builder); when(client.target(anyString())).thenReturn(webResource); openStackRegion.setClient(client); systemPropertiesProvider = mock(SystemPropertiesProvider.class); openStackRegion.setSystemPropertiesProvider(systemPropertiesProvider); String responseJSON = "{\"access\": {\"token\": {\"issued_at\": \"2014-01-13T14:00:10.103025\", \"expires\": \"2014-01-14T14:00:09Z\"," + "\"id\": \"ec3ecab46f0c4830ad2a5837fd0ad0d7\", \"tenant\": { \"description\": null, \"enabled\": true, \"id\": \"08bed031f6c54c9d9b35b42aa06b51c0\"," + "\"name\": \"admin\" } }, \"serviceCatalog\": []}}}"; when(builder.post(Entity.entity(anyString(), MediaType.APPLICATION_JSON))) .thenReturn(clientResponseAdmin); when(clientResponseAdmin.getStatus()).thenReturn(200); when(clientResponseAdmin.readEntity(String.class)).thenReturn(responseJSON); }
@Test public void testSetAdminGroupsSuccess() throws Exception { Task task = new Task(); task.setId(taskId); when(deploymentFeClient.setSecurityGroups(eq(deploymentId), anyListOf(String.class))) .thenReturn(task); ResourceList<String> adminGroups = new ResourceList<>( Arrays.asList(new String[] {"tenant\\adminGroup1", "tenant\\adminGroup2"})); Response response = client() .target(deploymentRoutePath) .request() .post(Entity.entity(adminGroups, MediaType.APPLICATION_JSON_TYPE)); assertThat(response.getStatus(), is(200)); Task responseTask = response.readEntity(Task.class); assertThat(responseTask, is(task)); assertThat(new URI(responseTask.getSelfLink()).isAbsolute(), is(true)); assertThat(responseTask.getSelfLink().endsWith(taskRoutePath), is(true)); }