/** 创建/更新/删除任务. */ @Test @Category(Smoke.class) public void createUpdateAndDeleteTask() { // create Task task = TaskData.randomTask(); URI createdTaskUri = restTemplate.postForLocation(resourceUrl, task); System.out.println(createdTaskUri.toString()); Task createdTask = restTemplate.getForObject(createdTaskUri, Task.class); assertThat(createdTask.getTitle()).isEqualTo(task.getTitle()); // update String id = StringUtils.substringAfterLast(createdTaskUri.toString(), "/"); task.setId(new Long(id)); task.setTitle(TaskData.randomTitle()); restTemplate.put(createdTaskUri, task); Task updatedTask = restTemplate.getForObject(createdTaskUri, Task.class); assertThat(updatedTask.getTitle()).isEqualTo(task.getTitle()); // delete restTemplate.delete(createdTaskUri); try { restTemplate.getForObject(createdTaskUri, Task.class); fail("Get should fail while feth a deleted task"); } catch (HttpStatusCodeException e) { assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } }
public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); String getAccessTokenUrl = String.format( "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", PropertyHolder.APPID, PropertyHolder.APPSECRET); String retData = restTemplate.getForObject(getAccessTokenUrl, String.class, new HashMap<String, Object>()); System.out.println("[Acess Token returned data] " + retData); JSONObject jsonObject = JSON.parseObject(retData); String accessToken = jsonObject.getString("access_token"); String jsapiTicketUrl = String.format( "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi", accessToken); retData = restTemplate.getForObject(jsapiTicketUrl, String.class, new HashMap<String, Object>()); System.out.println("[jsapiTicketUrl returned data] " + retData); jsonObject = JSON.parseObject(retData); String jsapi_ticket = jsonObject.getString("ticket"); String url = "http://cai.songdatech.com/crab/?buy_type=card"; Map<String, String> ret = sign(jsapi_ticket, url); for (Map.Entry entry : ret.entrySet()) { System.out.println(entry.getKey() + ", " + entry.getValue()); } }
/** * Gets the cloud ci. * * @param ns the ns * @param ciName the ci name * @return the cloud ci */ public CmsCISimple getCloudCi(String ns, String ciName) { try { CmsCISimple[] mgmtClouds = restTemplate.getForObject( serviceUrl + "cm/simple/cis?nsPath={nsPath}&ciClassName={mgmtCloud}&ciName={ciName}", new CmsCISimple[0].getClass(), ns, mgmtCloud, ciName); if (mgmtClouds.length > 0) { return mgmtClouds[0]; } CmsCISimple[] acctClouds = restTemplate.getForObject( serviceUrl + "cm/simple/cis?nsPath={nsPath}&ciClassName={acctCloud}&ciName={ciName}", new CmsCISimple[0].getClass(), ns, acctCloud, ciName); if (acctClouds.length > 0) { return acctClouds[0]; } return null; } catch (RestClientException ce) { logger.error("Broker can not connect to cms api to authenticate the user:" + ce.getMessage()); throw ce; } }
/* @RequestMapping(value="/status",produces = MediaType.APPLICATION_JSON_VALUE,method = RequestMethod.GET) public String getStatusOfDriver(Model model) { model.addAttribute("status",get) }*/ public static void main(String[] args) { final String uri = "http://localhost:4444/wd/hub/status"; RestTemplate restTemplate = new RestTemplate(); String result = restTemplate.getForObject(uri, String.class); DriverStatus driver = restTemplate.getForObject(uri, DriverStatus.class); System.out.println(result); System.out.println(driver.getState() + " " + driver.getSessionId()); System.out.println(driver); }
public PublicKey retrieveJwkKey(String jwkUrl) { RSAPublicKey pub = null; try { String jwkString = restTemplate.getForObject(jwkUrl, String.class); JsonObject json = (JsonObject) new JsonParser().parse(jwkString); JsonArray getArray = json.getAsJsonArray("keys"); for (int i = 0; i < getArray.size(); i++) { JsonObject object = getArray.get(i).getAsJsonObject(); String algorithm = object.get("alg").getAsString(); if (algorithm.equals("RSA")) { byte[] modulusByte = Base64.decodeBase64(object.get("mod").getAsString()); BigInteger modulus = new BigInteger(1, modulusByte); byte[] exponentByte = Base64.decodeBase64(object.get("exp").getAsString()); BigInteger exponent = new BigInteger(1, exponentByte); RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, exponent); KeyFactory factory = KeyFactory.getInstance("RSA"); pub = (RSAPublicKey) factory.generatePublic(spec); } } } catch (HttpClientErrorException e) { logger.error("HttpClientErrorException in KeyFetcher.java: ", e); } catch (NoSuchAlgorithmException e) { logger.error("NoSuchAlgorithmException in KeyFetcher.java: ", e); } catch (InvalidKeySpecException e) { logger.error("InvalidKeySpecException in KeyFetcher.java: ", e); } return pub; }
@Override protected void onHandleIntent(Intent intent) { ApplicationController app = ((ApplicationController) getApplicationContext()); UsuarioDTO user = app.getUserLogin(); Map<String, Integer> parms = new HashMap<String, Integer>(); parms.put("id", user.getId()); restTemp.setErrorHandler(new RestResponseErrorHandler<String>(String.class)); Intent intentBack = new Intent(Constantes.GET_AMIGOS_FILTRO_ACTION); try { UsuarioDTO[] respuesta = restTemp.getForObject(Constantes.GET_AMIGOS_SERVICE_URL, UsuarioDTO[].class, parms); intentBack.putExtra("respuesta", Util.getArrayListUsuarioDTO(respuesta)); } catch (RestResponseException e) { String msg = e.getMensaje(); intentBack.putExtra("error", msg); } catch (ResourceAccessException e) { Log.e(TAG, e.getMessage()); intentBack.putExtra("error", Constantes.MSG_ERROR_TIMEOUT); } this.sendBroadcast(intentBack); }
@Test public void hidesStsMilestoneDownloadsIfNotAvailable() throws Exception { String responseXml = Fixtures.load("/fixtures/tools/sts_downloads_without_milestones.xml"); stub(restTemplate.getForObject(anyString(), eq(String.class))).toReturn(responseXml); MvcResult mvcResult = mockMvc .perform(get("/tools/sts/all")) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith("text/html")) .andReturn(); Document document = Jsoup.parse(mvcResult.getResponse().getContentAsString()); assertThat( document.select(".milestone--release h2.tool-versions--version").text(), not(allOf(containsString("STS"), containsString(".M")))); assertThat( document.select(".milestone--release .item--dropdown a").attr("href"), not( allOf( containsString("http://download.springsource.com/milestone/STS/"), containsString("spring-tool-suite"), containsString("win32-installer.exe")))); }
@Override protected ItemGridModel[] doInBackground(Integer... args) { try { RestTemplate restTemplate = new RestTemplate(); HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory(); httpRequestFactory.setConnectTimeout(10 * 1000); httpRequestFactory.setReadTimeout(10 * 1000); restTemplate.setRequestFactory(httpRequestFactory); String url = Constant.URL_SERVICE; restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); return restTemplate.getForObject(url, ItemGridModel[].class); } catch (ResourceAccessException e) { Log.e(Constant.TAG, "Error update grid", e); } catch (Exception e) { Log.e(Constant.TAG, "Error update grid", e); } return null; }
/** Tests accessing to an existing warehouse */ @Test public void getWarehouse() { String uri = "http://localhost:8080/rest_test/spring/warehouses/{warehouseId}"; Warehouse warehouse = restTemplate.getForObject(uri, Warehouse.class, WAREHOUSE_ID); assertNotNull(warehouse); assertEquals("WAR_BCN_004", warehouse.getName()); }
@Override public Methods getMethods(String apiKey) { MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>(); if (apiKey != null) parameters.set("api_key", apiKey); return restTemplate.getForObject( buildUri("flickr.reflection.getMethods", parameters), Methods.class); }
public ArrayList getApplications(String keyword, UserDetails userDetails) { ArrayList applications = new ArrayList(); Gson gson = new Gson(); try { String urlString = "http://localhost:9093/prp-ws/hello/applications/" + keyword + "/" + userDetails.getUsername(); RestTemplate restTemplate = new RestTemplate(); String response = restTemplate.getForObject(urlString, String.class); Type listOfTestObject = new TypeToken<List<PrpAplctnEntity>>() {}.getType(); ArrayList<PrpAplctnEntity> list = gson.fromJson(response, listOfTestObject); for (int i = 0; i < list.size(); i++) { applications.add(list.get(i)); } } catch (Exception e) { e.printStackTrace(); } return applications; }
@Override protected Boolean doInBackground(HelpPost... arg0) { try { final String url = getMainApplication().getRestBaseUrl() + "/sendacceptnotification?" + "facebookId=" + arg0[0].getUserId() + "&" + "firstName=" + getMainApplication().getData("firstName") + "&" + "lastName=" + getMainApplication().getData("lastName") + "&" + "postId=" + arg0[0].getUserId() + "_" + arg0[0].getTime(); RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter()); return restTemplate.getForObject(new URI(url), Boolean.class); } catch (Exception e) { Log.e(TAG, e.getMessage(), e); } return false; }
/** 查看任务列表. */ @Test @Category(Smoke.class) public void listTasks() { TaskList tasks = restTemplate.getForObject(resourceUrl, TaskList.class); assertThat(tasks).hasSize(5); assertThat(tasks.get(0).getTitle()).isEqualTo("Study PlayFramework 2.0"); }
public void loadData() { final String uri = "http://api.fixer.io/latest"; RestTemplate restTemplate = new RestTemplate(); result = restTemplate.getForObject(uri, CurrencyObject.class); System.out.println(result.getRates().size()); }
@Override public List<Photo> search( String swLat, String swLng, String neLat, String neLng, String level, String width, String height, String term, String type) { Map<String, String> urlVariables = new HashMap<String, String>(); return restTemplate.getForObject( BASE_API_URL + "/panoramio/search?swlat={swLat}&swlng={swLng}&nelat={neLat}&nelng={neLng}&level={level}&width={width}&height={height}&term={term}&type={type}", com.mdtech.social.api.model.PhotoList.class, swLat, swLng, neLat, neLng, level, width, height, term, type); }
@Override protected Void doInBackground(Void... params) { try { EditText nombre = (EditText) findViewById(R.id.editText14); EditText descripcion = (EditText) findViewById(R.id.editText15); MyApp userURL = ((MyApp) getApplication()); String email = userURL.getUsuarioLogeado().getEmail(); final String url = userURL.getUrlServicio() + "/ServiceDiscoteca/Ingresar/" + nombre.getText().toString() + "/" + email + "/" + descripcion.getText().toString() + "/Image"; RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); restTemplate.getForObject(url, Void.class); Toast.makeText( getApplicationContext(), "Se ha registrado la discoteca " + nombre.getText().toString(), Toast.LENGTH_SHORT) .show(); } catch (Exception e) { Log.e("Cliente Rest", e.getMessage(), e); } return null; }
@Test public void loginWithOauth2Authentication() throws MalformedURLException { String token = "12345678"; RestTemplate restTemplate = mock(RestTemplate.class); ClientHttpRequestFactory clientHttpRequestFactory = mock(ClientHttpRequestFactory.class); RestUtil restUtil = mock(RestUtil.class); OAuth2AccessToken oauthToken = mock(OAuth2AccessToken.class); when(restUtil.createRestTemplate(any(HttpProxyConfiguration.class))).thenReturn(restTemplate); when(restUtil.createRequestFactory(any(HttpProxyConfiguration.class))) .thenReturn(clientHttpRequestFactory); when(restTemplate.getForObject(eq("http://api.cloud.me/info"), any(Class.class))) .thenReturn(INFO_WITH_AUTH); when(restUtil.createOauthClient(any(URL.class), any(HttpProxyConfiguration.class))) .thenReturn(new OauthClient(new URL("http://uaa.cloud.me"), restTemplate)); when(restTemplate.execute( eq("http://uaa.cloud.me/oauth/authorize"), eq(HttpMethod.POST), any(RequestCallback.class), any(ResponseExtractor.class), any(Map.class))) .thenReturn(oauthToken); when(oauthToken.getValue()).thenReturn(token); when(oauthToken.getTokenType()).thenReturn("bearer"); // Run Test CloudControllerClientFactory ccf = new CloudControllerClientFactory(restUtil, null); CloudControllerClient ccc = ccf.newCloudController( new URL("http://api.cloud.me"), new CloudCredentials("*****@*****.**", "passwd"), null); String loginToken = ccc.login(); assertThat(loginToken, is("bearer " + token)); }
/** * Adapter for spotify's lookup api * * @param spotifyId - id of track, has to start with "spotify:track:" * @return Track with given id * @throws SpotifyApiException - Error contacting spotify, * @throws IllegalArgumentException - Is thrown when trying to fetch data that isn't a track */ private SpotifyLookupContainer requestSpotifySong(String spotifyId) throws SpotifyApiException { RestTemplate rest = new RestTemplate(); SpotifyLookupContainer response = null; if (spotifyId.indexOf("spotify:track:") != 0) { // trying to look up something that isn't a track throw new IllegalArgumentException(); } try { logger.debug("Fetching spotifysong with uri: " + spotifyId); String jsonResponse = rest.getForObject("http://ws.spotify.com/lookup/1/.json?uri=" + spotifyId, String.class); response = gson.fromJson( jsonResponse, SpotifyLookupContainer .class); // use gson rather than built in spring deserializer which needs the // object to match all fields if (!isPlayable(response.getTrack())) { logger.debug( "Song " + response.getTrack().getName() + " is not playable in Norway, ignoring"); throw new IllegalArgumentException("Song not playable in Norway"); } } catch (RestClientException e) { logger.error( "Exception while fetching spotifySong " + spotifyId + " error: " + e.getMessage()); throw new SpotifyApiException(e.getMessage()); } return response; }
@Test public void loginWithNonOauthAuthentication() throws MalformedURLException { String token = "12345678"; Map<String, String> tokenResponse = new HashMap<String, String>(); tokenResponse.put("token", token); RestTemplate restTemplate = mock(RestTemplate.class); ClientHttpRequestFactory clientHttpRequestFactory = mock(ClientHttpRequestFactory.class); RestUtil restUtil = mock(RestUtil.class); when(restUtil.createRestTemplate(any(HttpProxyConfiguration.class))).thenReturn(restTemplate); when(restUtil.createRequestFactory(any(HttpProxyConfiguration.class))) .thenReturn(clientHttpRequestFactory); when(restTemplate.getForObject(eq("http://api.cloud.me/info"), any(Class.class))) .thenReturn(INFO_WITHOUT_AUTH); when(restTemplate.postForObject( eq("http://api.cloud.me/users/{id}/tokens"), any(Object.class), any(Class.class), any(Object[].class))) .thenReturn(tokenResponse); // Run Test CloudControllerClientFactory ccf = new CloudControllerClientFactory(restUtil, null); CloudControllerClient ccc = ccf.newCloudController( new URL("http://api.cloud.me"), new CloudCredentials("*****@*****.**", "passwd"), null); String loginToken = ccc.login(); assertThat(loginToken, is(token)); }
@Test public void loginWithWrongPassword() throws MalformedURLException { thrown.expect(CloudFoundryException.class); RestTemplate restTemplate = mock(RestTemplate.class); ClientHttpRequestFactory clientHttpRequestFactory = mock(ClientHttpRequestFactory.class); RestUtil restUtil = mock(RestUtil.class); when(restUtil.createRestTemplate(any(HttpProxyConfiguration.class))).thenReturn(restTemplate); when(restUtil.createRequestFactory(any(HttpProxyConfiguration.class))) .thenReturn(clientHttpRequestFactory); when(restTemplate.getForObject(eq("http://api.cloud.me/info"), any(Class.class))) .thenReturn(INFO_WITH_AUTH); when(restUtil.createOauthClient(any(URL.class), any(HttpProxyConfiguration.class))) .thenReturn(new OauthClient(new URL("http://uaa.cloud.me"), restTemplate)); when(restTemplate.execute( eq("http://uaa.cloud.me/oauth/authorize"), eq(HttpMethod.POST), any(RequestCallback.class), any(ResponseExtractor.class), any(Map.class))) .thenThrow( new CloudFoundryException(HttpStatus.UNAUTHORIZED, "Error requesting access token.")); // Run Test CloudControllerClientFactory ccf = new CloudControllerClientFactory(restUtil, null); CloudControllerClient ccc = ccf.newCloudController( new URL("http://api.cloud.me"), new CloudCredentials("*****@*****.**", "badpasswd"), null); ccc.login(); }
public String getStudyHost(String studyOid) throws Exception { String ocUrl = CoreResources.getField("sysURL.base") + "rest2/openrosa/" + studyOid; String pManageUrl = CoreResources.getField("portalURL"); String pManageUrlFull = pManageUrl + "/app/rest/oc/authorizations?studyoid=" + studyOid + "&instanceurl=" + ocUrl; CommonsClientHttpRequestFactory requestFactory = new CommonsClientHttpRequestFactory(); requestFactory.setReadTimeout(PARTICIPATE_READ_TIMEOUT); RestTemplate rest = new RestTemplate(requestFactory); try { Authorization[] response = rest.getForObject(pManageUrlFull, Authorization[].class); if (response.length > 0 && response[0].getStudy() != null && response[0].getStudy().getHost() != null && !response[0].getStudy().getHost().equals("")) { URL url = new URL(pManageUrl); String port = ""; if (url.getPort() > 0) port = ":" + String.valueOf(url.getPort()); return url.getProtocol() + "://" + response[0].getStudy().getHost() + "." + url.getHost() + port + "/#/login"; } } catch (Exception e) { logger.error(e.getMessage()); logger.error(ExceptionUtils.getStackTrace(e)); } return ""; }
public Account getByNumber(String accountNumber) { Account account = restTemplate.getForObject(serviceUrl + "/accounts/{number}", Account.class, accountNumber); if (account == null) throw new AccountNotFoundException(accountNumber); else return account; }
@Override protected String doInBackground(String... params) { ConnectivityManager connectivityManager = (ConnectivityManager) MainActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo; activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); if (activeNetworkInfo == null || !activeNetworkInfo.isConnected()) { MainActivity.this.runOnUiThread( new Runnable() { public void run() { Toast.makeText( MainActivity.this, "Connect to the internet to view tests.", Toast.LENGTH_SHORT) .show(); } }); String cs = prefs.getString("children", "[]"); children = new JsonParser().parse(cs).getAsJsonArray(); } else { try { RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(new StringHttpMessageConverter()); String rawJson = restTemplate.getForObject( "https://www.localresearch.com/api/profile/ucla-test-bank/", String.class); JsonElement object = new JsonParser().parse(rawJson); children = object .getAsJsonObject() .get("sections") .getAsJsonArray() .get(0) .getAsJsonObject() .get("highlights") .getAsJsonArray(); prefs.edit().putString("children", children.toString()).apply(); } catch (Exception e) { children = new JsonParser().parse(prefs.getString("children", "[]")).getAsJsonArray(); MainActivity.this.runOnUiThread( new Runnable() { public void run() { Toast.makeText( MainActivity.this, "An error occurred while updating tests. This may be caused by poor internet connection.", Toast.LENGTH_SHORT) .show(); } }); } } values.clear(); for (JsonElement child : children) { Log.d("LOG", child.getAsJsonObject().get("name").getAsString()); values.add(child.getAsJsonObject().get("name").getAsString()); } return null; }
@Override public void run(String... strings) throws Exception { RestTemplate restTemplate = new RestTemplate(); Quote quote = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote.class); log.info(quote.toString()); System.exit(0); }
public StarBabay.Model getStarbabayData(RestTemplate restTemplate) { cnpClient.configureRequest(); HashMap<String, String> params = cnpClient.getParamsforGet(); return restTemplate.getForObject( "http://api.chinaxueqian.com/school/babay/?" + "token={token}&uuid={uuid}&sid={sid}", StarBabay.Model.class, params); }
public List<HashMap<?, ?>> getWall(String userName) { List<HashMap<?, ?>> messages = new ArrayList<HashMap<?, ?>>( restTemplate .getForObject(baseURL + userName + "/wall.json", Resources.class) .getContent()); return messages; }
/** 根据参数Class<T> responseType responseType 去找对应 @link{HttpMessageConverter }转换响应内容 */ @Test public void test_getForObject1() { RestTemplate restTemplate = new RestTemplate(); String forObject = restTemplate.getForObject("http://www.baidu.com/baidu?wd=csdn&tn=monline_dg", String.class); System.out.println(forObject); }
@Override public List<Photo> getPanoramio(String... params) { return restTemplate.getForObject( BASE_API_URL + "/panoramio?swlat={swLat}&swlng={swLng}&nelat={neLat}&nelng={neLng}&level={level}", com.mdtech.social.api.model.PhotoList.class, params); }
// TODO: change to /account/{user} public Account getAccount(String user) { logger.debug("Looking for account with userId: " + user); Account account = restTemplate.getForObject("http://accounts/account/?name={user}", Account.class, user); logger.debug("Got Account: " + account); return account; }
/** * Get the status of a job id. The returned JSON will look like: {"all_judgments": 50, * "golden_judgments": 5, "tainted_judgments": 15, "needed_judgments": 20} * * @param jobId * @return JsonNode containing the status as supplied by Crowdflower */ JsonNode getStatus(String jobId) { RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter()); JsonNode result = restTemplate.getForObject(pingURL, JsonNode.class, jobId, apiKey); return result; }