public static String getAuthorizationCode(WebClient client, String scope) { // Make initial authorization request client.type("application/json").accept("application/json"); client.query("client_id", "consumer-id"); client.query("redirect_uri", "http://www.blah.apache.org"); client.query("response_type", "code"); if (scope != null) { client.query("scope", scope); } client.path("authorize/"); Response response = client.get(); OAuthAuthorizationData authzData = response.readEntity(OAuthAuthorizationData.class); // Now call "decision" to get the authorization code grant client.path("decision"); client.type("application/x-www-form-urlencoded"); Form form = new Form(); form.param("session_authenticity_token", authzData.getAuthenticityToken()); form.param("client_id", authzData.getClientId()); form.param("redirect_uri", authzData.getRedirectUri()); if (authzData.getProposedScope() != null) { form.param("scope", authzData.getProposedScope()); } form.param("oauthDecision", "allow"); response = client.post(form); String location = response.getHeaderString("Location"); return getSubstring(location, "code"); }
public String storeTurtleUserProfile(String userProfile, String username, String password) { String rsUri = getBASE_URI() + "createNewUserAccount"; WebClient client = WebClient.create(rsUri); client.type("multipart/mixed").accept(MediaType.TEXT_PLAIN); registerJsonProvider(); List<Attachment> atts = new LinkedList<Attachment>(); atts.add(new Attachment("userProfile", MediaType.TEXT_PLAIN, userProfile)); atts.add(new Attachment("username", MediaType.TEXT_PLAIN, username)); atts.add(new Attachment("password", MediaType.TEXT_PLAIN, password)); Response response = client.post(new MultipartBody(atts)); String userInstanceUriId = null; if (Response.Status.fromStatusCode(response.getStatus()) == Response.Status.CREATED) { try { userInstanceUriId = IOUtils.readStringFromStream((InputStream) response.getEntity()); logger.debug("Response Status CREATED - userInstanceUriId: " + userInstanceUriId); } catch (IOException ex) { logger.error("Error reading the REST response: " + ex.getMessage()); } } return userInstanceUriId; }
public boolean removeUserCredentialsForPaaS(String userInstanceUriId, String paaSInstanceUriId) throws SOAException { String rsUri = getBASE_URI() + "removeUserCredentialsForPaaS"; WebClient client = WebClient.create(rsUri); client.type("multipart/mixed").accept(MediaType.TEXT_PLAIN); registerJsonProvider(); List<Attachment> atts = new LinkedList<Attachment>(); atts.add(new Attachment("userInstanceUriId", MediaType.TEXT_PLAIN, userInstanceUriId)); atts.add(new Attachment("paaSInstanceUriId", MediaType.TEXT_PLAIN, paaSInstanceUriId)); Response response = client.post(new MultipartBody(atts)); if (Response.Status.fromStatusCode(response.getStatus()) == Response.Status.ACCEPTED) { try { String responseString = IOUtils.readStringFromStream((InputStream) response.getEntity()); logger.debug("Response Status ACCEPTED - " + responseString); } catch (IOException ex) { logger.error("Error reading the REST response: " + ex.getMessage()); } return true; } return false; }
public void testPie1() { try { String url = baseURL + "/rest/Pie/search;id=*/utensilCollection"; WebClient client = WebClient.create(url); client.type("application/xml").accept("application/xml"); Response response = client.get(); if (response.getStatus() == Status.NOT_ACCEPTABLE.getStatusCode()) { InputStream is = (InputStream) response.getEntity(); org.jdom.input.SAXBuilder builder = new org.jdom.input.SAXBuilder(false); org.jdom.Document jDoc = builder.build(is); assertEquals(jDoc.getRootElement().getName(), "response"); } else if (response.getStatus() == Status.NOT_FOUND.getStatusCode()) { InputStream is = (InputStream) response.getEntity(); org.jdom.input.SAXBuilder builder = new org.jdom.input.SAXBuilder(false); org.jdom.Document jDoc = builder.build(is); assertEquals(jDoc.getRootElement().getName(), "response"); } else if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } File myFile = new File("Pie_Search" + "XML.xml"); System.out.println("writing data to file " + myFile.getAbsolutePath()); FileWriter myWriter = new FileWriter(myFile); BufferedReader br = new BufferedReader(new InputStreamReader(((InputStream) response.getEntity()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { myWriter.write(output); System.out.println(output); } myWriter.flush(); myWriter.close(); } catch (Exception e) { e.printStackTrace(); ResponseBuilder builder = Response.status(Status.INTERNAL_SERVER_ERROR); builder.type("application/xml"); StringBuffer buffer = new StringBuffer(); buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); buffer.append("<response>"); buffer.append("<type>ERROR</type>"); buffer.append("<code>INTERNAL_ERROR_4</code>"); buffer.append("<message>Failed to Query due to: " + e.getMessage() + "</message>"); buffer.append("</response>"); builder.entity(buffer.toString()); throw new WebApplicationException(builder.build()); } }
public void handleFileUpload(FileUploadEvent fue) { String docId = UUID.randomUUID().toString(); getDocIds().add(docId); try { IclubDocumentModel model = new IclubDocumentModel(); model.setIclubPerson(getSessionUserId()); model.setDCrtdDt(new Date(System.currentTimeMillis())); model.setDId(docId); model.setDName(fue.getFile().getFileName()); model.setDContent(fue.getFile().getContentType()); model.setDSize(fue.getFile().getSize()); WebClient client = IclubWebHelper.createCustomClient(D_BASE_URL + "add"); ResponseModel response = client.accept(MediaType.APPLICATION_JSON).post(model, ResponseModel.class); client.close(); if (response.getStatusCode() == 0) { ContentDisposition cd = new ContentDisposition( "attachment;filename=" + fue.getFile().getFileName() + ";filetype=" + fue.getFile().getContentType()); List<Attachment> attachments = new ArrayList<Attachment>(); Attachment attachment = new Attachment(docId, fue.getFile().getInputstream(), cd); attachments.add(attachment); WebClient uploadClient = WebClient.create(D_BASE_URL + "upload"); Response res = uploadClient.type("multipart/form-data").post(new MultipartBody(attachments)); uploadClient.close(); if (res.getStatus() == 200) { IclubWebHelper.addMessage( getLabelBundle().getString("doucmentuploadedsuccessfully"), FacesMessage.SEVERITY_INFO); } else { IclubWebHelper.addMessage( getLabelBundle().getString("doucmentuploadingfailed") + " :: " + (res.getHeaderString("status") != null ? res.getHeaderString("status") : res.getStatusInfo()), FacesMessage.SEVERITY_ERROR); } } } catch (Exception e) { LOGGER.error(e, e); IclubWebHelper.addMessage( getLabelBundle().getString("doucmentuploadingerror") + " :: " + e.getMessage(), FacesMessage.SEVERITY_ERROR); } }
@Test public void testPostBookAdminRole() throws Exception { String address = "https://localhost:" + PORT + "/saml-roles/bookstore/books"; WebClient wc = createWebClient( address, Collections.<String, Object>singletonMap( "saml.roles", Collections.singletonList("admin"))); wc.type(MediaType.APPLICATION_XML).accept(MediaType.APPLICATION_XML); Book book = wc.post(new Book("CXF", 125L), Book.class); assertEquals(125L, book.getId()); }
@Test public void testPostBookAdminWithClaims() throws Exception { String address = "https://localhost:" + PORT + "/saml-claims/bookstore/books"; Map<String, Object> props = new HashMap<String, Object>(); props.put("saml.roles", Collections.singletonList("admin")); props.put("saml.auth", Collections.singletonList("smartcard")); WebClient wc = createWebClient(address, props); wc.type(MediaType.APPLICATION_XML).accept(MediaType.APPLICATION_XML); Book book = wc.post(new Book("CXF", 125L), Book.class); assertEquals(125L, book.getId()); }
@Test public void testPostBookAdminRoleWithGoodSubjectName() throws Exception { String address = "https://*****:*****@mycompany.com"); WebClient wc = createWebClient(address, props); wc.type(MediaType.APPLICATION_XML).accept(MediaType.APPLICATION_XML); Book book = wc.post(new Book("CXF", 125L), Book.class); assertEquals(125L, book.getId()); }
@Test public void testPostBookUserRole() throws Exception { String address = "https://localhost:" + PORT + "/saml-roles/bookstore/books"; WebClient wc = createWebClient(address, null); wc.type(MediaType.APPLICATION_XML).accept(MediaType.APPLICATION_XML); try { wc.post(new Book("CXF", 125L), Book.class); fail("403 is expected"); } catch (WebApplicationException ex) { assertEquals(403, ex.getResponse().getStatus()); } }
@Test @Ignore public void shit() throws Exception { WebClient client = WebClient.create("http://localhost:8080/forsendelse/service/rest/forsendelsesservice/send"); client.type("multipart/form-data"); List<Attachment> attacments = new ArrayList<Attachment>(); attacments.add( createDocumentAttachment(new File("src/test/resources/Undervisningsfritak.pdf"))); attacments.add(createForsendelsesAttachment(createForsendelse(1))); Response rs = client.post(new MultipartBody(attacments)); System.out.println(rs.getStatus()); }
public static ClientAccessToken getAccessTokenWithAuthorizationCode( WebClient client, String code) { client.type("application/x-www-form-urlencoded").accept("application/json"); client.path("token"); Form form = new Form(); form.param("grant_type", "authorization_code"); form.param("code", code); form.param("client_id", "consumer-id"); Response response = client.post(form); return response.readEntity(ClientAccessToken.class); }
@Test public void testPostBookAdminWithWeakClaims() throws Exception { String address = "https://localhost:" + PORT + "/saml-claims/bookstore/books"; Map<String, Object> props = new HashMap<String, Object>(); WebClient wc = createWebClient(address, props); wc.type(MediaType.APPLICATION_XML).accept(MediaType.APPLICATION_XML); try { wc.post(new Book("CXF", 125L), Book.class); fail("403 is expected"); } catch (WebApplicationException ex) { assertEquals(403, ex.getResponse().getStatus()); } }
private void invoke(int ind) throws Exception { client.type("text/plain").accept("text/plain"); String actualHeaderName = bookHeader + ind; String actualBookName = bookName + ind; MultivaluedMap<String, String> map = client.getHeaders(); map.putSingle("CustomHeader", actualHeaderName); client.headers(map).path("booksecho"); doInvoke(actualBookName, actualHeaderName); // reset current path client.back(true); }
@Test public void testPostBookAdminRoleWithWrongSubjectNameFormat() throws Exception { String address = "https://localhost:" + PORT + "/saml-roles2/bookstore/books"; WebClient wc = createWebClient( address, Collections.<String, Object>singletonMap( "saml.roles", Collections.singletonList("admin"))); wc.type(MediaType.APPLICATION_XML).accept(MediaType.APPLICATION_XML); try { wc.post(new Book("CXF", 125L), Book.class); fail("403 is expected"); } catch (WebApplicationException ex) { assertEquals(403, ex.getResponse().getStatus()); } }
@Test @Ignore public void statuslist() throws Exception { WebClient wc = WebClient.create( "http://localhost:8080/forsendelse/service/rest/forsendelsesservice/statuslist?ids=000000001689.pdf,000000001690.pdf"); wc.type("text/xml"); XMLSource source = wc.get(XMLSource.class); source.setBuffering(true); ForsendelseStatusRest b1 = source.getNode("/books/book[position() = 1]", ForsendelseStatusRest.class); assertNotNull(b1); ForsendelseStatusRest b2 = source.getNode("/books/book[position() = 2]", ForsendelseStatusRest.class); assertNotNull(b2); }
public void testSearch() throws Exception { try { String url = baseURL + "/rest/Pupil/search;id=*"; WebClient client = WebClient.create(url); client.type("application/xml").accept("application/xml"); Response response = client.get(); if (response.getStatus() == Status.NOT_ACCEPTABLE.getStatusCode()) { InputStream is = (InputStream) response.getEntity(); org.jdom.input.SAXBuilder builder = new org.jdom.input.SAXBuilder(false); org.jdom.Document jDoc = builder.build(is); assertEquals(jDoc.getRootElement().getName(), "response"); } else if (response.getStatus() == Status.NOT_FOUND.getStatusCode()) { InputStream is = (InputStream) response.getEntity(); org.jdom.input.SAXBuilder builder = new org.jdom.input.SAXBuilder(false); org.jdom.Document jDoc = builder.build(is); assertEquals(jDoc.getRootElement().getName(), "response"); } else if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } File myFile = new File("Pupil_Search" + "XML.xml"); System.out.println("writing data to file " + myFile.getAbsolutePath()); FileWriter myWriter = new FileWriter(myFile); BufferedReader br = new BufferedReader(new InputStreamReader(((InputStream) response.getEntity()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { myWriter.write(output); System.out.println(output); } myWriter.flush(); myWriter.close(); } catch (Exception e) { e.printStackTrace(); } }
@SuppressWarnings("unchecked") public void downloadDocument(String selDocId) { try { WebClient client = WebClient.create(D_BASE_URL + "download/" + selDocId); client.type("multipart/form-data").accept(MediaType.MULTIPART_FORM_DATA); List<Attachment> attachments = (List<Attachment>) client.getCollection(Attachment.class); file = new DefaultStreamedContent( attachments.get(0).getDataHandler().getInputStream(), attachments.get(0).getContentDisposition().getParameter("filetype"), attachments.get(0).getContentDisposition().getParameter("filename")); client.close(); } catch (Exception e) { LOGGER.error(e, e); IclubWebHelper.addMessage( getLabelBundle().getString("doucmentuploadingerror") + " :: " + e.getMessage(), FacesMessage.SEVERITY_ERROR); } }
public UserPaaSCredentials readUserCredentialsForPaaS( String userInstanceUriId, String paaSInstanceUriId) throws SOAException { String rsUri = getBASE_URI() + "readUserCredentialsForPaaS"; WebClient client = WebClient.create(rsUri); client.type("multipart/mixed").accept(MediaType.APPLICATION_JSON); registerJsonProvider(); List<Attachment> atts = new LinkedList<Attachment>(); atts.add(new Attachment("userInstanceUriId", MediaType.TEXT_PLAIN, userInstanceUriId)); atts.add(new Attachment("paaSInstanceUriId", MediaType.TEXT_PLAIN, paaSInstanceUriId)); UserPaaSCredentials userPaaSCredentials; try { userPaaSCredentials = client.post(new MultipartBody(atts), UserPaaSCredentials.class); } catch (ServerWebApplicationException cwe) { throw new SOAException(Response.Status.fromStatusCode(cwe.getStatus()), cwe.getMessage()); } return userPaaSCredentials; }
public UserInstance authenticateUser(String username, String password) throws ClientWebApplicationException { String rsUri = getBASE_URI() + "authenticateUser"; WebClient client = WebClient.create(rsUri); client.type("multipart/mixed").accept(MediaType.APPLICATION_XML_TYPE); registerJsonProvider(); List<Attachment> atts = new LinkedList<Attachment>(); atts.add(new Attachment("username", MediaType.TEXT_PLAIN, username)); atts.add(new Attachment("password", MediaType.TEXT_PLAIN, password)); // Response response = client.post(new MultipartBody(atts)); UserInstance userInstance = client.post(new MultipartBody(atts), UserInstance.class); // UserInstance userInstance = null; // userInstance = (UserInstance)response.getEntity(); // logger.debug("userInstance: "+userInstance); return userInstance; }
/** * Uses Nested Search Criteria for search Verifies that the results are returned Verifies size of * the result set Verifies that none of the attributes are null * * @throws Exception */ public void testGet() throws Exception { try { Pupil searchObject = new Pupil(); Collection results = getApplicationService() .search("gov.nih.nci.cacoresdk.domain.inheritance.abstrakt.Pupil", searchObject); String id = ""; if (results != null && results.size() > 0) { Pupil obj = (Pupil) ((List) results).get(0); id = obj.getId().getExtension(); } else return; if (id.equals("")) return; String url = baseURL + "/rest/Pupil/" + id; WebClient client = WebClient.create(url); client.type("application/xml").accept("application/xml"); Response response = client.get(); if (response.getStatus() == Status.NOT_ACCEPTABLE.getStatusCode()) { InputStream is = (InputStream) response.getEntity(); org.jdom.input.SAXBuilder builder = new org.jdom.input.SAXBuilder(false); org.jdom.Document jDoc = builder.build(is); assertEquals(jDoc.getRootElement().getName(), "response"); } else if (response.getStatus() == Status.NOT_FOUND.getStatusCode()) { InputStream is = (InputStream) response.getEntity(); org.jdom.input.SAXBuilder builder = new org.jdom.input.SAXBuilder(false); org.jdom.Document jDoc = builder.build(is); assertEquals(jDoc.getRootElement().getName(), "response"); } else if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } File myFile = new File("Pupil" + "XML.xml"); System.out.println("writing data to file " + myFile.getAbsolutePath()); FileWriter myWriter = new FileWriter(myFile); BufferedReader br = new BufferedReader(new InputStreamReader(((InputStream) response.getEntity()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { myWriter.write(output); System.out.println(output); } myWriter.flush(); myWriter.close(); } catch (Exception e) { e.printStackTrace(); throw e; } }
public void testgetUtensilCollection() { try { Pie searchObject = new Pie(); Collection results4 = getApplicationService() .search( "gov.nih.nci.cacoresdk.domain.other.differentpackage.associations.Pie", searchObject); String id = ""; if (results4 != null && results4.size() > 0) { Pie obj = (Pie) ((List) results4).get(0); Integer idVal = obj.getId(); id = new Integer(idVal).toString(); } else return; if (id.equals("")) return; String url = baseURL + "/rest/Pie/" + id + "/utensilCollection"; WebClient client = WebClient.create(url); client.type("application/xml").accept("application/xml"); Response response = client.get(); if (response.getStatus() == Status.NOT_ACCEPTABLE.getStatusCode()) { InputStream is = (InputStream) response.getEntity(); org.jdom.input.SAXBuilder builder = new org.jdom.input.SAXBuilder(false); org.jdom.Document jDoc = builder.build(is); assertEquals(jDoc.getRootElement().getName(), "response"); } else if (response.getStatus() == Status.NOT_FOUND.getStatusCode()) { InputStream is = (InputStream) response.getEntity(); org.jdom.input.SAXBuilder builder = new org.jdom.input.SAXBuilder(false); org.jdom.Document jDoc = builder.build(is); assertEquals(jDoc.getRootElement().getName(), "response"); } else if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } File myFile = new File("Pie_Search" + "XML.xml"); System.out.println("writing data to file " + myFile.getAbsolutePath()); FileWriter myWriter = new FileWriter(myFile); BufferedReader br = new BufferedReader(new InputStreamReader(((InputStream) response.getEntity()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { myWriter.write(output); System.out.println(output); } myWriter.flush(); myWriter.close(); } catch (Exception e) { e.printStackTrace(); ResponseBuilder builder = Response.status(Status.INTERNAL_SERVER_ERROR); builder.type("application/xml"); StringBuffer buffer = new StringBuffer(); buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); buffer.append("<response>"); buffer.append("<type>ERROR</type>"); buffer.append("<code>INTERNAL_ERROR_4</code>"); buffer.append("<message>Failed to Query due to: " + e.getMessage() + "</message>"); buffer.append("</response>"); builder.entity(buffer.toString()); throw new WebApplicationException(builder.build()); } }
@Test public void testSimpleWebClient() throws Exception { WebClient client = WebClient.create("http://localhost:" + PORT + "/bookstore/booksecho"); client.type("text/plain").accept("text/plain").header("CustomHeader", "CustomValue"); runWebClients(client, 10, true, false); }