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)); }
@Test public void testPostEmployee() { if (null == cookie) { fail("cannot login!!!"); } Employee ep1 = generateEmployee(); try { ResteasyClient client = new ResteasyClientBuilder().build(); WebTarget target = client.target(baseUrl + "/rest/ag/employee"); client.register(new CookieRequestFilter(cookie)); Response response = target.request().post(Entity.entity(ep1, "application/json")); if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } Employee value = response.readEntity(Employee.class); System.out.println("Server response : \n"); System.out.println(value.toString()); assertEquals("same first name", "Special", value.getFirstName()); client.close(); } catch (Exception e) { e.printStackTrace(); } }
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 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)); }
@Test public void testCMD() throws Exception { Authentication auth = new SkeletonKeyClientBuilder() .username("wburke") .password("geheim") .authentication("Skeleton Key"); ResteasyClient client = new ResteasyClient(); WebTarget target = client.target(generateBaseUrl()); String tiny = target.path("tokens").path("url").request().post(Entity.json(auth), String.class); System.out.println(tiny); System.out.println("tiny.size: " + tiny.length()); Security.addProvider(new BouncyCastleProvider()); KeyPair keyPair = KeyPairGenerator.getInstance("RSA", "BC").generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); X509Certificate cert = KeyTools.generateTestCertificate(keyPair); byte[] signed = p7s(privateKey, cert, null, tiny.getBytes()); CMSSignedData data = new CMSSignedData(signed); byte[] bytes = (byte[]) data.getSignedContent().getContent(); System.out.println("BYTES: " + new String(bytes)); System.out.println("size:" + signed.length); System.out.println("Base64.size: " + Base64.encodeBytes(signed).length()); SignerInformation signer = (SignerInformation) data.getSignerInfos().getSigners().iterator().next(); System.out.println("valid: " + signer.verify(cert, "BC")); }
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(); }
@Test public void testDispatchDynamic43() throws Exception { ResteasyClient client = new ResteasyClientBuilder().build43(); Invocation.Builder request = client.target(generateURL("/test/dispatch/dynamic")).request(); Response response = request.get(); assertEquals(HttpResponseCodes.SC_OK, response.getStatus()); assertEquals("Wrong content of response", "forward", response.readEntity(String.class)); }
public static <T> void save(String path, T data) { ResteasyClient client = new ResteasyClientBuilder().build(); Response response = client .target(SALES_ORDER_APP + path) .request() .post(Entity.entity(data, MediaType.APPLICATION_JSON)); System.out.println(response.getStatus()); }
public static <T> List<Object> getSaleOrdersList(String path) { ResteasyClient client = new ResteasyClientBuilder().build(); ArrayList<SaleOrders> response = client .target(SALES_ORDER_APP + path) .request() .get(new GenericType<ArrayList<SaleOrders>>() {}); Object[] array = response.toArray(); return Arrays.asList(array); }
@Test public void testMe() throws Exception { ResteasyClient client = new ResteasyClient(); MyTest proxy = client.target(TestPortProvider.generateURL("")).proxy(MyTest.class); try { proxy.postIt("hello"); Assert.fail(); } catch (NotAuthorizedException e) { Assert.assertEquals(401, e.getResponse().getStatus()); } client.close(); }
/** * Save CSV or XML file with the storage component * * @expects "GEMO portal wide params" in portal-ext.properties: * gemo.storage.upload.url=http://?????????/service/storage/upload * gemo.storage.search.query.url=http://?????????/service/storage/ search?query= * @param csvXmlFile the file * @return the url * @throws SystemException the system exception * @throws URISyntaxException the uRI syntax exception * @throws IOException * @throws PortalException */ public static String uploadToStorage(UploadedFile csvXmlFile) throws SystemException, URISyntaxException, IOException, PortalException, NullPointerException { // grab props from constants final String storage_uri = PrefsPropsUtil.getString(PortalProperties.GEMO_STORAGE_URL, "http://localhost/storage"); final String upload_uri = PrefsPropsUtil.getString( PortalProperties.GEMO_STORAGE_UPLOAD_URL, "http://localhost/storage/upload"); final String upload_base64_uri = PrefsPropsUtil.getString( PortalProperties.GEMO_STORAGE_UPLOADBASE64_URL, "http://localhost:8080/storage/uploadbase64"); final String query_uri = PrefsPropsUtil.getString( PortalProperties.GEMO_STORAGE_SEARCH_QUERY_URL, "http://localhost/storage/search?query="); final String tableName = NameUtils.UsersUsableUniqueNamefromFile(csvXmlFile); try { byte[] bytes = csvXmlFile.getBytes(); String theBase64Bytes = Base64.encodeBytes(bytes); ResteasyClient client = new ResteasyClientBuilder().build(); ResteasyWebTarget target = client.target(upload_base64_uri); MultipartFormDataOutput mdo = new MultipartFormDataOutput(); mdo.addFormData("tableName", tableName, MediaType.TEXT_PLAIN_TYPE); mdo.addFormData("fileName", csvXmlFile.getName(), MediaType.TEXT_PLAIN_TYPE); mdo.addFormData("fileBase64", theBase64Bytes, MediaType.TEXT_PLAIN_TYPE.withCharset("utf-8")); GenericEntity<MultipartFormDataOutput> entity = new GenericEntity<MultipartFormDataOutput>(mdo) {}; Response r = target.request().post(Entity.entity(entity, MediaType.MULTIPART_FORM_DATA_TYPE)); String obj = r.readEntity(String.class); LOG.debug("Storage returned: " + obj); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { // httpclient.getConnectionManager().shutdown(); } return query_uri + "select * from " + tableName + " LIMIT 10"; }
/** allow to reset proxy as per security needs */ @Override public void setProxy() { ResteasyClient client = null; String urlString = url.toString(); Class<P> proxyClass = this.getProxyClass(); if (useAuth()) { String user = properties.getProperty(USER_PROPERTY); String password = properties.getProperty(PASSWORD_PROPERTY); client = (ResteasyClient) ClientBuilder.newClient().register(new Authenticator(user, password)); } else { client = (ResteasyClient) ClientBuilder.newClient(); } proxy = client.target(urlString).proxy(proxyClass); }
public static void main(String args[]) throws Exception { Configuration config = OtrBootstrap.init(); File fLibrary = new File(config.getString(TestPropertyKeys.dirTaggerDst)); File fBackup = new File(config.getString(TestPropertyKeys.dirMcBackup)); String restUrl = config.getString("url.otrseries"); logger.info("Connectiong to " + restUrl); ResteasyClient client = new ResteasyClientBuilder().build(); ResteasyWebTarget target = client.target(restUrl); OtrSeriesRest rest = target.proxy(OtrSeriesRest.class); ; McLibraryTagger tagger = new McLibraryTagger(rest, fBackup, null); tagger.scan(fLibrary); }
/** * @tpTestDetails This tests decorators in general with the @Stylesheet annotation * @tpPassCrit The response contains expected xml-stylesheet header * @tpSince RESTEasy 3.0.16 */ @Test public void testStylesheet() throws Exception { ResteasyWebTarget target = client.target(generateURL("/test/stylesheet")); String response = target.request().get(String.class); logger.info(response); Assert.assertTrue( "The response doesn't contain the expected xml-stylesheet header", response.contains("<?xml-stylesheet")); }
protected Response spnegoLogin(String username, String password) { SpnegoAuthenticator.bypassChallengeJavascript = true; driver.navigate().to(KERBEROS_APP_URL); String kcLoginPageLocation = driver.getCurrentUrl(); String location = "http://localhost:8081/auth/realms/test/protocol/openid-connect/auth?response_type=code&client_id=kerberos-app&redirect_uri=http%3A%2F%2Flocalhost%3A8081%2Fkerberos-portal&state=0%2F88a96ddd-84fe-4e77-8a46-02394d7b3a7d&login=true"; // Request for SPNEGO login sent with Resteasy client spnegoSchemeFactory.setCredentials(username, password); Response response = client.target(kcLoginPageLocation).request().get(); SpnegoAuthenticator.bypassChallengeJavascript = false; if (response.getStatus() == 302) { if (response.getLocation() == null) return response; String uri = response.getLocation().toString(); if (uri.contains("login-actions/required-action")) { response = client.target(uri).request().get(); } } return response; }
@Test public void testNotAuthenticated() { { // assuming @RolesAllowed is on class level. Too lazy to test it all! String newUser = "******"user\" : { \"username\" : \"wburke\", \"name\" : \"Bill Burke\", \"email\" : \"[email protected]\", \"enabled\" : true, \"credentials\" : { \"password\" : \"geheim\" }} }"; ResteasyClient client = new ResteasyClient(deployment.getProviderFactory()); Response response = client.target(generateURL("/users")).request().post(Entity.json(newUser)); Assert.assertEquals(response.getStatus(), 403); response.close(); } { String newRole = "{ \"role\" : { \"name\" : \"admin\"} }"; ResteasyClient client = new ResteasyClient(deployment.getProviderFactory()); Response response = client.target(generateURL("/roles")).request().post(Entity.json(newRole)); Assert.assertEquals(response.getStatus(), 403); response.close(); } { String newProject = "{ \"project\" : { \"id\" : \"5\", \"name\" : \"Resteasy\", \"description\" : \"The Best of REST\", \"enabled\" : true } }"; ResteasyClient client = new ResteasyClient(deployment.getProviderFactory()); Response response = client.target(generateURL("/projects")).request().post(Entity.json(newProject)); Assert.assertEquals(response.getStatus(), 403); response.close(); } }
private String callNeo(String query) { ResteasyClient client = new ResteasyClientBuilder().build(); ResteasyWebTarget target = client.target("http://" + getStrNeoHost() + ":7474/db/data/cypher"); String token = "neo4j" + ":" + "neo4j"; String base64Token = ""; try { base64Token = DatatypeConverter.printBase64Binary(token.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } Response response = target .request() .header("Authorization", "Basic " + base64Token) .header("Accept", "application/json; charset=UTF-8") .header("Content-Type", "application/json") .post(Entity.entity(query, "application/json")); String value = response.readEntity(String.class); response.close(); return value; }
@Test public void testSignedAuth() throws Exception { // Use our own providerFactory to test json context provider ResteasyProviderFactory providerFactory = new ResteasyProviderFactory(); RegisterBuiltin.register(providerFactory); ResteasyClient client = new ResteasyClient(providerFactory); 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()); String signed = new SkeletonKeyClientBuilder() .username("jsmith") .password("foobar") .idp(target) .obtainSignedToken("Skeleton Key"); System.out.println(signed); PKCS7SignatureInput input = new PKCS7SignatureInput(signed); input.setCertificate(certificate); Assert.assertTrue(input.verify()); }
@Test public void testReadProductRelease() throws Exception { String relativeUrl = "/product-releases/" + productReleaseId; stubFor( get(urlEqualTo(CONTEXT_URL + relativeUrl)) .willReturn( aResponse() .withHeader("Content-Type", "application/json") .withBody(readResponseBodyFromTemplate("product-releases-1.json")))); Response response = client.target(pncUrl + relativeUrl).request().get(); Singleton<ProductReleaseRest> responseEntity = response.readEntity(new GenericType<Singleton<ProductReleaseRest>>() {}); assertEquals(productReleaseId, responseEntity.getContent().getId()); }
@Test public void spnegoNotAvailableTest() throws Exception { initHttpClient(false); SpnegoAuthenticator.bypassChallengeJavascript = true; driver.navigate().to(KERBEROS_APP_URL); String kcLoginPageLocation = driver.getCurrentUrl(); Response response = client.target(kcLoginPageLocation).request().get(); Assert.assertEquals(401, response.getStatus()); Assert.assertEquals( KerberosConstants.NEGOTIATE, response.getHeaderString(HttpHeaders.WWW_AUTHENTICATE)); String responseText = response.readEntity(String.class); responseText.contains("Log in to test"); response.close(); SpnegoAuthenticator.bypassChallengeJavascript = false; }
@Test public void testReadProductReleaseBuildConfigurations() throws Exception { String relativeUrl = "/product-releases/" + productReleaseId + "/distributed-build-records-ids"; stubFor( get(urlEqualTo(CONTEXT_URL + relativeUrl)) .willReturn( aResponse() .withHeader("Content-Type", "application/json") .withBody( readResponseBodyFromTemplate( "product-release-distributed-build-records-ids-1.json")))); ProductReleaseEndpoint endpoint = client.target(pncUrl).proxy(ProductReleaseEndpoint.class); Response response = endpoint.getAllBuildsInDistributedRecordsetOfProductRelease(productReleaseId); Page<BuildRecordRest> ids = ((Page<BuildRecordRest>) response.readEntity(new GenericType<Page<BuildRecordRest>>() {})); assertArrayEquals(asList(1, 2).toArray(), extractIds(ids.getContent()).toArray()); }
@Before public void init() throws Exception { httpClient = HttpClientBuilder.create().build(); engine = new CustomApacheHttpClient4Engine(httpClient); clientBuilder = new CustomResteasyClientBuilder(); client = clientBuilder.build(); client.register(JacksonConfigurationProvider.class); ResteasyProviderFactory resteasyProviderFactory = new ResteasyProviderFactory(); clientConfiguration = new ClientConfiguration(resteasyProviderFactory); headers = new ClientRequestHeaders(clientConfiguration); uri = new URI("http://127.0.0.1"); // request = new ClientInvocation(client, uri, headers, clientConfiguration); request = mock(ClientInvocation.class); when(request.getHeaders()).thenReturn(headers); when(request.getClientConfiguration()).thenReturn(clientConfiguration); }
@After public void tearDown() throws Exception { if (client != null) { client.close(); } }
@After public void after() throws Exception { client.close(); client = null; }
@Test public void testResteasy734() throws Exception { ResteasyWebTarget target = null; Response response = null; target = client.target("http://localhost:8081/encoded/pathparam/bee bop"); response = target.request().get(); String entity = response.readEntity(String.class); System.out.println("Received encoded path param: " + entity); Assert.assertEquals(200, response.getStatus()); Assert.assertEquals("bee%20bop", entity); response.close(); target = client.target("http://localhost:8081/decoded/pathparam/bee bop"); response = target.request().get(); entity = response.readEntity(String.class); System.out.println("Received decoded path param: " + entity); Assert.assertEquals(200, response.getStatus()); Assert.assertEquals("bee bop", entity); response.close(); target = client.target("http://localhost:8081/encoded/matrix;m=bee bop"); response = target.request().get(); entity = response.readEntity(String.class); System.out.println("Received encoded matrix param: " + entity); Assert.assertEquals(200, response.getStatus()); Assert.assertEquals("bee%20bop", entity); response.close(); target = client.target("http://localhost:8081/decoded/matrix;m=bee bop"); response = target.request().get(); entity = response.readEntity(String.class); System.out.println("Received decoded matrix param: " + entity); Assert.assertEquals(200, response.getStatus()); Assert.assertEquals("bee bop", entity); response.close(); target = client.target("http://localhost:8081/encoded/query?m=bee bop"); response = target.request().get(); entity = response.readEntity(String.class); System.out.println("Received encoded query param: " + entity); Assert.assertEquals(200, response.getStatus()); Assert.assertEquals("bee%20bop", entity); response.close(); target = client.target("http://localhost:8081/decoded/query?m=bee bop"); response = target.request().get(); entity = response.readEntity(String.class); System.out.println("Received decoded query param: " + entity); Assert.assertEquals(200, response.getStatus()); Assert.assertEquals("bee bop", entity); response.close(); target = client.target("http://localhost:8081/encoded/form"); Form form = new Form(); form.param("f", "bee bop"); response = target.request().post(Entity.form(form)); entity = response.readEntity(String.class); System.out.println("Received encoded form param: " + entity); Assert.assertEquals(200, response.getStatus()); Assert.assertEquals("bee+bop", entity); response.close(); target = client.target("http://localhost:8081/decoded/form"); form = new Form(); form.param("f", "bee bop"); response = target.request().post(Entity.form(form)); entity = response.readEntity(String.class); System.out.println("Received decoded form param: " + entity); Assert.assertEquals(200, response.getStatus()); Assert.assertEquals("bee bop", entity); response.close(); target = client.target("http://localhost:8081/encoded/segment/bee bop"); response = target.request().get(); entity = response.readEntity(String.class); System.out.println("Received encoded path param from segment: " + entity); Assert.assertEquals(200, response.getStatus()); Assert.assertEquals("bee%20bop", entity); response.close(); target = client.target("http://localhost:8081/decoded/segment/bee bop"); response = target.request().get(); entity = response.readEntity(String.class); System.out.println("Received decoded path param from segment: " + entity); Assert.assertEquals(200, response.getStatus()); Assert.assertEquals("bee bop", entity); response.close(); target = client.target("http://localhost:8081/encoded/segment/matrix/params;m=bee bop"); response = target.request().get(); entity = response.readEntity(String.class); System.out.println("Received encoded matrix param from segment: " + entity); Assert.assertEquals(200, response.getStatus()); Assert.assertEquals("bee%20bop", entity); response.close(); target = client.target("http://localhost:8081/decoded/segment/matrix/params;m=bee bop"); response = target.request().get(); entity = response.readEntity(String.class); System.out.println("Received decoded matrix param from segment: " + entity); Assert.assertEquals(200, response.getStatus()); Assert.assertEquals("bee bop", entity); response.close(); }
public static <T> Object get(String path, Class<T> clas) { ResteasyClient client = new ResteasyClientBuilder().build(); T response = client.target(SALES_ORDER_APP + path).request().get(clas); return response; }
@After public void after() { client.close(); client = null; }
public static <T> Response delete(String path) { ResteasyClient client = new ResteasyClientBuilder().build(); Response response = client.target(SALES_ORDER_APP + path).request().delete(); System.out.println(response.getStatus()); return response; }
@AfterClass public static void shutdown() throws Exception { client.close(); EmbeddedContainer.stop(); deployment = null; }