/** * Deletes the Snapshot with the given id.( It is asynchronous operation ) * * @param snapshotId */ public void deleteSnapshot(String snapshotId) { _log.info("CinderApi - start deleteSnapshot"); String deleteSnapshotUri = endPoint.getBaseUri() + String.format( CinderConstants.URI_DELETE_SNAPSHOT, new Object[] {endPoint.getCinderTenantId(), snapshotId}); ClientResponse deleteResponse = getClient().delete(URI.create(deleteSnapshotUri)); String s = deleteResponse.getEntity(String.class); _log.debug("Got the response {}", s); if (deleteResponse.getStatus() == ClientResponse.Status.NOT_FOUND.getStatusCode()) { throw CinderException.exceptions.snapshotNotFound(snapshotId); } if (deleteResponse.getStatus() != ClientResponse.Status.ACCEPTED.getStatusCode()) { throw CinderException.exceptions.snapshotDeleteFailed(s); } _log.info("CinderApi - end deleteSnapshot"); }
@Test(dependsOnMethods = "testSubmitEntity") public void testAddProperty() throws Exception { final String guid = tableId._getId(); // add property String description = "bar table - new desc"; ClientResponse clientResponse = addProperty(guid, "description", description); Assert.assertEquals(clientResponse.getStatus(), Response.Status.OK.getStatusCode()); String entityRef = getEntityDefinition(getEntityDefinition(guid)); Assert.assertNotNull(entityRef); tableInstance.set("description", description); // invalid property for the type clientResponse = addProperty(guid, "invalid_property", "bar table"); Assert.assertEquals(clientResponse.getStatus(), Response.Status.BAD_REQUEST.getStatusCode()); // non-string property, update String currentTime = String.valueOf(System.currentTimeMillis()); clientResponse = addProperty(guid, "createTime", currentTime); Assert.assertEquals(clientResponse.getStatus(), Response.Status.OK.getStatusCode()); entityRef = getEntityDefinition(getEntityDefinition(guid)); Assert.assertNotNull(entityRef); tableInstance.set("createTime", currentTime); }
public void expandVolume(String volumeId, long new_size) { _log.info("CinderApi - expandVolume START"); Gson gson = new Gson(); VolumeExpandRequest request = new VolumeExpandRequest(); request.extend.new_size = new_size; String expandVolumeUri = endPoint.getBaseUri() + String.format( CinderConstants.URI_VOLUME_ACTION, new Object[] {endPoint.getCinderTenantId(), volumeId}); _log.debug("Expanding volume with uri : {}", expandVolumeUri); String json = gson.toJson(request); _log.debug("Expanding volume with body : {}", json); ClientResponse js_response = getClient().postWithHeader(URI.create(expandVolumeUri), json); String s = js_response.getEntity(String.class); _log.debug("Got the response {}", s); _log.debug("Response status {}", String.valueOf(js_response.getStatus())); if (js_response.getStatus() != ClientResponse.Status.ACCEPTED.getStatusCode()) { // This means volume expand request not accepted throw CinderException.exceptions.volumeExpandFailed(s); } _log.info("CinderApi - expandVolume END"); }
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 void bootFromServer(String clientName, Database db1) throws JSONException, ClassNotFoundException { Client client = Client.create(); WebResource webResource = client.resource("http://localhost:8080/com.youtube.rest/api/bootstrap/get/" + clientName); ; ClientResponse response = webResource.accept("application/json").get(ClientResponse.class); if (response.getStatus() != 200 && response.getStatus() != 204) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } String output = response.getEntity(String.class); System.out.println("Server Bootstrap information: "); System.out.println(output); String query = db1.parseData(output); System.out.println("QUERY"); System.out.println(query); db1.delete("client1"); // db1.insert(query); System.out.println("Information saved in Mysql!"); System.out.println("Server boot done!"); }
@Test public void shouldFilterLogEntriesOnEventId() throws Exception { DocumentModel doc = RestServerInit.getFile(1, session); MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl(); queryParams.putSingle("eventId", "documentModified"); ClientResponse response = getResponse( BaseTest.RequestType.GET, "id/" + doc.getId() + "/@" + AuditAdapter.NAME, queryParams); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); JsonNode node = mapper.readTree(response.getEntityInputStream()); List<JsonNode> nodes = getLogEntries(node); assertEquals(1, nodes.size()); assertEquals("documentModified", nodes.get(0).get("eventId").getValueAsText()); queryParams.putSingle("principalName", "bender"); response = getResponse( BaseTest.RequestType.GET, "id/" + doc.getId() + "/@" + AuditAdapter.NAME, queryParams); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); node = mapper.readTree(response.getEntityInputStream()); nodes = getLogEntries(node); assertEquals(0, nodes.size()); }
public void testHead() throws Exception { startServer(Resource.class); WebResource r = Client.create().resource(getUri().path("/").build()); ClientResponse cr = r.path("string").accept("text/plain").head(); assertEquals(200, cr.getStatus()); assertEquals(MediaType.TEXT_PLAIN_TYPE, cr.getType()); assertFalse(cr.hasEntity()); cr = r.path("byte").accept("application/octet-stream").head(); assertEquals(200, cr.getStatus()); String length = cr.getMetadata().getFirst("Content-Length"); assertNotNull(length); assertEquals(3, Integer.parseInt(length)); assertEquals(MediaType.APPLICATION_OCTET_STREAM_TYPE, cr.getType()); assertFalse(cr.hasEntity()); cr = r.path("ByteArrayInputStream").accept("application/octet-stream").head(); assertEquals(200, cr.getStatus()); length = cr.getMetadata().getFirst("Content-Length"); assertNotNull(length); assertEquals(3, Integer.parseInt(length)); assertEquals(MediaType.APPLICATION_OCTET_STREAM_TYPE, cr.getType()); assertFalse(cr.hasEntity()); }
/** Executes an authentication request via HTTP POST */ private <T> T executeAuthenticationPost(WebResource webResource, Class<T> returnClass) throws CIWiseRESTConnectorTokenExpiredException, CIWiseRESTConnectorException { // Map query params for POST operation MultivaluedMap, MultivaluedMapImpl MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl(); queryParams.add("username", getConnector().getConfig().getUsername()); queryParams.add("password", getConnector().getConfig().getPassword()); /** Call HTTP POST */ ClientResponse clientResponse = webResource .queryParams(queryParams) .accept(MediaType.APPLICATION_JSON) .post(ClientResponse.class); if (clientResponse.getStatus() == 200) { return clientResponse.getEntity(returnClass); } else if (clientResponse.getStatus() == 401) { throw new CIWiseRESTConnectorTokenExpiredException( "The access token has expired; " + clientResponse.getEntity(String.class)); } else { throw new CIWiseRESTConnectorException( String.format( "ERROR - statusCode: %d - message: %s", clientResponse.getStatus(), clientResponse.getEntity(String.class))); } }
@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; }
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; }
@Test public void testGetDependencies() throws Exception { ClientResponse response; response = this.service .path("api/entities/list/process/") .header("Remote-User", REMOTE_USER) .type(MediaType.TEXT_XML) .accept(MediaType.TEXT_XML) .get(ClientResponse.class); Assert.assertEquals(response.getStatus(), 200); Map<String, String> overlay = getUniqueOverlay(); response = submitToIvory(CLUSTER_FILE_TEMPLATE, overlay, EntityType.CLUSTER); assertSuccessful(response); response = this.service .path("api/entities/list/cluster/") .header("Remote-User", REMOTE_USER) .type(MediaType.TEXT_XML) .accept(MediaType.TEXT_XML) .get(ClientResponse.class); Assert.assertEquals(response.getStatus(), 200); }
@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; }
@ApiOperation("To fetch and display records") @RequestMapping("/display") public ModelAndView display(HttpServletRequest request, HttpServletResponse responses) { String table = request.getParameter("table"); String name = request.getParameter("name"); ModelAndView mav = new ModelAndView(); String msg = null; try { Client client = Client.create(); String names = URLEncoder.encode(name, "UTF-8").replace("+", "%20"); WebResource webResource = client.resource("http://localhost:8080/EmpOrderRest/api/display/" + table + "/" + names); ClientResponse response = webResource.head(); if (response.getStatus() == 200) { JSONObject json = readJsonFromUrl( "http://localhost:8080/EmpOrderRest/api/display/" + table + "/" + names); msg = json.toString(); } 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; }
/** * Get the URL of the file to download. This has not been modified from the original version. * * <p>For more information, please see: <a href= * "https://collegereadiness.collegeboard.org/educators/higher-ed/reporting-portal-help#features"> * https://collegereadiness.collegeboard.org/educators/higher-ed/reporting- * portal-help#features</a> * * <p>Original code can be accessed at: <a href= * "https://collegereadiness.collegeboard.org/zip/pascoredwnld-java-sample.zip"> * https://collegereadiness.collegeboard.org/zip/pascoredwnld-java-sample.zip </a> * * @see #login(String, String) * @see org.collegeboard.scoredwnld.client.FileInfo * @author CollegeBoard * @param accessToken Access token obtained from {@link #login(String, String)} * @param filePath File to download * @return FileInfo descriptor of file to download */ private FileInfo getFileUrlByToken(String accessToken, String filePath) { Client client = getClient(); WebResource webResource = client.resource( scoredwnldUrlRoot + "/pascoredwnld/file?tok=" + accessToken + "&filename=" + filePath); ClientResponse response = webResource.accept("application/json").get(ClientResponse.class); if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } try { JSONObject json = new JSONObject(response.getEntity(String.class)); FileInfo fileInfo = new FileInfo(); fileInfo.setFileName(filePath); fileInfo.setFileUrl(String.valueOf(json.get("fileUrl"))); return fileInfo; } catch (ClientHandlerException e) { log("Error: " + e.getMessage()); e.printStackTrace(); } catch (UniformInterfaceException e) { log("Error: " + e.getMessage()); e.printStackTrace(); } catch (JSONException e) { log("Error: " + e.getMessage()); e.printStackTrace(); } return null; }
/** * Login to the PAScoresDwnld site. This method has not been modified from the original published * by CollegeBoard. * * <p>For more information, please see: <a href= * "https://collegereadiness.collegeboard.org/educators/higher-ed/reporting-portal-help#features"> * https://collegereadiness.collegeboard.org/educators/higher-ed/reporting- * portal-help#features</a> * * <p>Original code can be accessed at: <a href= * "https://collegereadiness.collegeboard.org/zip/pascoredwnld-java-sample.zip"> * https://collegereadiness.collegeboard.org/zip/pascoredwnld-java-sample.zip </a> * * @author CollegeBoard * @param username Username to login with * @param password Password to login with * @return Authentication token */ private String login(String username, String password) { Client client = getClient(); WebResource webResource = client.resource(scoredwnldUrlRoot + "/pascoredwnld/login"); String input = "{\"username\":\"" + username + "\",\"password\":\"" + password + "\"};"; ClientResponse response = webResource .accept("application/json") .type("application/json") .post(ClientResponse.class, input); if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } try { JSONObject json = new JSONObject(response.getEntity(String.class)); return String.valueOf(json.get("token")); } catch (Exception e) { log("Error: " + e.getMessage()); e.printStackTrace(); } return ""; }
@Test public void testCantAddDuplicatedResearcherUrl() throws InterruptedException, JSONException, URISyntaxException { String accessToken = getAccessToken(this.client1ClientId, this.client1ClientSecret, this.client1RedirectUri); assertNotNull(accessToken); Long now = System.currentTimeMillis(); ResearcherUrl rUrlToCreate = new ResearcherUrl(); rUrlToCreate.setUrl(new Url("http://newurl.com/" + now)); rUrlToCreate.setUrlName("url-name-" + System.currentTimeMillis()); rUrlToCreate.setVisibility(Visibility.PUBLIC); // Create it ClientResponse postResponse = memberV2ApiClient.createResearcherUrls(user1OrcidId, rUrlToCreate, accessToken); assertNotNull(postResponse); assertEquals(Response.Status.CREATED.getStatusCode(), postResponse.getStatus()); // Add it again postResponse = memberV2ApiClient.createResearcherUrls(user1OrcidId, rUrlToCreate, accessToken); assertNotNull(postResponse); assertEquals(Response.Status.CONFLICT.getStatusCode(), postResponse.getStatus()); // Check it can be created by other client String otherClientToken = getAccessToken(this.client2ClientId, this.client2ClientSecret, this.client2RedirectUri); postResponse = memberV2ApiClient.createResearcherUrls(user1OrcidId, rUrlToCreate, otherClientToken); assertNotNull(postResponse); assertEquals(Response.Status.CREATED.getStatusCode(), postResponse.getStatus()); }
@SuppressWarnings("deprecation") @Test public void testReferenceCatalogEntity() throws Exception { getManagementContext().getCatalog().addItem(BasicEntity.class); String yaml = "{ name: simple-app-yaml, location: localhost, services: [ { serviceType: " + BasicEntity.class.getName() + " } ] }"; ClientResponse response = client() .resource("/v1/applications") .entity(yaml, "application/x-yaml") .post(ClientResponse.class); assertTrue(response.getStatus() / 100 == 2, "response is " + response); // Expect app to be running URI appUri = response.getLocation(); waitForApplicationToBeRunning(response.getLocation()); assertEquals( client().resource(appUri).get(ApplicationSummary.class).getSpec().getName(), "simple-app-yaml"); ClientResponse response2 = client().resource(appUri.getPath()).delete(ClientResponse.class); assertEquals(response2.getStatus(), Response.Status.ACCEPTED.getStatusCode()); }
public static void main(String[] args) { try { Client client = Client.create(); WebResource webResource = client.resource("http://localhost:8080/TrainingDiaryPortal/api/downloadDb"); client.setReadTimeout(10000); client.setConnectTimeout(10000); ClientResponse response = webResource .path("") .queryParam("id", "1") .queryParam("channel", "mobile") .type("application/json") .get(ClientResponse.class); if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } System.out.println("Output from Server .... \n"); UserData output = response.getEntity(UserData.class); System.out.println(output); } catch (Exception e) { e.printStackTrace(); } }
/** Executes an API request */ private <T> T execute(WebResource webResource, String method, Class<T> returnClass) throws CIWiseRESTConnectorTokenExpiredException, CIWiseRESTConnectorException { /** Call HTTP Method */ if (connector.getToken() == null) { Token token = getXAuthToken(); if (token != null) { connector.setToken((String) token.getToken()); } } ClientResponse clientResponse = webResource .accept(MediaType.APPLICATION_JSON) .header("X-Auth-Token", connector.getToken()) .method(method, ClientResponse.class); if (clientResponse.getStatus() == 200) { return clientResponse.getEntity(returnClass); } else if (clientResponse.getStatus() == 401) { throw new CIWiseRESTConnectorTokenExpiredException( "The access token has expired; " + clientResponse.getEntity(String.class)); } else { throw new CIWiseRESTConnectorException( String.format( "ERROR - statusCode: %d - message: %s", clientResponse.getStatus(), clientResponse.getEntity(String.class))); } }
/* * The test will connect to VDC1 as local user, obtain a token, try to use it on VDC2. * Should fail as local users cannot do SSO. */ @Test public void localUserSSODenied() throws Exception { BalancedWebResource rRoot = createHttpsClient( EnvConfig.get("sanity", "geosvc.SSOTest.localUserSSODenied.username"), EnvConfig.get("sanity", "geosvc.SSOTest.localUserSSODenied.password"), baseUrls, true); _savedTokens.remove(EnvConfig.get("sanity", "geosvc.SSOTest.localUserSSODenied.username")); ClientResponse resp = rRoot.path("/tenant").get(ClientResponse.class); Assert.assertEquals(200, resp.getStatus()); String tokenFromVDC1 = (String) _savedTokens.get("root"); Assert.assertNotNull(tokenFromVDC1); // just verify on vdc1 the token we got is good against vdc1 resp = rRoot.path("/tenant").header(AUTH_TOKEN_HEADER, tokenFromVDC1).get(ClientResponse.class); Assert.assertEquals(200, resp.getStatus()); // use vdc1's token in vdc2's login resource with no other credentials. Verify this is rejected // (local user). BalancedWebResource rRootVDC2NoCreds = createHttpsClient("", "", Collections.singletonList(remoteVDCVIP), false); resp = rRootVDC2NoCreds .path("/tenant") .header(AUTH_TOKEN_HEADER, tokenFromVDC1) .get(ClientResponse.class); Assert.assertEquals(401, resp.getStatus()); }
// @Test public void testSubnetCascadingDelete() { // Create a subnet with several configuration pieces: option 3, // option 121, and a host assignment. Then delete it. ClientResponse response; DtoDhcpSubnet subnet = new DtoDhcpSubnet(); subnet.setSubnetPrefix("172.31.0.0"); subnet.setSubnetLength(24); subnet.setServerAddr("172.31.0.118"); response = resource() .uri(bridge.getDhcpSubnets()) .type(APPLICATION_DHCP_SUBNET_JSON) .post(ClientResponse.class, subnet); assertEquals(201, response.getStatus()); subnet = resource() .uri(response.getLocation()) .accept(APPLICATION_DHCP_SUBNET_JSON) .get(DtoDhcpSubnet.class); DtoDhcpHost host1 = new DtoDhcpHost(); host1.setMacAddr("02:33:44:55:00:00"); host1.setIpAddr("172.31.0.11"); host1.setName("saturn"); response = resource() .uri(subnet.getHosts()) .type(APPLICATION_DHCP_HOST_JSON) .post(ClientResponse.class, host1); assertEquals(201, response.getStatus()); // List the subnets response = resource() .uri(bridge.getDhcpSubnets()) .accept(APPLICATION_DHCP_SUBNET_COLLECTION_JSON) .get(ClientResponse.class); assertEquals(200, response.getStatus()); DtoDhcpSubnet[] subnets = response.getEntity(DtoDhcpSubnet[].class); assertThat("We expect 1 listed subnets.", subnets, arrayWithSize(1)); assertThat( "We expect the listed subnets to match the one we created.", subnets, arrayContainingInAnyOrder(subnet)); // Now delete the subnet. response = resource().uri(subnet.getUri()).delete(ClientResponse.class); assertEquals(204, response.getStatus()); // Show that the list of DHCP subnet configurations is empty. response = resource() .uri(bridge.getDhcpSubnets()) .accept(APPLICATION_DHCP_SUBNET_COLLECTION_JSON) .get(ClientResponse.class); assertEquals(200, response.getStatus()); subnets = response.getEntity(DtoDhcpSubnet[].class); assertThat("We expect 0 listed subnets.", subnets, arrayWithSize(0)); }
protected T get(URI uri) { ClientResponse response = ClientUtil.readEntity( uri, getHttpClient(), getResourceRepresentationType(), ClientResponse.class); if (logger.isDebugEnabled()) { logger.debug("Request Accept header: " + getResourceRepresentationType()); logger.debug("Response header: " + response.getType()); } final int status = response.getStatus(); if (followRedirectionEnabled && status == ClientResponse.Status.MOVED_PERMANENTLY.getStatusCode()) { final URI location = response.getLocation(); if (location != null) { this.thisResourceUri = location; this.absoluteThisResourceUri = generateAbsoluteUri(); return get(); } } if (followRedirectionEnabled && (status == ClientResponse.Status.FOUND.getStatusCode() || status == ClientResponse.Status.SEE_OTHER.getStatusCode())) { final URI location = response.getLocation(); if (location != null) { URI absolutionLocation = getHttpClient().getAbsoluteUri(location, getReferrerUri()); return get(absolutionLocation); } } if (status < 300 || (status == ClientResponse.Status.NOT_MODIFIED.getStatusCode())) { if (response.hasEntity() && response.getStatus() != ClientResponse.Status.NO_CONTENT.getStatusCode()) { lastReadStateOfEntity = response.getEntity(getEntityClass()); if (getClientUtil() != null) { try { getClientUtil().parseLinks(lastReadStateOfEntity, getRelatedResourceUris()); } catch (Exception ex) { logger.warn(ex.getMessage(), ex); } } if (invokeGet) { invokeGETOnNestedResources(); } } else { lastReadStateOfEntity = null; } getInvocationCount++; Map<String, Object> headers = new HashMap<String, Object>(); EntityTag tag = response.getEntityTag(); if (tag != null) { headers.put(HttpHeaders.ETAG, tag); } Date date = response.getLastModified(); if (date != null) { headers.put(HttpHeaders.LAST_MODIFIED, date); } cachedHeaders.put(uri.toString(), headers); return lastReadStateOfEntity; } throw new UniformInterfaceException(response); }
public void assertOk(final ClientResponse response) { if (response.getStatus() != 200) { System.out.println("-- NOT OK --"); System.out.println(response.getStatus()); System.out.println(response.getEntity(String.class)); } assertTrue(response.getStatus() == 200); }
public URI put(URI uri, Object entity, String mediaType) { ClientResponse response = resource().uri(uri).type(mediaType).put(ClientResponse.class, entity); if (response.getStatus() != 204 && response.getStatus() != 200) { handleHttpError(response); } return response.getLocation(); }
private boolean updateIssueInJira(Issue issue) { ClientResponse postResponse = restAccess.put("/issue/" + issue.getKey(), issue); if (postResponse.getStatus() >= Status.OK.getStatusCode() && postResponse.getStatus() <= Status.PARTIAL_CONTENT.getStatusCode()) { return true; } else { System.err.println("Problems while updating issue: " + postResponse.getEntity(String.class)); return false; } }
private String getData(String url) throws Exception { Client client = Client.create(); WebResource webResource = client.resource(url); ClientResponse response = webResource.accept("application/json").get(ClientResponse.class); if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } String[] d = url.split("/"); String machineId = d[d.length - 1]; return response.getEntity(String.class).replace("}", ", \"machine_id\":\"" + machineId + "\"}"); }
private String requestUserId() { Client client = Client.create(); String env = "http://www.mancala.xyz:8080/"; WebResource webResource = client.resource(env + "users"); ClientResponse response = webResource.accept("application/json").post(ClientResponse.class); if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } return response.getEntity(String.class); }
public static List<PatientSearchResult> getDynamicSearch( List<DynamicSearchCriteria> criteria, String stateRelation, String userToken) { // Use a form because there are an unknown number of values MultivaluedMap form = new MultivaluedMapImpl(); // stateRelation is how the criteria are logically related "AND", "OR" form.add("stateRelation", stateRelation); int i = 0; // Step through all criteria given, the form fields are appended with an integer // to maintain grouping in REST call (dataGroup0, dataGroup1...) for (DynamicSearchCriteria dcriteria : criteria) { form.add("sourceName" + i, dcriteria.getDataGroup()); form.add("itemName" + i, dcriteria.getField()); form.add("operator" + i, dcriteria.getOperator().getValue()); form.add("value" + i, dcriteria.getValue()); i++; } ClientConfig cc = new DefaultClientConfig(); cc.getClasses().add(JacksonJsonProvider.class); Client client = Client.create(); WebResource resource = client.resource(APIURLHolder.getUrl() + "/nbia-api/services/getDynamicSearch"); ClientResponse response = resource .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_FORM_URLENCODED) .header("Authorization", "Bearer " + userToken) .post(ClientResponse.class, form); // check response status code if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } // display response String output = response.getEntity(String.class); List<PatientSearchResultImpl> myObjects; try { // Object json = mapper.readValue(output, Object.class); // String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json); // logger.info("Returned JSON\n"+indented); myObjects = mapper.readValue(output, new TypeReference<List<PatientSearchResultImpl>>() {}); } catch (Exception e) { e.printStackTrace(); return null; } List<PatientSearchResult> returnValue = new ArrayList<PatientSearchResult>(); for (PatientSearchResultImpl result : myObjects) { returnValue.add(result); } return returnValue; }
@Test(dependsOnMethods = "testGetTraitNames") public void testAddTraitWithAttribute() throws Exception { final String traitName = "PII_Trait" + randomString(); HierarchicalTypeDefinition<TraitType> piiTrait = TypesUtil.createTraitTypeDef( traitName, ImmutableList.<String>of(), TypesUtil.createRequiredAttrDef("type", DataTypes.STRING_TYPE)); String traitDefinitionAsJSON = TypesSerialization$.MODULE$.toJson(piiTrait, true); LOG.debug("traitDefinitionAsJSON = " + traitDefinitionAsJSON); createType(traitDefinitionAsJSON); Struct traitInstance = new Struct(traitName); traitInstance.set("type", "SSN"); String traitInstanceAsJSON = InstanceSerialization.toJson(traitInstance, true); LOG.debug("traitInstanceAsJSON = " + traitInstanceAsJSON); final String guid = tableId._getId(); ClientResponse clientResponse = service .path(ENTITIES) .path(guid) .path(TRAITS) .accept(Servlets.JSON_MEDIA_TYPE) .type(Servlets.JSON_MEDIA_TYPE) .method(HttpMethod.POST, ClientResponse.class, traitInstanceAsJSON); Assert.assertEquals(clientResponse.getStatus(), Response.Status.CREATED.getStatusCode()); String responseAsString = clientResponse.getEntity(String.class); Assert.assertNotNull(responseAsString); JSONObject response = new JSONObject(responseAsString); Assert.assertNotNull(response.get(AtlasClient.REQUEST_ID)); Assert.assertNotNull(response.get(AtlasClient.GUID)); // verify the response clientResponse = getEntityDefinition(guid); Assert.assertEquals(clientResponse.getStatus(), Response.Status.OK.getStatusCode()); responseAsString = clientResponse.getEntity(String.class); Assert.assertNotNull(responseAsString); response = new JSONObject(responseAsString); Assert.assertNotNull(response.get(AtlasClient.REQUEST_ID)); final String definition = response.getString(AtlasClient.DEFINITION); Assert.assertNotNull(definition); Referenceable entityRef = InstanceSerialization.fromJsonReferenceable(definition, true); IStruct traitRef = entityRef.getTrait(traitName); String type = (String) traitRef.get("type"); Assert.assertEquals(type, "SSN"); }
public String registrarEncuentroOpenmrs(Encuentro encuentro) { String mensaje = "no registrado"; String fecha = encuentro.getFechaTime(); String pacienteEncuentro = encuentro.getPaciente(); String medicoEncuentro = encuentro.getMedico(); String tipoencuentro = encuentro.getTipoEncuentro(); System.out.println(fecha); // 9fed5cb8-2af5-4ba2-a475-a2d8bc604d50 aps // 8af7f6b9-832e-4ff7-9a26-12817abd4bc2 control try { ClientConfig clientConfig = new DefaultClientConfig(); Client client = Client.create(clientConfig); client.addFilter(new HTTPBasicAuthFilter("admin", "Admin123")); WebResource webResource = client.resource("http://localhost:8080/openmrs/ws/rest/v1/encounter"); String input = "{\"encounterDatetime\" :\"" + fecha + "\",\"patient\":\"" + pacienteEncuentro + "\", \"encounterType\":\"" + tipoencuentro + "\",\"provider\":\"" + medicoEncuentro + "\" }"; ClientResponse response = webResource.type("application/json").post(ClientResponse.class, input); if (response.getStatus() != 201) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } if (response.getStatus() == 201) { String respuesta = "{\"results\":[" + response.getEntity(String.class) + "]}"; String personaUuid = Transformar.jsonPersonaUud(respuesta); return personaUuid; } else { return mensaje; } } catch (Exception e) { e.printStackTrace(); return mensaje; } }