@Test( groups = {"wso2.esb"}, description = "Tests with filter mediator - JSON path Scenario - Filter condition true", enabled = false) public void testJSONFilterFromJSONPathConditionTrueTestScenario() throws Exception { String JSON_PAYLOAD = "{\"album\":\"Hello\",\"singer\":\"Peter\"}"; WebResource webResource = client.resource(getProxyServiceURLHttp("JSONPathFilterWithJSONProxy")); // sending post request ClientResponse postResponse = webResource.type("application/json").post(ClientResponse.class, JSON_PAYLOAD); assertEquals( postResponse.getType().toString(), "application/json", "Content-Type Should be application/json"); assertEquals(postResponse.getStatus(), 201, "Response status should be 201"); // Calling the GET request to verify Added album details ClientResponse getResponse = webResource.type("application/json").get(ClientResponse.class); assertNotNull(getResponse, "Received Null response for while getting Music album details"); assertEquals( getResponse.getEntity(String.class), JSON_PAYLOAD, "Response mismatch for HTTP Get call"); }
public OpenImpl(String name) { this.name = name; publisherName = name; stateEventTypeName = "_" + name + "_state"; state = s0; ClientConfig config = new DefaultClientConfig(); client = Client.create(config); service = client.resource(REST_URI); eventTypeService = service.path(EVENTS_PATH); publishersService = service.path(PUBLISHERS_PATH); myPublisher = service.path(PUBLISHERS_PATH + "/" + publisherName); System.out.println("Registering events"); ClientResponse response = eventTypeService .type(MediaType.APPLICATION_XML) .put(ClientResponse.class, CopalClient.eventType(stateEventTypeName)); System.out.println(response.toString()); System.out.println(response.getEntity(String.class).toString()); System.out.println("Setting ttl"); WebResource test = service.path(EVENTS_PATH + "/" + stateEventTypeName + "/ttl"); response = test.type(MediaType.TEXT_PLAIN).put(ClientResponse.class, "" + Integer.MAX_VALUE); System.out.println(response.toString()); System.out.println(response.getEntity(String.class).toString()); String[] eventNames = {stateEventTypeName}; System.out.println("Registering publisher"); System.out.println(CopalClient.publisher(publisherName, eventNames)); response = publishersService .type(MediaType.APPLICATION_XML) .put(ClientResponse.class, CopalClient.publisher(publisherName, eventNames)); System.out.println(response.toString()); System.out.println(response.getEntity(String.class).toString()); response = myPublisher .type(MediaType.APPLICATION_XML) .post(ClientResponse.class, CopalClient.event(stateEventTypeName, state)); System.out.println(response.toString()); Runtime.getRuntime() .addShutdownHook( new Thread() { public void run() { System.out.println("Removing publisher"); ClientResponse response = myPublisher.delete(ClientResponse.class); System.out.println(response.toString()); System.out.println(response.getEntity(String.class).toString()); System.out.println("Removing events"); WebResource wr = service.path(EVENTS_PATH + "/" + stateEventTypeName); response = wr.delete(ClientResponse.class); System.out.println(response.toString()); System.out.println(response.getEntity(String.class).toString()); } }); }
@Test public void shouldNotActivateUser() throws Exception { String email = "*****@*****.**"; UserResult userResult; Client client = createClient(); WebResource webResource = client.resource(ringringServerApi.getUrl() + "/user"); // Create request hash with email address HashMap<String, String> requestHash = new HashMap<String, String>(); requestHash.put("email", email); // First email registration userResult = webResource .type(MediaType.APPLICATION_JSON_TYPE) .accept(MediaType.APPLICATION_JSON_TYPE) .post(UserResult.class, requestHash); // User needs to registered assertEquals(Status.OKAY, userResult.getStatus()); assertTrue(userResult.isSuccess()); // Check if email sent to the user MimeMessage message = getLastMail().getMimeMessage(); assertEquals(configManager.getSmtpFrom(), message.getFrom()[0].toString()); assertEquals(email, message.getRecipients(Message.RecipientType.TO)[0].toString()); User registeredUser = userResult.getUser(); assertEquals(email, registeredUser.getEmail()); assertFalse(registeredUser.getIsActivated()); assertFalse(registeredUser.getIsLoggedIn()); // 1st try: email in the path is not matching to the user's email webResource = client.resource(ringringServerApi.getUrl() + "/user/[email protected]"); StatusResult statusResult = webResource .type(MediaType.APPLICATION_JSON_TYPE) .accept(MediaType.APPLICATION_JSON_TYPE) .put(StatusResult.class, registeredUser); assertEquals(Status.INVALID_EMAIL, statusResult.getStatus()); // 2nd try: Incorrect activation code registeredUser.setActivationCode("SOME_FALSE_ACTIVATION_CODE"); webResource = client.resource(ringringServerApi.getUrl() + "/user/" + registeredUser.getEmail()); statusResult = webResource .type(MediaType.APPLICATION_JSON_TYPE) .accept(MediaType.APPLICATION_JSON_TYPE) .put(StatusResult.class, registeredUser); assertEquals(Status.INVALID_ACTIVATION_CODE, statusResult.getStatus()); }
@Test public void shouldBadRequest() throws Exception { String email = "*****@*****.**"; UserResult userResult; Client client = createClient(); WebResource webResource = client.resource(ringringServerApi.getUrl() + "/user"); // Create request hash with email address using wrong key HashMap<String, String> requestHash = new HashMap<String, String>(); requestHash.put("email_wrong_key", email); // First email registration userResult = webResource .type(MediaType.APPLICATION_JSON_TYPE) .accept(MediaType.APPLICATION_JSON_TYPE) .post(UserResult.class, requestHash); assertEquals(Status.BAD_REQUEST, userResult.getStatus()); assertNull(userResult.getUser()); // Create request hash with email address HashMap<String, List<String>> emailsRequestHash = new HashMap<String, List<String>>(); List<String> userEmails = Arrays.asList( "*****@*****.**", "*****@*****.**", "*****@*****.**", "*****@*****.**"); // Put emails list into requestHash with wrong hash key emailsRequestHash.put("emails_wrong_key", userEmails); webResource = client.resource(ringringServerApi.getUrl() + "/user/list"); UserListResult userListResult = webResource .type(MediaType.APPLICATION_JSON_TYPE) .accept(MediaType.APPLICATION_JSON_TYPE) .post(UserListResult.class, emailsRequestHash); assertEquals(Status.BAD_REQUEST, userListResult.getStatus()); assertNull(userListResult.getUsers()); // Invite email with wrong key HashMap<String, String> inviteRequestHash = new HashMap<String, String>(); inviteRequestHash.put("email_wrong_key", email); inviteRequestHash.put("to_email", email); webResource = client.resource(ringringServerApi.getUrl() + "/user/" + email + "/invite"); StatusResult statusResult = webResource .type(MediaType.APPLICATION_JSON_TYPE) .accept(MediaType.APPLICATION_JSON_TYPE) .post(StatusResult.class, inviteRequestHash); assertEquals(Status.BAD_REQUEST, statusResult.getStatus()); }
@Test public void shouldActivateUser() throws Exception { String email = "*****@*****.**"; UserResult userResult; Client client = createClient(); WebResource webResource = client.resource(ringringServerApi.getUrl() + "/user"); // Create request hash with email address HashMap<String, String> requestHash = new HashMap<String, String>(); requestHash.put("email", email); // First email registration userResult = webResource .type(MediaType.APPLICATION_JSON_TYPE) .accept(MediaType.APPLICATION_JSON_TYPE) .post(UserResult.class, requestHash); // Check if email sent to the user MimeMessage message = getLastMail().getMimeMessage(); assertEquals(configManager.getSmtpFrom(), message.getFrom()[0].toString()); assertEquals(email, message.getRecipients(Message.RecipientType.TO)[0].toString()); // User needs to registered assertEquals(Status.OKAY, userResult.getStatus()); assertTrue(userResult.isSuccess()); User registeredUser = userResult.getUser(); assertEquals(email, registeredUser.getEmail()); assertFalse(registeredUser.getIsActivated()); assertFalse(registeredUser.getIsLoggedIn()); // The activation code is not sent in the REST response. Get it from the email String activationCode = getActivationCodeFromEmailContent(message.getContent().toString()); registeredUser.setActivationCode(activationCode); // Activate the user webResource = client.resource(ringringServerApi.getUrl() + "/user/" + registeredUser.getEmail()); StatusResult statusresult = webResource .type(MediaType.APPLICATION_JSON_TYPE) .accept(MediaType.APPLICATION_JSON_TYPE) .put(StatusResult.class, registeredUser); assertEquals(Status.OKAY, statusresult.getStatus()); }
public String contactNumberClient(Business input) { String contactNumber = ""; try { Client client = Client.create(); WebResource webResource = client.resource("http://localhost:9280/NICUtil/rest/contact/post"); ObjectMapper mapper = new ObjectMapper(); ClientResponse response = webResource .type("application/json") .post(ClientResponse.class, mapper.writeValueAsString(input)); if (response.getStatus() != 201) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } System.out.println("**Web Service Successful in helper**\n\n"); contactNumber = response.getEntity(String.class); } catch (Exception e) { e.printStackTrace(); } return contactNumber; }
public String fileUploadClient(MultipartFile mpf) { String filePath = ""; Client client = Client.create(); WebResource webResource = client.resource("http://localhost:9280/NICUtil/rest/contact/upload"); byte[] logo = null; try { // logo = FileUtils.readFileToByteArray(file); logo = mpf.getBytes(); } catch (IOException e1) { e1.printStackTrace(); } // Construct a MultiPart with two body parts MultiPart multiPart = new MultiPart().bodyPart(new BodyPart(logo, MediaType.APPLICATION_OCTET_STREAM_TYPE)); // POST the request try { ClientResponse response = webResource.type("multipart/mixed").post(ClientResponse.class, multiPart); filePath = response.getEntity(String.class); System.out.println("id is " + filePath); } catch (Exception e) { e.printStackTrace(); } return filePath; }
@ApiOperation(value = "to insert employee records", response = EmpOrderController.class) @RequestMapping(value = "/empinsert", method = RequestMethod.GET) public ModelAndView empController( HttpServletRequest request, HttpServletResponse responses, @RequestParam("name") String name, @RequestParam("age") int age, @RequestParam("gender") String gender) { /*String name= request.getParameter("name"); int age =Integer.parseInt(request.getParameter("age")); String gender= request.getParameter("gender");*/ ModelAndView mav = new ModelAndView(); JSONObject json = new JSONObject(); json.put("name", name); json.put("age", age); json.put("gender", gender); String msg = null; try { Client client = Client.create(); WebResource webResource = client.resource("http://localhost:8080/EmpOrderRest/api/insertEmp"); ClientResponse response = webResource.type("application/json").post(ClientResponse.class, json.toString()); if (response.getStatus() == 200) { msg = "Employee entry inserted Successfully"; } else { msg = "Cannot insert the records"; throw new RuntimeException("Why Failed : HTTP error code : " + response.getStatus()); } } catch (Exception e) { e.printStackTrace(); } mav.setViewName("welcome.jsp"); mav.addObject("msg", msg); return mav; }
@ApiOperation("to insert order records") @RequestMapping(value = "/orderinsert", method = RequestMethod.GET) public ModelAndView ordersController( HttpServletRequest request, HttpServletResponse responses, @RequestParam("name") String name, @RequestParam("description") String desc) { ModelAndView mav = new ModelAndView(); JSONObject json = new JSONObject(); json.put("name", name); json.put("description", desc); String msg = null; try { Client client = Client.create(); WebResource webResource = client.resource("http://localhost:8080/EmpOrderRest/api/insertOrder"); ClientResponse response = webResource.type("application/json").post(ClientResponse.class, json.toString()); if (response.getStatus() == 200) { msg = "Order entry inserted Successfully"; } else { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } } catch (Exception e) { e.printStackTrace(); } mav.setViewName("welcome.jsp"); mav.addObject("msg", msg); return mav; }
public static void main(String[] args) { Client c = Client.create(); String v1 = "http://www.diachron-fp7.eu/resource/recordset/efo/2.34"; String v2 = "http://www.diachron-fp7.eu/resource/recordset/efo/2.35"; boolean ingest = true; String ip = "139.91.183.48"; ip = "localhost"; WebResource r = c.resource("http://" + ip + ":8181/ForthMaven-1.0/diachron/change_detection"); String input = "{ \"Old_Version\" : \"" + v1 + "\", " + "\"New_Version\" : \"" + v2 + "\", " + "\"Ingest\" : " + ingest + ", " + "\"Complex_Changes\" : [ ] }"; ClientResponse response = r.type(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .post(ClientResponse.class, input); System.out.println(response.getEntity(String.class)); System.out.println(response.getStatus()); }
// setting a configuration private void testSetConfig4Element() { String url = "http://localhost:8080/sensorData/rest/config/setConfig4Element"; Client client = Client.create(); WebResource webResource = client.resource(url); Configuration config = new Configuration(); HashMap<String, String> values = new HashMap<String, String>(); values.put("PT_DS1_316233.ED01_AB219_M04.AS.V2251", M2MDataType.FLOAT.toString()); values.put("PT_DS1_316233.ED01_AB219_M04.AS.V2253", M2MDataType.FLOAT.toString()); values.put("PT_DS1_316233.ED01_AB219_M04.AS.V2254", M2MDataType.FLOAT.toString()); values.put("PT_DS1_316233.ED01_FA011.AA.R244", M2MDataType.FLOAT.toString()); values.put("PT_DS1_316233.ED01_FA011.AA.R244", M2MDataType.FLOAT.toString()); values.put("ABC123", M2MDataType.FLOAT.toString()); // if commented all values will be gone config.setConfigForElement("sensors", values); String input = JSONBuilderParserUtil.getInstance().toJSON(config); // off we go ClientResponse response = webResource.type("application/json").post(ClientResponse.class, input); }
private String performPost(String address, String input) { ClientConfig clientConfig = new DefaultClientConfig(); clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); ClientResponse response = null; try { System.err.println("web address " + address); WebResource webResource = client.resource(address); response = webResource.type("application/json").post(ClientResponse.class, input); } catch (Exception e) { System.err.println("Exception web address " + address); e.printStackTrace(); return ""; } if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } // System.out.println("Output from Server .... \n"); String output = response.getEntity(String.class); // System.out.println(output); return output; }
public KeystoneAccess createToken(KeystoneAuthCredentials credentials) throws KeystoneServerException, KeystoneConnectionException, KeystoneUnauthorizedException { Client client = Client.create(clientConfig); WebResource resource = client.resource(getTokensUrl()); try { return resource .type(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .post(KeystoneAccess.class, credentials); } catch (UniformInterfaceException e) { if (e.getResponse().getStatus() == Response.Status.BAD_REQUEST.getStatusCode()) { String err = "Keystone v2 login credentials invalid " + credentials.toString(); log.warn(err); throw new KeystoneUnauthorizedException(err, e); } else if (e.getResponse().getStatus() == Response.Status.UNAUTHORIZED.getStatusCode()) { String err = "Keystone v2 login credentials not found " + credentials.toString(); log.warn(err, credentials); throw new KeystoneUnauthorizedException(err, e); } else { throw new KeystoneServerException("Keystone server error", e, e.getResponse().getStatus()); } } catch (ClientHandlerException e) { throw new KeystoneConnectionException( "Could not connect to Keystone server. Uri=" + resource.getURI(), e); } }
@Test public void shouldNotRegisterUser() throws Exception { String email = "test.user.invalid.email.com"; UserResult userResult; Client client = createClient(); WebResource webResource = client.resource(ringringServerApi.getUrl() + "/user"); // Create request hash with email address HashMap<String, String> requestHash = new HashMap<String, String>(); requestHash.put("email", email); // First email registration userResult = webResource .type(MediaType.APPLICATION_JSON_TYPE) .accept(MediaType.APPLICATION_JSON_TYPE) .post(UserResult.class, requestHash); // Should be failed with invalid email exception assertEquals(Status.INVALID_EMAIL, userResult.getStatus()); assertFalse(userResult.isSuccess()); assertNull(userResult.getUser()); }
public static void postForm(WebResource r, String id, String name) { Form form = new Form(); form.add("id", id); form.add("name", name); ClientResponse response = r.type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, form); System.out.println(response.getEntity(String.class)); }
public void login() { WebResource contactResource = client.resource(wsBaseUrl + "aas/partner/login?pwd=pwd&partnerId=" + partnerId); WebResource.Builder builder = contactResource.type(MediaType.APPLICATION_JSON_TYPE); PartnerLoginResponse response = builder.get(PartnerLoginResponse.class); token = response.getData().getPartnerLogin().getToken(); logger.info(token); }
@Test @SuppressWarnings("unchecked") public void testCreateResource() { WebResource wr = resource().path(getResourcePath()); T r = createTestResource(); T res = (T) wr.type(MediaType.APPLICATION_XML).post(r.getClass(), r); Assert.assertNotNull("Resource not created", res); }
private WebResource.Builder getBuilder(String fullUrl) { logger.info("Test url : " + fullUrl); WebResource contactResource = client.resource(fullUrl); WebResource.Builder builder = contactResource.type(MediaType.APPLICATION_JSON_TYPE); builder.header("token", token); builder.header("partnerId", partnerId); return builder; }
@Test public void shouldRegisterUser() throws Exception { String email = "*****@*****.**"; UserResult userResult; Client client = createClient(); WebResource webResource = client.resource(ringringServerApi.getUrl() + "/user"); // Create request hash with email address HashMap<String, String> requestHash = new HashMap<String, String>(); requestHash.put("email", email); // First email registration userResult = webResource .type(MediaType.APPLICATION_JSON_TYPE) .accept(MediaType.APPLICATION_JSON_TYPE) .post(UserResult.class, requestHash); // Check if email sent to the user MimeMessage message = getLastMail().getMimeMessage(); assertEquals(configManager.getSmtpFrom(), message.getFrom()[0].toString()); assertEquals(email, message.getRecipients(Message.RecipientType.TO)[0].toString()); // User needs to be registered assertEquals(Status.OKAY, userResult.getStatus()); assertTrue(userResult.isSuccess()); User registeredUser = userResult.getUser(); assertEquals(email, registeredUser.getEmail()); assertFalse(registeredUser.getIsActivated()); assertFalse(registeredUser.getIsLoggedIn()); // Try to register the same email again userResult = webResource .type(MediaType.APPLICATION_JSON_TYPE) .accept(MediaType.APPLICATION_JSON_TYPE) .post(UserResult.class, requestHash); // Should be failed with email already registered exception assertEquals(Status.EMAIL_ALREADY_REGISTERED, userResult.getStatus()); assertFalse(userResult.isSuccess()); assertNull(userResult.getUser()); }
private void testPing() { String url = "http://localhost:8080/sensorData/rest/config/ping"; Client client = Client.create(); WebResource webResource = client.resource(url); ClientResponse response = webResource.type("aplication/json").get(ClientResponse.class); LOG.debug(response.getEntity(String.class)); }
/** * Delete method is used when data needs to be removed * * @param path * @return a message */ public String delete(String path) { Client client = Client.create(); System.out.println(getHostAddress() + ":" + getPort() + "/api/" + path); WebResource webResource = client.resource(getHostAddress() + ":" + getPort() + "/api/" + path); ClientResponse response = webResource.type("application/json").delete(ClientResponse.class); return response.getEntity(String.class); }
public void testStoreSysParamsAtUser(final String sp) { final Client client = getClient(); final WebResource webResource = client.resource(userServiceURL + "systemParameters/store"); final ClientResponse response = webResource.type("application/xml").put(ClientResponse.class, sp); assertOk(response); }
@Test public void shouldRenewActivationCode() throws Exception { String email = "*****@*****.**"; UserResult userResult; Client client = createClient(); WebResource webResource = client.resource(ringringServerApi.getUrl() + "/user"); // Create request hash with email address HashMap<String, String> requestHash = new HashMap<String, String>(); requestHash.put("email", email); // First email registration userResult = webResource .type(MediaType.APPLICATION_JSON_TYPE) .accept(MediaType.APPLICATION_JSON_TYPE) .post(UserResult.class, requestHash); assertEquals(Status.OKAY, userResult.getStatus()); assertNotNull(userResult.getUser()); // Get first activation code from email MimeMessage message1 = getLastMail().getMimeMessage(); String firstActivationCode = getActivationCodeFromEmailContent(message1.getContent().toString()); // Request to change the activation code webResource = client.resource(ringringServerApi.getUrl() + "/user/" + email + "/renewactivationcode"); StatusResult statusResult = webResource .type(MediaType.APPLICATION_JSON_TYPE) .accept(MediaType.APPLICATION_JSON_TYPE) .get(StatusResult.class); assertEquals(Status.OKAY, statusResult.getStatus()); // Get first activation code from email MimeMessage message2 = getLastMail().getMimeMessage(); String secondActivationCode = getActivationCodeFromEmailContent(message2.getContent().toString()); // The new activation code should not be the same as the previous one assertFalse(firstActivationCode.equals(secondActivationCode)); }
public String testExtractIssuanceMessage(final String imab) { final Client client = getClient(); final WebResource webResource = client.resource(userServiceURL + "extractIssuanceMessage"); final ClientResponse response = webResource.type("application/xml").post(ClientResponse.class, imab); assertOk(response); return response.getEntity(String.class); }
public String testCreatePresentationToken(final String ppa) { final Client client = getClient(); final WebResource webResource = client.resource(userServiceURL + "createPresentationToken"); final ClientResponse response = webResource.type("application/xml").post(ClientResponse.class, ppa); assertOk(response); return response.getEntity(String.class); }
public String testIssuanceStepUser1(final String im) { final Client client = getClient(); final WebResource webResource = client.resource(userServiceURL + "issuanceProtocolStep"); final ClientResponse response = webResource.type("application/xml").post(ClientResponse.class, im); assertOk(response); return response.getEntity(String.class); }
public String testIssuanceRequest(final String ir) { final Client client = getClient(); final WebResource webResource = client.resource(issuanceServiceURLUnprot + "issuanceRequest"); final ClientResponse response = webResource.type("application/xml").post(ClientResponse.class, ir); assertOk(response); return response.getEntity(String.class); }
public void testStoreCredSpecAtIssuer(final String credSpec) { final Client client = getClient(); final WebResource webResource = client.resource(issuanceServiceURL + "credentialSpecification/store/" + credSpecURI); final ClientResponse response = webResource.type("application/xml").put(ClientResponse.class, credSpec); assertOk(response); }
public void testStoreQueryRuleAtIssuer(final String queryRule) { final Client client = getClient(); final WebResource webResource = client.resource(issuanceServiceURL + "queryRule/store/" + credSpecURI); final ClientResponse response = webResource.type("application/xml").put(ClientResponse.class, queryRule); assertOk(response); }
public void testStoreIssParamsAtVerifier(final String p) { final Client client = getClient(); final WebResource webResource = client.resource(verificationServiceURL + "issuerParameters/store/" + issuanceURI); final ClientResponse response = webResource.type("application/xml").put(ClientResponse.class, p); assertOk(response); }