List of usage examples for org.springframework.web.util UriComponentsBuilder fromHttpUrl
public static UriComponentsBuilder fromHttpUrl(String httpUrl)
From source file:com.haulmont.restapi.controllers.FileUploadController.java
protected ResponseEntity<FileInfo> createFileInfoResponseEntity(HttpServletRequest request, FileDescriptor fd) { FileInfo fileInfo = new FileInfo(fd.getId(), fd.getName(), fd.getSize()); UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(request.getRequestURL().toString()) .path("/{id}").buildAndExpand(fd.getId().toString()); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setLocation(uriComponents.toUri()); return new ResponseEntity<>(fileInfo, httpHeaders, HttpStatus.CREATED); }
From source file:org.cloudfoundry.identity.uaa.integration.feature.AutologinIT.java
public void testAutologinFlow(String contentType, Map body) throws Exception { webDriver.get(baseUrl + "/logout.do"); HttpHeaders headers = getAppBasicAuthHttpHeaders(); headers.add(HttpHeaders.CONTENT_TYPE, contentType); ResponseEntity<Map> autologinResponseEntity = restOperations.exchange(baseUrl + "/autologin", HttpMethod.POST, new HttpEntity<>(body, headers), Map.class); String autologinCode = (String) autologinResponseEntity.getBody().get("code"); String authorizeUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/authorize") .queryParam("redirect_uri", appUrl).queryParam("response_type", "code") .queryParam("scope", "openid").queryParam("client_id", "app").queryParam("code", autologinCode) .build().toUriString();// w ww. ja v a 2 s. co m webDriver.get(authorizeUrl); webDriver.get(baseUrl); Assert.assertEquals(testAccounts.getUserName(), webDriver.findElement(By.cssSelector(".header .nav")).getText()); IntegrationTestUtils.validateAccountChooserCookie(baseUrl, webDriver, IdentityZoneHolder.get()); }
From source file:org.mitre.discovery.web.DiscoveryEndpoint.java
@RequestMapping(value = { "/" + WEBFINGER_URL }, produces = MediaType.APPLICATION_JSON_VALUE) public String webfinger(@RequestParam("resource") String resource, @RequestParam(value = "rel", required = false) String rel, Model model) { if (!Strings.isNullOrEmpty(rel) && !rel.equals("http://openid.net/specs/connect/1.0/issuer")) { logger.warn("Responding to webfinger request for non-OIDC relation: " + rel); }//from w ww .j av a 2 s.c o m if (!resource.equals(config.getIssuer())) { // it's not the issuer directly, need to check other methods UriComponents resourceUri = WebfingerURLNormalizer.normalizeResource(resource); if (resourceUri != null && resourceUri.getScheme() != null && resourceUri.getScheme().equals("acct")) { // acct: URI (email address format) // check on email addresses first UserInfo user = userService .getByEmailAddress(resourceUri.getUserInfo() + "@" + resourceUri.getHost()); if (user == null) { // user wasn't found, see if the local part of the username matches, plus our issuer host user = userService.getByUsername(resourceUri.getUserInfo()); // first part is the username if (user != null) { // username matched, check the host component UriComponents issuerComponents = UriComponentsBuilder.fromHttpUrl(config.getIssuer()) .build(); if (!Strings.nullToEmpty(issuerComponents.getHost()) .equals(Strings.nullToEmpty(resourceUri.getHost()))) { logger.info("Host mismatch, expected " + issuerComponents.getHost() + " got " + resourceUri.getHost()); model.addAttribute(HttpCodeView.CODE, HttpStatus.NOT_FOUND); return HttpCodeView.VIEWNAME; } } else { // if the user's still null, punt and say we didn't find them logger.info("User not found: " + resource); model.addAttribute(HttpCodeView.CODE, HttpStatus.NOT_FOUND); return HttpCodeView.VIEWNAME; } } } else { logger.info("Unknown URI format: " + resource); model.addAttribute(HttpCodeView.CODE, HttpStatus.NOT_FOUND); return HttpCodeView.VIEWNAME; } } // if we got here, then we're good, return ourselves model.addAttribute("resource", resource); model.addAttribute("issuer", config.getIssuer()); return "webfingerView"; }
From source file:org.appverse.web.framework.backend.test.util.frontfacade.mvc.tests.predefined.BasicAuthEndPointsServiceEnabledPredefinedTests.java
@Test public void basicAuthenticationRemoteLogServiceEnabledWithoutCsrfTokenTest() throws Exception { RemoteLogRequestVO logRequestVO = new RemoteLogRequestVO(); logRequestVO.setMessage("Test mesage!"); logRequestVO.setLogLevel("DEBUG"); HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", "Basic " + new String(Base64.encode((getUsername() + ":" + getPassword()).getBytes("UTF-8")))); HttpEntity<RemoteLogRequestVO> entity = new HttpEntity<RemoteLogRequestVO>(logRequestVO, headers); UriComponentsBuilder builder = UriComponentsBuilder .fromHttpUrl("http://localhost:" + port + baseApiPath + remoteLogEndpointPath); ResponseEntity<String> responseEntity = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST, entity, String.class); assertEquals(HttpStatus.FORBIDDEN, responseEntity.getStatusCode()); }
From source file:com.haulmont.restapi.controllers.EntitiesController.java
@PostMapping("/{entityName}") public ResponseEntity<String> createEntity(@RequestBody String entityJson, @PathVariable String entityName, @RequestParam(required = false) String modelVersion, HttpServletRequest request) { CreatedEntityInfo entityInfo = entitiesControllerManager.createEntity(entityJson, entityName, modelVersion); UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(request.getRequestURL().toString()) .path("/{id}").buildAndExpand(entityInfo.getId().toString()); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setLocation(uriComponents.toUri()); return new ResponseEntity<>(entityInfo.getJson(), httpHeaders, HttpStatus.CREATED); }
From source file:com.orange.ngsi2.client.Ngsi2Client.java
/** * Retrieve a list of Entities// w ww . j a v a2 s .c o m * @param ids an optional list of entity IDs (cannot be used with idPatterns) * @param idPattern an optional pattern of entity IDs (cannot be used with ids) * @param types an optional list of types of entity * @param attrs an optional list of attributes to return for all entities * @param query an optional Simple Query Language query * @param geoQuery an optional Geo query * @param orderBy an option list of attributes to difine the order of entities * @param offset an optional offset (0 for none) * @param limit an optional limit (0 for none) * @param count true to return the total number of matching entities * @return a pagined list of Entities */ public ListenableFuture<Paginated<Entity>> getEntities(Collection<String> ids, String idPattern, Collection<String> types, Collection<String> attrs, String query, GeoQuery geoQuery, Collection<String> orderBy, int offset, int limit, boolean count) { UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseURL); builder.path("v2/entities"); addParam(builder, "id", ids); addParam(builder, "idPattern", idPattern); addParam(builder, "type", types); addParam(builder, "attrs", attrs); addParam(builder, "query", query); addGeoQueryParams(builder, geoQuery); addParam(builder, "orderBy", orderBy); addPaginationParams(builder, offset, limit); if (count) { addParam(builder, "options", "count"); } return adaptPaginated(request(HttpMethod.GET, builder.toUriString(), null, Entity[].class), offset, limit); }
From source file:it.scoppelletti.wui.ActivityPanelAction.java
/** * Elenco delle categorie.//from w w w . j a v a 2s .c om * * @param applList Applicazioni. * @return Collezione. */ private List<String> listCategories(List<String> applList) { String uri; UriComponentsBuilder uriBuilder; ActivityCategoryListResource catgRes; List<String> categoryList, list; Map<String, String> map; map = new HashMap<String, String>(); for (String ctxPath : applList) { uriBuilder = UriComponentsBuilder.fromHttpUrl(myApplMgr.getBaseUrl()); uriBuilder.path(ctxPath).path(ActivityCategoryListResource.PATH); uriBuilder.queryParam(AbstractServerResource.QUERY_LOCALE, getLocale().toString()); uri = uriBuilder.build().toUriString(); catgRes = ClientResource.create(uri, ActivityCategoryListResource.class); try { list = catgRes.listCategories(); } catch (Exception ex) { myLogger.error(String.format("Failed to get %1$s.", uri), ex); continue; } if (list == null) { myLogger.error("Failed to get {}.", uri); continue; } for (String catg : list) { addCategory(map, Strings.trim(catg)); } } categoryList = new ArrayList<String>(map.values()); Collections.sort(categoryList); return categoryList; }
From source file:gov.fda.open.demo.service.FDADataProxyServiceImplTest.java
/** * Test get drug adverse summary./* w w w . j a v a 2 s.c o m*/ */ @Test public void testGetDrugAdverseSummary() { // Execute GetDrugAdverseSummaryRequest request = new GetDrugAdverseSummaryRequest(DRUG_NAME_2); // Setup Mock SearchTermBuilder searchParamBuilder = new SearchTermBuilder(); searchParamBuilder.exists(request.getSummaryType().getField()).and() .appendTerm(MEDICINAL_PRODUCT, request.getDrugName()).and() .between(RECEIVED_DATE, request.getStartDate(), request.getEndDate()); // build query String String searchTerm = searchParamBuilder.toString(); StringBuilder drugURL = new StringBuilder(URI_VALUE); drugURL.append(FDADataProxyServiceImpl.DRUG_EVENT_SEARCH_URL); final Map<String, String> params = new HashMap<String, String>(); params.put(SEARCH_KEY, searchTerm); params.put(APP_KEY, APP_VALUE); params.put(LIMIT_KEY, String.valueOf(100)); params.put(SKIP_KEY, String.valueOf(0)); URI httpUri = UriComponentsBuilder.fromHttpUrl(drugURL.toString()).buildAndExpand(params).toUri(); when(template.getForObject(httpUri, String.class)).thenReturn(jsonString); // Execute GetDrugAdverseSummaryResponse response = fdaDataProxyService.getDrugAdverseSummary(request); // Verify assertNotNull(response); assertTrue(response.isSuccess()); assertNull(response.getMessage()); // Execute for message request = new GetDrugAdverseSummaryRequest(DRUG_NAME_2, null, null, null, 10); response = fdaDataProxyService.getDrugAdverseSummary(request); // Verify assertNotNull(response); assertTrue(response.isSuccess()); assertNotNull(response.getMessage()); }
From source file:de.loercher.localpress.core.api.LocalPressController.java
@RequestMapping(value = "/articles", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<String> getArticlesAround(@RequestParam Double lat, @RequestParam Double lon) throws InterruptedException, ExecutionException, JsonProcessingException { UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(GEO_URL).queryParam("lat", lat.toString()) .queryParam("lon", lon.toString()); RestTemplate template = new RestTemplate(); List<Map<String, Object>> geoResponse = template.getForObject(builder.build().encode().toUri(), List.class); Iterator<Map<String, Object>> it = geoResponse.iterator(); List<Future<ResponseEntity<Map>>> jobs = new ArrayList<>(); // to be able to merge answers from rating to geoitems there is a need // to map the article to its articleID // (articleID) => (articleItem) Map<String, Map<String, Object>> mappedResponseObjects = new HashMap<>(); while (it.hasNext()) { Map<String, Object> item = it.next(); AsyncRestTemplate async = new AsyncRestTemplate(); Future<ResponseEntity<Map>> futureResult = async.getForEntity((String) item.get("rating"), Map.class); jobs.add(futureResult);//from w w w .ja v a2 s. c o m mappedResponseObjects.put((String) item.get("articleID"), item); } for (Future<ResponseEntity<Map>> job : jobs) { Map<String, Object> ratingMap = job.get().getBody(); String articleID = (String) ratingMap.get("articleID"); if ((Boolean) ratingMap.get("appropriate")) { mappedResponseObjects.get(articleID).putAll(ratingMap); } else { mappedResponseObjects.remove(articleID); } } WeightingPolicy policy = new WeightingPolicyImpl(); List<Map<String, Object>> orderedResponse = policy.sortIncludingRating(mappedResponseObjects.values()); List<Map<String, Object>> result = new ResponseMapFilterImpl().filter(orderedResponse); return new ResponseEntity<>(objectMapper.writeValueAsString(result), HttpStatus.OK); }
From source file:org.appverse.web.framework.backend.test.util.oauth2.tests.predefined.authorizationcode.Oauth2AuthorizationCodeFlowPredefinedTests.java
@Test public void testRemoteLogIsProtected() throws Exception { RemoteLogRequestVO remoteLogRequest = new RemoteLogRequestVO(); remoteLogRequest.setLogLevel("DEBUG"); remoteLogRequest.setMessage("This is my log message!"); // We call remote log WITHOUT the access token HttpEntity<RemoteLogRequestVO> entity = new HttpEntity<RemoteLogRequestVO>(remoteLogRequest); UriComponentsBuilder builder = UriComponentsBuilder .fromHttpUrl(resourceServerBaseUrl + baseApiPath + remoteLogEndpointPath); ResponseEntity<String> result = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST, entity, String.class); assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode()); assertTrue("Wrong header: " + result.getHeaders(), result.getHeaders().getFirst("WWW-Authenticate").startsWith("Bearer realm=")); }