List of usage examples for org.springframework.web.util UriComponentsBuilder fromUriString
public static UriComponentsBuilder fromUriString(String uri)
From source file:org.openmhealth.shim.runkeeper.RunkeeperShim.java
@Override protected String getAuthorizationUrl(UserRedirectRequiredException exception) { final OAuth2ProtectedResourceDetails resource = getResource(); UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(exception.getRedirectUri()) .queryParam("state", exception.getStateKey()).queryParam("client_id", resource.getClientId()) .queryParam("response_type", "code").queryParam("redirect_uri", getCallbackUrl()); return uriBuilder.build().encode().toUriString(); }
From source file:edu.purdue.cybercenter.dm.web.GlobusControllerTest.java
@Test @Ignore/*from w w w . j a va2 s . c om*/ public void shouldBeAbleToRunWorkflowWithGlobusTransfer() throws Exception { useTestWorkspace("brouder_sylvie"); login("george.washington", "1234"); /* * upload the test workflow */ MockMultipartFile mockMultipartFile = new MockMultipartFile(WORKFLOW_ZIP_FILE, new FileInputStream(WORKFLOW_FILES_DIR + WORKFLOW_ZIP_FILE)); MockMultipartHttpServletRequestBuilder mockMultipartHttpServletRequestBuilder = (MockMultipartHttpServletRequestBuilder) fileUpload( "/workflows/import").accept(MediaType.ALL).session(httpSession); mockMultipartHttpServletRequestBuilder.file(mockMultipartFile); ResultActions resultActions = mockMvc.perform(mockMultipartHttpServletRequestBuilder); resultActions.andExpect(status().isCreated()); String content = extractTextarea(resultActions.andReturn().getResponse().getContentAsString()); Map<String, Object> workflow = Helper.deserialize(content, Map.class); assertNotNull("workflow is null", workflow); Integer workflowId = (Integer) workflow.get("id"); /* * create a project and an experiment to associate the job for the workflow with * while doing that, make sure we save all the IDs associated to post it with the job */ MockHttpServletRequestBuilder mockHttpServletRequestBuilder = post("/projects") .content("{\"description\":\"This is a project\",\"name\":\"Project 1\"}") .accept(MediaType.APPLICATION_JSON).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isCreated()); content = resultActions.andReturn().getResponse().getContentAsString(); Map<String, Object> map = Helper.deserialize(content, Map.class); Integer projectId = (Integer) map.get("id"); mockHttpServletRequestBuilder = post("/experiments") .content("{\"projectId\":{\"$ref\":\"/projects/" + projectId + "\"},\"name\":\"Experiment 1\",\"description\":\"This is an experiment\"}") .accept(MediaType.APPLICATION_JSON).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isCreated()); content = resultActions.andReturn().getResponse().getContentAsString(); map = Helper.deserialize(content, Map.class); Integer experimentId = (Integer) map.get("id"); /* * create a job associated with the project, experiment and workflow we just created */ mockHttpServletRequestBuilder = post("/jobs").param("projectId", projectId.toString()) .param("experimentId", experimentId.toString()).param("workflowId", workflowId.toString()) .param("name", "Just a job").accept(MediaType.TEXT_HTML).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isOk()); /* * forwarded to job/submit/jobId */ String forwardedUrl = resultActions.andReturn().getResponse().getForwardedUrl(); mockHttpServletRequestBuilder = post(forwardedUrl).accept(MediaType.TEXT_HTML_VALUE).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); /* * redirected to jobs/task/jobId */ String redirectedUrl = resultActions.andReturn().getResponse().getRedirectedUrl(); mockHttpServletRequestBuilder = get(redirectedUrl).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); /* * we're at UT1 in the workflow */ String jobId = redirectedUrl.substring(redirectedUrl.lastIndexOf('/') + 1); TaskEntity task = (TaskEntity) resultActions.andReturn().getModelAndView().getModel().get("task"); String taskId = task.getId(); String templateId = "305b0f27-e829-424e-84eb-7a8a9ed93e28"; String templateVersion = "db719406-f665-45cb-a8fb-985b6082b654"; // For buttton 1 UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString("/globus/browseFile"); uriBuilder.queryParam("jobId", jobId); uriBuilder.queryParam("alias", templateId + ".browsefile1"); uriBuilder.queryParam("multiple", false); System.out.println(uriBuilder.build(true).toUriString()); mockHttpServletRequestBuilder = get(uriBuilder.build(true).toUriString()).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isOk()); redirectedUrl = resultActions.andReturn().getResponse().getContentAsString(); System.out.println("Redirected to: " + redirectedUrl); uriBuilder = UriComponentsBuilder.fromUriString("https://www.globus.org/service/graph/goauth/authorize"); uriBuilder.queryParam("response_type", "code"); //uriBuilder.queryParam("redirect_uri", "code"); uriBuilder.queryParam("client_id", username); URL url = new URL(uriBuilder.build(true).toUriString()); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); String userpass = username + ":" + password; String basicAuth = "Basic " + new String(Base64.encodeBase64(userpass.getBytes())); connection.setRequestProperty("Authorization", basicAuth); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); String res = IOUtils.toString(connection.getInputStream()); Map<String, Object> responseMap = Helper.deserialize(res, Map.class); String code = (String) responseMap.get("code"); uriBuilder = UriComponentsBuilder.fromUriString("/globus/loginCallback"); uriBuilder.queryParam("jobId", Integer.parseInt(jobId)); uriBuilder.queryParam("alias", templateId + ".browsefile1"); uriBuilder.queryParam("multiple", false); String uri = uriBuilder.build(true).toUriString() + "&code=" + code; mockHttpServletRequestBuilder = get(uri).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().is3xxRedirection()); redirectedUrl = resultActions.andReturn().getResponse().getRedirectedUrl(); System.out.println("Redirected to: " + redirectedUrl); // For Button 2 uriBuilder = UriComponentsBuilder.fromUriString("/globus/browseFile"); uriBuilder.queryParam("jobId", jobId); uriBuilder.queryParam("alias", templateId + ".browsefile2"); uriBuilder.queryParam("multiple", true); System.out.println(uriBuilder.build(true).toUriString()); mockHttpServletRequestBuilder = get(uriBuilder.build(true).toUriString()).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isOk()); redirectedUrl = resultActions.andReturn().getResponse().getContentAsString(); System.out.println("Redirected to: " + redirectedUrl); uriBuilder = UriComponentsBuilder.fromUriString("https://www.globus.org/service/graph/goauth/authorize"); uriBuilder.queryParam("response_type", "code"); uriBuilder.queryParam("client_id", username); url = new URL(uriBuilder.build(true).toUriString()); connection = (HttpsURLConnection) url.openConnection(); userpass = username + ":" + password; basicAuth = "Basic " + new String(Base64.encodeBase64(userpass.getBytes())); connection.setRequestProperty("Authorization", basicAuth); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); res = IOUtils.toString(connection.getInputStream()); responseMap = Helper.deserialize(res, Map.class); code = (String) responseMap.get("code"); // For button 2 uriBuilder = UriComponentsBuilder.fromUriString("/globus/loginCallback"); uriBuilder.queryParam("jobId", Integer.parseInt(jobId)); uriBuilder.queryParam("alias", templateId + ".browsefile2"); uriBuilder.queryParam("multiple", true); uri = uriBuilder.build(true).toUriString() + "&code=" + code; mockHttpServletRequestBuilder = get(uri).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().is3xxRedirection()); redirectedUrl = resultActions.andReturn().getResponse().getRedirectedUrl(); System.out.println("Redirected to: " + redirectedUrl); // Getting accessToken only from one button String accessToken = ""; String[] urlParts = redirectedUrl.split("&"); for (String urlPart : urlParts) { if (urlPart.contains("accessToken")) { String[] accessTokenPair = urlPart.split("="); accessToken = accessTokenPair[1]; break; } } //Button 1 uriBuilder = UriComponentsBuilder.fromUriString("/globus/fileSelectCallback"); uriBuilder.queryParam(URLEncoder.encode("file[0]", "UTF-8"), FILE_TO_UPLOAD_1); uriBuilder.queryParam("jobId", jobId); uriBuilder.queryParam("alias", templateId + ".browsefile1"); uriBuilder.queryParam("accessToken", accessToken);//URLEncoder.encode(accessToken,"UTF-8") uriBuilder.queryParam("path", URLEncoder.encode("/~/remote_endpoint/", "UTF-8")); uri = uriBuilder.build(true).toUriString(); uri = URLDecoder.decode(uri); uri = uri + "&endpoint=" + URLEncoder.encode(endpoint, "UTF-8"); mockHttpServletRequestBuilder = get(uri).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isOk()); //Button 2 uriBuilder = UriComponentsBuilder.fromUriString("/globus/fileSelectCallback"); uriBuilder.queryParam(URLEncoder.encode("file[0]", "UTF-8"), FILE_TO_UPLOAD_1); uriBuilder.queryParam(URLEncoder.encode("file[1]", "UTF-8"), FILE_TO_UPLOAD_2); uriBuilder.queryParam("jobId", jobId); uriBuilder.queryParam("alias", templateId + ".browsefile2"); uriBuilder.queryParam("accessToken", accessToken);//URLEncoder.encode(accessToken,"UTF-8") uriBuilder.queryParam("path", URLEncoder.encode("/~/remote_endpoint/", "UTF-8")); uri = uriBuilder.build(true).toUriString(); uri = URLDecoder.decode(uri); uri = uri + "&endpoint=" + URLEncoder.encode(endpoint, "UTF-8"); mockHttpServletRequestBuilder = get(uri).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isOk()); //For getting Storage Files (an abstract button called browsefile3) uriBuilder = UriComponentsBuilder.fromUriString("/globus/browseFile"); uriBuilder.queryParam("jobId", jobId); uriBuilder.queryParam("alias", templateId + ".browsefile3"); uriBuilder.queryParam("multiple", true); uriBuilder.queryParam("storageFile", "StorageFile:1");// This file has to be present in the storage file record and in memory System.out.println(uriBuilder.build(true).toUriString()); mockHttpServletRequestBuilder = get(uriBuilder.build(true).toUriString()).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isOk()); redirectedUrl = resultActions.andReturn().getResponse().getContentAsString(); System.out.println("Redirected to: " + redirectedUrl); //FileSelect uriBuilder = UriComponentsBuilder.fromUriString("/globus/fileSelectCallback"); uriBuilder.queryParam("fileId", 1); uriBuilder.queryParam(URLEncoder.encode("folder[0]", "UTF-8"), "remote_endpoint/"); uriBuilder.queryParam("jobId", jobId); uriBuilder.queryParam("alias", templateId + ".browsefile3"); uriBuilder.queryParam("accessToken", accessToken);//URLEncoder.encode(accessToken,"UTF-8") uriBuilder.queryParam("path", URLEncoder.encode("/~/", "UTF-8")); uri = uriBuilder.build(true).toUriString(); uri = URLDecoder.decode(uri, "UTF-8"); uri = uri + "&endpoint=" + URLEncoder.encode(endpoint, "UTF-8"); mockHttpServletRequestBuilder = get(uri).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isOk()); String multipartBoundary = "------WebKitFormBoundary3xeGH8uP6GWtBfd1"; MultiPartFileContentBuilder multiPartFileContentBuilder = new MultiPartFileContentBuilder( multipartBoundary); multiPartFileContentBuilder.addField("autoGenerated", "true"); multiPartFileContentBuilder.addField("jobId", jobId); multiPartFileContentBuilder.addField("taskId", taskId); multiPartFileContentBuilder.addField("jsonToServer", "{}"); multiPartFileContentBuilder.addField("isIframe", "true"); multiPartFileContentBuilder.addField("experimentId", ""); multiPartFileContentBuilder.addField("projectId", ""); multiPartFileContentBuilder .addField(templateId + ".name({%22_template_version:%22" + templateVersion + "%22})", ""); multiPartFileContentBuilder .addField(templateId + ".browsefile1({%22_template_version:%22" + templateVersion + "%22})", ""); multiPartFileContentBuilder .addField(templateId + ".browsefile2({%22_template_version:%22" + templateVersion + "%22})", ""); String taskContent = multiPartFileContentBuilder.build(); // /rest/objectus post call mockHttpServletRequestBuilder = (MockMultipartHttpServletRequestBuilder) fileUpload("/rest/objectus/") .param("jobId", jobId).param("taskId", taskId).param(templateId + ".name", "") .param(templateId + ".browsefile1", "").param(templateId + ".browsefile2", "") .param("jsonToServer", "{}").accept(MediaType.ALL).session(httpSession); mockHttpServletRequestBuilder.content(taskContent); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isOk()); multipartBoundary = "------WebKitFormBoundarybiQtLhfKnPwaMgsR"; multiPartFileContentBuilder = new MultiPartFileContentBuilder(multipartBoundary); multiPartFileContentBuilder.addField("jobId", jobId); multiPartFileContentBuilder.addField("taskId", taskId); multiPartFileContentBuilder.addField("jsonToServer", "{}"); taskContent = multiPartFileContentBuilder.build(); // /jobs/task post call mockHttpServletRequestBuilder = (MockMultipartHttpServletRequestBuilder) fileUpload("/jobs/task") .param("jobId", jobId).param("taskId", taskId).param("ignoreFormData", "true") .param("jsonToServer", "{}").accept(MediaType.ALL).session(httpSession); mockHttpServletRequestBuilder.content(taskContent); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().is3xxRedirection()); redirectedUrl = resultActions.andReturn().getResponse().getRedirectedUrl(); System.out.println("Redirected to: " + redirectedUrl); deleteDatasetEntries(templateId); }
From source file:org.openmhealth.shim.jawbone.JawboneShim.java
@Override protected String getAuthorizationUrl(UserRedirectRequiredException exception) { final OAuth2ProtectedResourceDetails resource = getResource(); UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(exception.getRedirectUri()) .queryParam("state", exception.getStateKey()).queryParam("client_id", resource.getClientId()) .queryParam("response_type", "code") .queryParam("scope", StringUtils.collectionToDelimitedString(resource.getScope(), " ")) .queryParam("redirect_uri", getCallbackUrl()); return uriBuilder.build().encode().toUriString(); }
From source file:io.pivotal.github.GithubClient.java
public void createRepository() throws IOException { if (!shouldDeleteCreateRepository()) { return;/*from w ww . ja va2s . c o m*/ } String slug = getRepositorySlug(); UriComponentsBuilder uri = UriComponentsBuilder.fromUriString("https://api.github.com/user/repos") .queryParam("access_token", getAccessToken()); Map<String, String> repository = new HashMap<>(); repository.put("name", slug.split("/")[1]); rest.postForEntity(uri.toUriString(), repository, String.class); }
From source file:com.nec.harvest.controller.SuihController.java
/** * Render page with path variables mapping suih/{unitLevel}/{unitDept} * //from w w w. ja v a2 s. c o m * @param businessDay * Actual business day * @param proGNo * A path variable user's group code * @param unitLevel * A path variable classify's code * @param unitDept * A path variable department level2's code * @return A redirect URL */ @RequestMapping(value = "/{unitLevel}/{unitDept}", method = RequestMethod.GET) public String render(@SessionAttribute(Constants.SESS_BUSINESS_DAY) Date businessDay, @PathVariable String proGNo, @PathVariable String unitLevel, @PathVariable String unitDept) { // UriComponents uriComponents = UriComponentsBuilder .fromUriString(Constants.SUIH_PATH + "/{unitLevel}/{unitDept}/{deptCode}").build(); URI uri = uriComponents.expand(proGNo, unitLevel, unitDept, unitDept).encode().toUri(); logger.info("Redirect to suih screen with params in path [/suih/{unitLevel}/{unitDept}/{deptCode}]"); return "redirect:" + uri.toString(); }
From source file:org.openmhealth.shim.ihealth.IHealthShim.java
@Override protected ResponseEntity<ShimDataResponse> getData(OAuth2RestOperations restTemplate, ShimDataRequest shimDataRequest) throws ShimException { final IHealthDataTypes dataType; try {/*from w ww. j av a2 s . c o m*/ dataType = valueOf(shimDataRequest.getDataTypeKey().trim().toUpperCase()); } catch (NullPointerException | IllegalArgumentException e) { throw new ShimException("Null or Invalid data type parameter: " + shimDataRequest.getDataTypeKey() + " in shimDataRequest, cannot retrieve data."); } OffsetDateTime now = OffsetDateTime.now(); OffsetDateTime startDate = shimDataRequest.getStartDateTime() == null ? now.minusDays(1) : shimDataRequest.getStartDateTime(); OffsetDateTime endDate = shimDataRequest.getEndDateTime() == null ? now.plusDays(1) : shimDataRequest.getEndDateTime(); /* The physical activity point handles start and end datetimes differently than the other endpoints. It requires use to include the range until the beginning of the next day. */ if (dataType == PHYSICAL_ACTIVITY) { endDate = endDate.plusDays(1); } // SC and SV values are client-based keys that are unique to each endpoint within a project String scValue = getScValue(); List<String> svValues = getSvValues(dataType); List<JsonNode> responseEntities = newArrayList(); int i = 0; // We iterate because one of the measures (Heart rate) comes from multiple endpoints, so we submit // requests to each of these endpoints, map the responses separately and then combine them for (String endPoint : dataType.getEndPoint()) { UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(API_URL); // Need to use a dummy userId if we haven't authenticated yet. This is the case where we are using // getData to trigger Spring to conduct the OAuth exchange String userId = "uk"; if (shimDataRequest.getAccessParameters() != null) { OAuth2AccessToken token = SerializationUtils .deserialize(shimDataRequest.getAccessParameters().getSerializedToken()); userId = Preconditions.checkNotNull((String) token.getAdditionalInformation().get("UserID")); uriBuilder.queryParam("access_token", token.getValue()); } uriBuilder.path("/user/").path(userId + "/").path(endPoint) .queryParam("client_id", restTemplate.getResource().getClientId()) .queryParam("client_secret", restTemplate.getResource().getClientSecret()) .queryParam("start_time", startDate.toEpochSecond()) .queryParam("end_time", endDate.toEpochSecond()).queryParam("locale", "default") .queryParam("sc", scValue).queryParam("sv", svValues.get(i)); ResponseEntity<JsonNode> responseEntity; try { URI url = uriBuilder.build().encode().toUri(); responseEntity = restTemplate.getForEntity(url, JsonNode.class); } catch (HttpClientErrorException | HttpServerErrorException e) { // FIXME figure out how to handle this logger.error("A request for iHealth data failed.", e); throw e; } if (shimDataRequest.getNormalize()) { IHealthDataPointMapper mapper; switch (dataType) { case PHYSICAL_ACTIVITY: mapper = new IHealthPhysicalActivityDataPointMapper(); break; case BLOOD_GLUCOSE: mapper = new IHealthBloodGlucoseDataPointMapper(); break; case BLOOD_PRESSURE: mapper = new IHealthBloodPressureDataPointMapper(); break; case BODY_WEIGHT: mapper = new IHealthBodyWeightDataPointMapper(); break; case BODY_MASS_INDEX: mapper = new IHealthBodyMassIndexDataPointMapper(); break; case STEP_COUNT: mapper = new IHealthStepCountDataPointMapper(); break; case SLEEP_DURATION: mapper = new IHealthSleepDurationDataPointMapper(); break; case HEART_RATE: // there are two different mappers for heart rate because the data can come from two endpoints if (endPoint == "bp.json") { mapper = new IHealthBloodPressureEndpointHeartRateDataPointMapper(); break; } else if (endPoint == "spo2.json") { mapper = new IHealthBloodOxygenEndpointHeartRateDataPointMapper(); break; } case OXYGEN_SATURATION: mapper = new IHealthOxygenSaturationDataPointMapper(); break; default: throw new UnsupportedOperationException(); } responseEntities.addAll(mapper.asDataPoints(singletonList(responseEntity.getBody()))); } else { responseEntities.add(responseEntity.getBody()); } i++; } return ResponseEntity.ok().body(ShimDataResponse.result(SHIM_KEY, responseEntities)); }
From source file:com.nec.harvest.controller.SonekihController.java
/** * Handling when user type on browser's address to take calculation totally * of all organizations that given department manage them * //from ww w .ja v a2 s . c o m * @param userOrgCode * Organization code from session * @param businessDay * Business day from session * @param proGNo * Processing menu group * @param unitLevel * Classify code of management * @param unitDept * Department code of management * @param month * Processing month * @param model * Model interchange between client and server * @return Redirect url path */ @RequestMapping(value = "/{unitLevel}/{unitDept}/{month}", method = RequestMethod.GET) public String render(@SessionAttribute(Constants.SESS_ORGANIZATION_CODE) String userOrgCode, @SessionAttribute(Constants.SESS_BUSINESS_DAY) Date businessDay, @PathVariable String proGNo, @PathVariable String unitLevel, @PathVariable String unitDept, final HttpServletRequest request, @PathVariable String month, final Model model) { logger.info("Loading profit monthly data by full path [/sonekih/{unitLevel}/{unitDept}/{month}]"); try { /* Get processing month */ Date processMonth = monthStandard(month, businessDay); if (processMonth == null) { UriComponents uriComponents = UriComponentsBuilder .fromUriString(Constants.SONEKIH_PATH + "/{unitLevel}/{unitDept}/{deptCode}/{month}") .build(); String businessMonth = DateFormatUtil.format(businessDay, DateFormat.DATE_WITHOUT_DAY); URI uri = uriComponents.expand(proGNo, unitLevel, unitDept, month, businessMonth).encode().toUri(); return "redirect:" + uri.toString(); } loadClassifies(unitLevel, model); loadDepartments(unitLevel, unitDept, model); loadDepartmentPage(request, proGNo, unitDept, "-1", model); loadDepartmentData(unitDept, unitDept, processMonth, businessDay, model); } catch (ServiceException ex) { logger.error(ex.getMessage(), ex); // ??????????? model.addAttribute(ERROR, true); model.addAttribute(ERROR_MESSAGE, getSystemError()); } return getViewName(); }
From source file:org.zalando.boot.etcd.EtcdClient.java
/** * Deletes the node with the given key from etcd. * /*from w w w . j a va 2 s . c o m*/ * @param key * the node's key * @return the response from etcd with the node * @throws EtcdException * in case etcd returned an error */ public EtcdResponse delete(final String key) throws EtcdException { UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(KEYSPACE); builder.pathSegment(key); return execute(builder, HttpMethod.DELETE, null, EtcdResponse.class); }
From source file:org.wallride.service.PostService.java
/** * * @param blogLanguage//ww w. j a v a 2 s . co m * @param type * @param maxRank * @see PostService#getPopularPosts(String, PopularPost.Type) */ @CacheEvict(value = WallRideCacheConfiguration.POPULAR_POST_CACHE, key = "'list.type.' + #blogLanguage.language + '.' + #type") public void updatePopularPosts(BlogLanguage blogLanguage, PopularPost.Type type, int maxRank) { logger.info("Start update of the popular posts"); GoogleAnalytics googleAnalytics = blogLanguage.getBlog().getGoogleAnalytics(); if (googleAnalytics == null) { logger.info("Configuration of Google Analytics can not be found"); return; } Analytics analytics = GoogleAnalyticsUtils.buildClient(googleAnalytics); WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext, "org.springframework.web.servlet.FrameworkServlet.CONTEXT.guestServlet"); if (context == null) { logger.info("GuestServlet is not ready yet"); return; } final RequestMappingHandlerMapping mapping = context.getBean(RequestMappingHandlerMapping.class); Map<Post, Long> posts = new LinkedHashMap<>(); int startIndex = 1; int currentRetry = 0; int totalResults = 0; do { try { LocalDate now = LocalDate.now(); LocalDate startDate; switch (type) { case DAILY: startDate = now.minusDays(1); break; case WEEKLY: startDate = now.minusWeeks(1); break; case MONTHLY: startDate = now.minusMonths(1); break; default: throw new ServiceException(); } DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); Analytics.Data.Ga.Get get = analytics.data().ga() .get(googleAnalytics.getProfileId(), startDate.format(dateTimeFormatter), now.format(dateTimeFormatter), "ga:sessions") .setDimensions(String.format("ga:pagePath", googleAnalytics.getCustomDimensionIndex())) .setSort(String.format("-ga:sessions", googleAnalytics.getCustomDimensionIndex())) .setStartIndex(startIndex).setMaxResults(GoogleAnalyticsUtils.MAX_RESULTS); if (blogLanguage.getBlog().isMultiLanguage()) { get.setFilters("ga:pagePath=~/" + blogLanguage.getLanguage() + "/"); } logger.info(get.toString()); final GaData gaData = get.execute(); if (CollectionUtils.isEmpty(gaData.getRows())) { break; } for (List row : gaData.getRows()) { UriComponents uriComponents = UriComponentsBuilder.fromUriString((String) row.get(0)).build(); MockHttpServletRequest request = new MockHttpServletRequest(servletContext); request.setRequestURI(uriComponents.getPath()); request.setQueryString(uriComponents.getQuery()); MockHttpServletResponse response = new MockHttpServletResponse(); BlogLanguageRewriteRule rewriteRule = new BlogLanguageRewriteRule(blogService); BlogLanguageRewriteMatch rewriteMatch = (BlogLanguageRewriteMatch) rewriteRule.matches(request, response); try { rewriteMatch.execute(request, response); } catch (ServletException e) { throw new ServiceException(e); } catch (IOException e) { throw new ServiceException(e); } request.setRequestURI(rewriteMatch.getMatchingUrl()); HandlerExecutionChain handler; try { handler = mapping.getHandler(request); } catch (Exception e) { throw new ServiceException(e); } if (!(handler.getHandler() instanceof HandlerMethod)) { continue; } HandlerMethod method = (HandlerMethod) handler.getHandler(); if (!method.getBeanType().equals(ArticleDescribeController.class) && !method.getBeanType().equals(PageDescribeController.class)) { continue; } // Last path mean code of post String code = uriComponents.getPathSegments().get(uriComponents.getPathSegments().size() - 1); Post post = postRepository.findOneByCodeAndLanguage(code, rewriteMatch.getBlogLanguage().getLanguage()); if (post == null) { logger.debug("Post not found [{}]", code); continue; } if (!posts.containsKey(post)) { posts.put(post, Long.parseLong((String) row.get(1))); } if (posts.size() >= maxRank) { break; } } if (posts.size() >= maxRank) { break; } startIndex += GoogleAnalyticsUtils.MAX_RESULTS; totalResults = gaData.getTotalResults(); } catch (IOException e) { logger.warn("Failed to synchronize with Google Analytics", e); if (currentRetry >= GoogleAnalyticsUtils.MAX_RETRY) { throw new GoogleAnalyticsException(e); } currentRetry++; logger.info("{} ms to sleep...", GoogleAnalyticsUtils.RETRY_INTERVAL); try { Thread.sleep(GoogleAnalyticsUtils.RETRY_INTERVAL); } catch (InterruptedException ie) { throw new GoogleAnalyticsException(e); } logger.info("Retry for the {} time", currentRetry); } } while (startIndex <= totalResults); popularPostRepository.deleteByType(blogLanguage.getLanguage(), type); int rank = 1; for (Map.Entry<Post, Long> entry : posts.entrySet()) { PopularPost popularPost = new PopularPost(); popularPost.setLanguage(blogLanguage.getLanguage()); popularPost.setType(type); popularPost.setRank(rank); popularPost.setViews(entry.getValue()); popularPost.setPost(entry.getKey()); popularPostRepository.saveAndFlush(popularPost); rank++; } logger.info("Complete the update of popular posts"); }
From source file:it.scoppelletti.programmerpower.web.control.ActionBase.java
/** * Restituisce l’indirizzo della pagina HTML di guida. * /* w w w . j a v a 2s .c o m*/ * <P>Questa implementazione del metodo {@code getHelpUrl} rileva il valore * della proprietà {@code path.help} tra le risorse * associate all’azione: se questa proprietà è * impostata, è considerata come un percorso relativo * all’indirizzo di base della guida di riferimento di Programmer * Power ({@code http://www.scoppelletti.it/programmerpower/reference}); * questo indirizzo di base può essere sovrascritto dal valore * impostato sulla proprietà di ambiente * {@code it.scoppelletti.programmerpower.web.help.url}.<BR> * Le classi derivate da terze parti dovrebbero implementare una versione * prevalente del metodo {@code getHelpUrl} per restituire l’URL * opportuno.</P> * * @return Valore. Se la guida non è prevista, restituisce * {@code null}. * @see <A HREF="{@docRoot}/../reference/setup/envprops.html" * TARGET="_top">Proprietà di ambiente</A> */ public String getHelpUrl() { String base, path; UriComponentsBuilder uriBuilder; Environment env; path = getText(ActionBase.PROP_HELPPATH); if (Strings.isNullOrEmpty(path) || ActionBase.PROP_HELPPATH.equals(path)) { return null; } if (myApplCtx == null) { base = ActionBase.DEF_HELPURL; } else { env = myApplCtx.getEnvironment(); base = env.getProperty(ActionBase.PROP_HELPURL, ActionBase.DEF_HELPURL); } if (!base.endsWith("/") && !path.startsWith("/")) { base = base.concat("/"); } uriBuilder = UriComponentsBuilder.fromUriString(base); uriBuilder.path(path); return uriBuilder.build().toUriString(); }