@Test
  public void updateTargetUrlWithContextLoader() throws Exception {
    StaticWebApplicationContext wac = new StaticWebApplicationContext();
    wac.registerSingleton("requestDataValueProcessor", RequestDataValueProcessorWrapper.class);

    MockServletContext servletContext = new MockServletContext();
    ContextLoader contextLoader = new ContextLoader(wac);
    contextLoader.initWebApplicationContext(servletContext);

    try {
      RequestDataValueProcessor mockProcessor = mock(RequestDataValueProcessor.class);
      wac.getBean(RequestDataValueProcessorWrapper.class)
          .setRequestDataValueProcessor(mockProcessor);

      RedirectView rv = new RedirectView();
      rv.setUrl("/path");

      MockHttpServletRequest request = createRequest();
      HttpServletResponse response = new MockHttpServletResponse();

      given(mockProcessor.processUrl(request, "/path")).willReturn("/path?key=123");

      rv.render(new ModelMap(), request, response);

      verify(mockProcessor).processUrl(request, "/path");
    } finally {
      contextLoader.closeWebApplicationContext(servletContext);
    }
  }
Example #2
0
 @ExceptionHandler
 public RedirectView handle(PostMovedException moved) {
   RedirectView redirect = new RedirectView();
   redirect.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
   redirect.setUrl("/blog/" + moved.getPublicSlug());
   return redirect;
 }
 @Test
 public void explicitStatusCodeHttp10() throws Exception {
   RedirectView rv = new RedirectView();
   rv.setUrl("http://url.somewhere.com");
   rv.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
   MockHttpServletRequest request = createRequest();
   MockHttpServletResponse response = new MockHttpServletResponse();
   rv.render(new HashMap<String, Object>(), request, response);
   assertEquals(301, response.getStatus());
   assertEquals("http://url.somewhere.com", response.getHeader("Location"));
 }
 @Test
 public void attributeStatusCodeHttp11() throws Exception {
   RedirectView rv = new RedirectView();
   rv.setUrl("http://url.somewhere.com");
   rv.setHttp10Compatible(false);
   MockHttpServletRequest request = createRequest();
   request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, HttpStatus.CREATED);
   MockHttpServletResponse response = new MockHttpServletResponse();
   rv.render(new HashMap<String, Object>(), request, response);
   assertEquals(201, response.getStatus());
   assertEquals("http://url.somewhere.com", response.getHeader("Location"));
 }
  /**
   * Resolves the view from the advanced search form, from search form under the menu in start page,
   * from categories or from tags AND from links to next/previous page and so on.
   *
   * @param advancedSearchData
   * @param bindingResult
   * @param model
   * @return
   * @throws UnsupportedEncodingException
   */
  @RequestMapping(value = "/advanced_search/results", method = RequestMethod.GET)
  public ModelAndView getAdvancedSearchResults(
      @ModelAttribute("advancedSearchData") SearchData advancedSearchData,
      BindingResult bindingResult,
      Model model,
      HttpServletRequest httpRequest)
      throws UnsupportedEncodingException {

    LOG.debug(
        "------ getAdvancedSearchResults : get SEARCH RESULTS based on advanced search form -----");

    if (advancedSearchData.getSearchTarget() == null)
      advancedSearchData.setSearchTarget("episodes");
    SearchResult searchResult = searchService.getResultsForSearchCriteria(advancedSearchData);

    String redirectUrl = null;
    String tilesDef = null;
    ModelAndView mv;

    // no results found
    if (searchResult.getResults().isEmpty()) {
      bindingResult.rejectValue("queryText", "notFound", "not found");
      redirectUrl = "/search/advanced_search?noResultsFound=true";
    } else if (searchResult.getResults().size() > 1) {
      String query = httpRequest.getQueryString();
      query = query.substring(0, query.lastIndexOf("&currentPage="));

      model.addAttribute("queryString", query.replaceAll("&", "&amp;"));
      model.addAttribute("advancedSearchResult", searchResult);

      tilesDef = "search_results_def";

    } else {
      // exactly one result found (either podcast or episode), redirect to it
      redirectUrl = searchResult.getResults().get(0).getRelativeLink();
    }

    if (tilesDef != null) {
      mv = new ModelAndView();
      mv.setViewName(tilesDef);
    } else {
      // must be a redirect
      RedirectView rv = new RedirectView();
      rv.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
      rv.setUrl(redirectUrl);
      mv = new ModelAndView(rv);
    }

    return mv;
  }
 @Test
 public void http11() throws Exception {
   RedirectView rv = new RedirectView();
   rv.setUrl("http://url.somewhere.com");
   rv.setHttp10Compatible(false);
   MockHttpServletRequest request = createRequest();
   MockHttpServletResponse response = new MockHttpServletResponse();
   request.setAttribute(DispatcherServlet.OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap());
   request.setAttribute(
       DispatcherServlet.FLASH_MAP_MANAGER_ATTRIBUTE, new SessionFlashMapManager());
   rv.render(new HashMap<String, Object>(), request, response);
   assertEquals(303, response.getStatus());
   assertEquals("http://url.somewhere.com", response.getHeader("Location"));
 }
  @RequestMapping("/tracker.jsp")
  public View trackerOldUrl(
      @RequestParam(value = "filter", defaultValue = "all") String filterAction)
      throws UnsupportedEncodingException {
    RedirectView redirectView = new RedirectView("/tracker/");

    redirectView.setExposeModelAttributes(false);

    if (filterValues.contains(filterAction) && !filterAction.equals("all")) {
      redirectView.setUrl("/tracker/?filter=" + URLEncoder.encode(filterAction, "UTF-8"));
    }

    return redirectView;
  }
  /** The method to replace http:// URLs to https:// */
  protected void sendRedirect(
      HttpServletRequest request,
      HttpServletResponse response,
      String targetUrl,
      boolean http10Compatible)
      throws IOException {

    if (secure && targetUrl.startsWith("http://")) {
      targetUrl = StringUtils.replaceOnce(targetUrl, "http://", "https://");
    }

    if (!targetUrl.startsWith("http")) {
      // Get the secure URL and build complete URL
      StringBuffer sb = new StringBuffer();

      if (!ignoreContext) {
        sb.append(request.getServletPath());
      }
      sb.append("/");
      sb.append(targetUrl);
      targetUrl = sb.toString();
    }

    if (logger.isDebugEnabled()) {
      logger.debug("Redirecting to URL : [" + targetUrl + "]");
    }

    super.sendRedirect(request, response, targetUrl, http10Compatible);
  }
  @Test
  public void shouldPassANotificationToTheViewThatBookWasRecommended() {
    BookService bookService = mock(BookService.class);
    Book book = getBook();
    when(bookService.getBookByID(0)).thenReturn(book);
    BookViewController bookViewController = new BookViewController(bookService);
    RedirectView viewBook = bookViewController.recommend(0);
    String actualNotification = viewBook.getUrl();

    assertThat(
        actualNotification,
        is(
            "/viewbook?bookId="
                + book.getId()
                + "&notification="
                + BookViewController.RECOMMENDED_SUCCESFULLY));
  }
Example #10
0
  @Test
  public void flashMap() throws Exception {
    RedirectView rv = new RedirectView();
    rv.setUrl("http://url.somewhere.com/path");
    rv.setHttp10Compatible(false);
    MockHttpServletRequest request = createRequest();
    HttpServletResponse response = new MockHttpServletResponse();
    FlashMap flashMap = new FlashMap();
    flashMap.put("successMessage", "yay!");
    request.setAttribute(DispatcherServlet.OUTPUT_FLASH_MAP_ATTRIBUTE, flashMap);
    ModelMap model = new ModelMap("id", "1");
    rv.render(model, request, response);
    assertEquals(303, response.getStatus());
    assertEquals("http://url.somewhere.com/path?id=1", response.getHeader("Location"));

    assertEquals("/path", flashMap.getTargetRequestPath());
    assertEquals(model, flashMap.getTargetRequestParams().toSingleValueMap());
  }
  @RequestMapping(value = "/check-user", method = RequestMethod.POST)
  public ModelAndView checkUser(
      Locale locale,
      @Valid @ModelAttribute("user") User user,
      BindingResult bindingResult,
      ModelMap modelMap,
      RedirectAttributes redirectAttributes) {

    ModelAndView modelAndView = new ModelAndView();
    if (!bindingResult.hasErrors()) {
      RedirectView redirectView = new RedirectView("mainpage");
      redirectView.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
      modelAndView.setView(redirectView);

      redirectAttributes.addFlashAttribute(
          "locale",
          messageSource.getMessage("locale", new String[] {locale.getDisplayName(locale)}, locale));
    } else {
      modelAndView.setViewName("login");
    }

    return modelAndView;
  }
  @Test
  public void testEditTeamHappyFlow() throws Exception {
    MockHttpServletRequest request = getRequest();
    String token = TokenUtil.generateSessionToken();
    // Add the teamId, team name, description & token
    request.addParameter("teamName", "Team 1");
    request.addParameter("team", "team-1");
    request.addParameter("description", "description");
    request.addParameter("token", token);

    GrouperTeamService grouperTeamService = mock(GrouperTeamService.class);
    when(grouperTeamService.findTeamById("team-1")).thenReturn(mockTeam);
    when(grouperTeamService.findMember("team-1", "member-1")).thenReturn(mockAdminMember);
    autoWireMock(editTeamController, grouperTeamService, GrouperTeamService.class);
    autoWireMock(editTeamController, new Returns(true), ControllerUtil.class);
    autoWireRemainingResources(editTeamController);

    RedirectView result =
        editTeamController.editTeam(
            getModelMap(), request, token, token, new SimpleSessionStatus());

    assertEquals("detailteam.shtml?team=team-1&view=app", result.getUrl());
  }
Example #13
0
  @Test
  public void updateTargetUrl() throws Exception {
    StaticWebApplicationContext wac = new StaticWebApplicationContext();
    wac.registerSingleton("requestDataValueProcessor", RequestDataValueProcessorWrapper.class);
    wac.setServletContext(new MockServletContext());
    wac.refresh();

    RequestDataValueProcessor mockProcessor = mock(RequestDataValueProcessor.class);
    wac.getBean(RequestDataValueProcessorWrapper.class).setRequestDataValueProcessor(mockProcessor);

    RedirectView rv = new RedirectView();
    rv.setApplicationContext(wac); // Init RedirectView with WebAppCxt
    rv.setUrl("/path");

    MockHttpServletRequest request = createRequest();
    request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
    HttpServletResponse response = new MockHttpServletResponse();

    given(mockProcessor.processUrl(request, "/path")).willReturn("/path?key=123");

    rv.render(new ModelMap(), request, response);

    verify(mockProcessor).processUrl(request, "/path");
  }
  @RequestMapping
  public View restorePassword(HttpServletRequest request) throws IOException {
    RedirectView rv = new RedirectView();
    Map<String, String> attributes = new HashMap<String, String>();

    EmailExtractedData extractedData = null;
    try {
      extractedData = extractEmailData(request);
    } catch (CryptoException cryptoEx) {
      log.error("Could not extract data from URL", cryptoEx);
      cryptoEx.printStackTrace();

      attributes.put(FlowsConstatns.ERR_HEADER, "URL IS INVALID");
      attributes.put(
          FlowsConstatns.ERR_MSG,
          "URL IS INVALID" + " exception message: " + cryptoEx.getMessage());
      // adding attributes to the redirect return value:
      rv.setAttributesMap(attributes);
      rv.setUrl("login/error.jsp");
      return rv;
    }

    if (extractedData.expired) {
      log.error("user " + extractedData.userEmail + " tried to use an expired link");

      attributes.put(FlowsConstatns.ERR_HEADER, "URL IS EXPIRED");
      attributes.put(FlowsConstatns.ERR_MSG, "URL IS Expired");
      // adding attributes to the redirect return value:
      rv.setAttributesMap(attributes);
      rv.setUrl("login/error.jsp");
      return rv;
    } else {
      // we send also the signed-email, so no one can change the email and set-new-password for
      // another user:
      String encodedEmailAndTimestamp = FlowsUtil.getParamsUserAndTimestamp(request);

      Date lastChange = processor.getPasswordLastChangeDate(extractedData.userEmail);

      Date emailCreationDate = extractedData.emailCreationDate;

      request.getSession().invalidate();
      request.getSession(true);
      SecurityContextHolder.getContext().setAuthentication(null);

      String redirectUri = extractedData.redirectUri;

      // if password was changed AFTER the email creation (that is AFTER the user initiated "4got
      // password" flow) -
      // it means the request is irrelevant
      if (lastChange.after(emailCreationDate)) {
        log.error(
            "user "
                + extractedData.userEmail
                + " tried to use an expired link: password was already changed AFTER the timestamp of the link");

        attributes.put(FlowsConstatns.ERR_HEADER, "Cannot set new password");
        attributes.put(
            FlowsConstatns.ERR_MSG,
            "Cannot set new password, because it was set AFTER the link was created.");
        // adding attributes to the redirect return value:
        rv.setAttributesMap(attributes);
        rv.setUrl("login/error.jsp");
        return rv;
      }

      //		String encoded = URLEncoder.encode(redirectUri, "utf-8");		//returns something like:
      // https%3A%2F%2Foauthsubdomain.ohad.sealdoc
      //			String escaped = StringEscapeUtils.escapeHtml4( redirectUri );

      // after all the checks, all look good (link not expired, etc). so show the user the "set new
      // password" page.
      // if "secret question" is implemented, here you get the secret Q and show the user the screen
      // to answer it. then
      // check the answer, etc.

      //			attributes.put(FlowsConstatns.ERR_HEADER,  "URL IS EXPIRED");
      //			attributes.put(FlowsConstatns.ERR_MSG,  "URL IS Expired");
      // adding attributes to the redirect return value:
      //			rv.setAttributesMap(attributes);
      rv.setUrl(
          "login/setNewPassword.jsp"
              + "?"
              + FlowsConstatns.HASH_PARAM_NAME
              + "="
              + encodedEmailAndTimestamp);
    }
    return rv;
  }
  public void testSaveRecord(String intWithRangeValue) throws Exception {
    login("admin", "password", new String[] {Role.ADMIN});

    request.setMethod("POST");
    request.setRequestURI("/bdrs/user/singleSiteMultiTaxa.htm");

    DateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy");
    dateFormat.setLenient(false);

    GregorianCalendar cal = new GregorianCalendar();
    cal.set(2010, 10, 12, 15, 30);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    Date sightingDate = cal.getTime();

    Map<String, String> params = new HashMap<String, String>();
    params.put("surveyId", survey.getId().toString());
    params.put("latitude", "-36.879620605027");
    params.put("longitude", "126.650390625");
    params.put("date", dateFormat.format(sightingDate));
    params.put("time_hour", new Integer(cal.get(Calendar.HOUR_OF_DAY)).toString());
    params.put("time_minute", new Integer(cal.get(Calendar.MINUTE)).toString());
    params.put("notes", "This is a test record");
    params.put("sightingIndex", "2");

    Map<Attribute, Object> surveyScopeAttributeValueMapping = new HashMap<Attribute, Object>();
    Map<IndicatorSpecies, Map<Attribute, Object>> recordScopeAttributeValueMapping =
        new HashMap<IndicatorSpecies, Map<Attribute, Object>>(2);
    Map<Attribute, Object> attributeValueMapping;

    // We have 2 species set up so lets save them both
    int sightingIndex = 0;
    String surveyPrefix = "";
    for (IndicatorSpecies taxon : new IndicatorSpecies[] {speciesA, speciesB}) {
      params.put(
          String.format("%d_survey_species_search", sightingIndex), taxon.getScientificName());
      params.put(String.format("%d_species", sightingIndex), taxon.getId().toString());
      params.put(
          String.format("%d_number", sightingIndex), new Integer(sightingIndex + 21).toString());

      String recordPrefix = String.format("%d_", sightingIndex);
      String prefix;
      String key;
      String value; // The value in the post dict
      attributeValueMapping = new HashMap<Attribute, Object>();
      Map<Attribute, Object> valueMap;
      recordScopeAttributeValueMapping.put(taxon, attributeValueMapping);
      for (Attribute attr : survey.getAttributes()) {

        if (AttributeScope.SURVEY.equals(attr.getScope())) {
          prefix = surveyPrefix;
          valueMap = surveyScopeAttributeValueMapping;
        } else {
          prefix = recordPrefix;
          valueMap = attributeValueMapping;
        }

        key = String.format(AttributeParser.ATTRIBUTE_NAME_TEMPLATE, prefix, attr.getId());
        value = "";

        switch (attr.getType()) {
          case INTEGER:
            Integer val = new Integer(sightingIndex + 30);
            value = val.toString();
            valueMap.put(attr, val);
            break;
          case INTEGER_WITH_RANGE:
            valueMap.put(attr, intWithRangeValue);
            break;
          case DECIMAL:
            value = String.format("50.%d", sightingIndex);
            valueMap.put(attr, Double.parseDouble(value));
            break;
          case DATE:
            Date date = new Date(System.currentTimeMillis());
            value = dateFormat.format(date);
            // Reparsing the date strips out the hours, minutes and seconds
            valueMap.put(attr, dateFormat.parse(value));
            break;
          case STRING_AUTOCOMPLETE:
          case STRING:
            value = String.format("String %d", sightingIndex);
            valueMap.put(attr, value);
            break;
          case TEXT:
            value = String.format("Text %d", sightingIndex);
            valueMap.put(attr, value);
            break;
          case STRING_WITH_VALID_VALUES:
            value = attr.getOptions().get(sightingIndex).getValue();
            valueMap.put(attr, value);
            break;
          case FILE:
            String file_filename = String.format("attribute_%d", attr.getId());
            MockMultipartFile mockFileFile =
                new MockMultipartFile(key, file_filename, "audio/mpeg", file_filename.getBytes());
            ((MockMultipartHttpServletRequest) request).addFile(mockFileFile);
            valueMap.put(attr, mockFileFile);
            break;
          case IMAGE:
            String image_filename = String.format("attribute_%d", attr.getId());
            MockMultipartFile mockImageFile =
                new MockMultipartFile(key, image_filename, "image/png", image_filename.getBytes());
            ((MockMultipartHttpServletRequest) request).addFile(mockImageFile);
            valueMap.put(attr, mockImageFile);
            break;
          default:
            Assert.assertTrue("Unknown Attribute Type: " + attr.getType().toString(), false);
            break;
        }
        params.put(key, value);
      }
      sightingIndex += 1;
    }

    request.setParameters(params);
    ModelAndView mv = handle(request, response);
    Assert.assertEquals(2, recordDAO.countAllRecords().intValue());

    Assert.assertTrue(mv.getView() instanceof RedirectView);
    RedirectView redirect = (RedirectView) mv.getView();
    Assert.assertEquals(redirectionService.getMySightingsUrl(survey), redirect.getUrl());

    sightingIndex = 0;
    for (IndicatorSpecies taxon : new IndicatorSpecies[] {speciesA, speciesB}) {
      List<Record> records = recordDAO.getRecords(taxon);
      Assert.assertEquals(1, records.size());
      Record record = records.get(0);

      Assert.assertEquals(survey.getId(), record.getSurvey().getId());
      // Coordinates are truncates to 6 decimal points
      Assert.assertEquals(
          new Double(params.get("latitude")).doubleValue(),
          record.getPoint().getY(),
          Math.pow(10, -6));
      Assert.assertEquals(
          new Double(params.get("longitude")).doubleValue(),
          record.getPoint().getX(),
          Math.pow(10, -6));
      Assert.assertEquals(sightingDate, record.getWhen());
      Assert.assertEquals(sightingDate.getTime(), record.getTime().longValue());
      Assert.assertEquals(params.get("notes"), record.getNotes());

      Assert.assertEquals(taxon, record.getSpecies());
      Assert.assertEquals(sightingIndex + 21, record.getNumber().intValue());

      Map<Attribute, Object> attributeValueMap = recordScopeAttributeValueMapping.get(taxon);
      Object expected;
      for (TypedAttributeValue recAttr : record.getAttributes()) {
        if (AttributeScope.SURVEY.equals(recAttr.getAttribute().getScope())) {
          expected = surveyScopeAttributeValueMapping.get(recAttr.getAttribute());
        } else {
          expected = attributeValueMap.get(recAttr.getAttribute());
        }

        switch (recAttr.getAttribute().getType()) {
          case INTEGER:
          case INTEGER_WITH_RANGE:
            Assert.assertEquals(expected, recAttr.getNumericValue().intValue());
            break;
          case DECIMAL:
            Assert.assertEquals(expected, recAttr.getNumericValue().doubleValue());
            break;
          case DATE:
            Assert.assertEquals(expected, recAttr.getDateValue());
            break;
          case STRING_AUTOCOMPLETE:
          case STRING:
          case TEXT:
            Assert.assertEquals(expected, recAttr.getStringValue());
            break;
          case STRING_WITH_VALID_VALUES:
            Assert.assertEquals(expected, recAttr.getStringValue());
            break;
          case FILE:
          case IMAGE:
            String filename = ((MockMultipartFile) expected).getOriginalFilename();
            Assert.assertEquals(filename, recAttr.getStringValue());
            break;
          default:
            Assert.assertTrue(
                "Unknown Attribute Type: " + recAttr.getAttribute().getType().toString(), false);
            break;
        }
      }
      sightingIndex += 1;
    }

    // Test Save and Add Another
    request.setParameter("submitAndAddAnother", "submitAndAddAnother");
    mv = handle(request, response);
    Assert.assertEquals(4, recordDAO.countAllRecords().intValue());

    Assert.assertTrue(mv.getView() instanceof RedirectView);
    redirect = (RedirectView) mv.getView();
    Assert.assertEquals("/bdrs/user/surveyRenderRedirect.htm", redirect.getUrl());
  }
Example #16
0
 @Test(expected = IllegalArgumentException.class)
 public void noUrlSet() throws Exception {
   RedirectView rv = new RedirectView();
   rv.afterPropertiesSet();
 }