public void testSMDPrimitivesNoResult() throws Exception {
    // request
    setRequestContent("smd-6.txt");
    this.request.addHeader("content-type", "application/json-rpc");

    JSONInterceptor interceptor = new JSONInterceptor();
    interceptor.setEnableSMD(true);
    SMDActionTest1 action = new SMDActionTest1();

    this.invocation.setAction(action);

    // can't be invoked
    interceptor.intercept(this.invocation);
    assertFalse(this.invocation.isInvoked());

    // asert values were passed properly
    assertEquals("string", action.getStringParam());
    assertEquals(1, action.getIntParam());
    assertEquals(true, action.isBooleanParam());
    assertEquals('c', action.getCharParam());
    assertEquals(2, action.getLongParam());
    assertEquals(new Float(3.3), action.getFloatParam());
    assertEquals(4.4, action.getDoubleParam());
    assertEquals(5, action.getShortParam());
    assertEquals(6, action.getByteParam());

    String json = response.getContentAsString();

    String normalizedActual = TestUtils.normalize(json, true);
    String normalizedExpected = TestUtils.normalize(JSONResultTest.class.getResource("smd-11.txt"));
    assertEquals(normalizedExpected, normalizedActual);

    assertEquals("application/json;charset=ISO-8859-1", response.getContentType());
  }
  @Test
  public void testDoFilterGzipResponseCompression() throws Exception {
    MockHttpServletRequest request =
        new MockHttpServletRequest(HttpMethod.POST.name(), "http://localhost:8080/gzip");
    request.addHeader(HttpHeaders.ACCEPT_ENCODING, "gzip");

    MockHttpServletResponse response = new MockHttpServletResponse();
    MockFilterChain filterChain =
        new MockFilterChain(
            servlet,
            new GzipServletFilter(),
            new OncePerRequestFilter() {
              @Override
              protected void doFilterInternal(
                  HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
                  throws ServletException, IOException {
                response.getOutputStream().write("Should be compressed".getBytes());
              }
            });
    filterChain.doFilter(request, response);

    ByteArrayOutputStream unzippedStream = new ByteArrayOutputStream();
    StreamUtils.copy(
        new GZIPInputStream(new ByteArrayInputStream(response.getContentAsByteArray())),
        unzippedStream);
    String unzipped = new String(unzippedStream.toByteArray());

    Assert.assertEquals(unzipped, "Should be compressed");
  }
 @Test
 public void customTemplateLoaderPath() throws Exception {
   registerAndRefreshContext("spring.groovy.template.prefix:classpath:/custom-templates/");
   MockHttpServletResponse response = render("custom");
   String result = response.getContentAsString();
   assertThat(result, containsString("custom"));
 }
Example #4
0
  public void testGetBadCommand() throws Exception {
    MockHttpServletRequest request = createMockRequest("GET", "/deadbeef");
    MockHttpServletResponse response = new MockHttpServletResponse();
    servlet.service(request, response);

    assertTrue(response.getStatus() == MockHttpServletResponse.SC_NOT_FOUND);
  }
  @Test
  public void resolveViewNoMatchUseUnacceptableStatus() throws Exception {
    viewResolver.setUseNotAcceptableStatusCode(true);
    request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9");

    ViewResolver viewResolverMock = createMock(ViewResolver.class);
    viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock));

    View viewMock = createMock("application_xml", View.class);

    String viewName = "view";
    Locale locale = Locale.ENGLISH;

    expect(viewResolverMock.resolveViewName(viewName, locale)).andReturn(viewMock);
    expect(viewMock.getContentType()).andReturn("application/pdf").anyTimes();

    replay(viewResolverMock, viewMock);

    View result = viewResolver.resolveViewName(viewName, locale);
    assertNotNull("Invalid view", result);
    MockHttpServletResponse response = new MockHttpServletResponse();
    result.render(null, request, response);
    assertEquals("Invalid status code set", 406, response.getStatus());

    verify(viewResolverMock, viewMock);
  }
  public void testDownload() throws Exception {

    final Long processId = issueProcessAndWaitForTermination();

    // zip extension is not required but should be handled
    final String request = RESTLET_PATH + "/" + processId.longValue() + ".zip";

    final MockHttpServletResponse response = getAsServletResponse(request);
    assertEquals(Status.SUCCESS_OK, Status.valueOf(response.getStatus()));
    assertEquals(MediaType.APPLICATION_ZIP, MediaType.valueOf(response.getContentType()));
    assertEquals(
        "attachment; filename=\"test map.zip\"", response.getHeader("Content-Disposition"));

    final ByteArrayInputStream responseStream = getBinaryInputStream(response);
    final ZipInputStream zipIn = new ZipInputStream(responseStream);

    Set<String> expectedFiles = new HashSet<String>();
    expectedFiles.add("README.txt");
    expectedFiles.add(VECTOR_LAYER.getLocalPart() + ".shp");
    expectedFiles.add(VECTOR_LAYER.getLocalPart() + ".cst");
    expectedFiles.add(VECTOR_LAYER.getLocalPart() + ".prj");
    expectedFiles.add(VECTOR_LAYER.getLocalPart() + ".dbf");
    expectedFiles.add(VECTOR_LAYER.getLocalPart() + ".shx");
    // TODO: change this expectation once we normalize the raster file name
    expectedFiles.add(RASTER_LAYER.getPrefix() + ":" + RASTER_LAYER.getLocalPart() + ".tiff");

    Set<String> archivedFiles = new HashSet<String>();

    ZipEntry nextEntry;
    while ((nextEntry = zipIn.getNextEntry()) != null) {
      archivedFiles.add(nextEntry.getName());
    }

    assertEquals(expectedFiles, archivedFiles);
  }
Example #7
0
  public void testRunWithOnlyFormName() throws Exception {
    MockHttpServletRequest request = constructMockRequest("POST", "/document/validate", WILDCARD);
    request.setContent(("document=").getBytes()); // NOTE: need space between periods.
    MockHttpServletResponse response = invoke(request);

    assertEquals("HTTP status", HttpStatus.OK.getCode(), response.getStatus());
  }
  /**
   * Test a complete scenario. User sends .wmc file via POST and gets back the generated file path.
   * Then user asks via GET to get back the file stored on the server
   *
   * @throws Exception
   */
  @Test
  public void testWMCService() throws Exception {

    // valid wmc file content
    String fileContent =
        "<ViewContext xmlns=\"http://www.opengis.net/context\" version=\"1.1.0\" id=\"OpenLayers_Context_133\" xsi:schemaLocation=\"http://www.opengis.net/context http://schemas.opengis.net/context/1.1.0/context.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><General><Window width=\"1233\" height=\"342\"/><BoundingBox minx=\"-201405.7589\" miny=\"2245252.767\" maxx=\"598866.8058\" maxy=\"2467226.179\" SRS=\"EPSG:2154\"/><Title/><Extension><ol:maxExtent xmlns:ol=\"http://openlayers.org/context\" minx=\"47680.03567\" miny=\"2267644.975\" maxx=\"349781.0112\" maxy=\"2444833.970\"/></Extension></General><LayerList><Layer queryable=\"0\" hidden=\"0\"><Server service=\"OGC:WMS\" version=\"1.1.1\"><OnlineResource xlink:type=\"simple\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xlink:href=\"http://drebretagne-geobretagne.int.lsn.camptocamp.com/geoserver/wms\"/></Server><Name>topp:communes_geofla</Name><Title>communes_geofla</Title><FormatList><Format current=\"1\">image/jpeg</Format></FormatList><StyleList><Style current=\"1\"><Name/><Title>Default</Title></Style></StyleList><Extension><ol:maxExtent xmlns:ol=\"http://openlayers.org/context\" minx=\"47680.03567\" miny=\"2267644.975\" maxx=\"349781.0112\" maxy=\"2444833.970\"/><ol:numZoomLevels xmlns:ol=\"http://openlayers.org/context\">16</ol:numZoomLevels><ol:units xmlns:ol=\"http://openlayers.org/context\">m</ol:units><ol:isBaseLayer xmlns:ol=\"http://openlayers.org/context\">true</ol:isBaseLayer><ol:displayInLayerSwitcher xmlns:ol=\"http://openlayers.org/context\">true</ol:displayInLayerSwitcher><ol:singleTile xmlns:ol=\"http://openlayers.org/context\">false</ol:singleTile></Extension></Layer></LayerList></ViewContext>"; // wmc file to be send

    _requestPost.setRequestURI(DOMAIN_NAME + DocController.WMC_URL); // fake URI, Rest style
    _requestPost.setContent(fileContent.getBytes()); // fake body containing wmc file

    _controller.storeWMCFile(_requestPost, _responsePost);
    assertEquals(201, _responsePost.getStatus()); // 201 Created

    String sResp = _responsePost.getContentAsString();

    // the response is actually a JSON object
    JSONObject oResp = new JSONObject(sResp);
    String filePath = (String) oResp.get(DocController.FILEPATH_VARNAME);

    // file name contains absolute url + CSV service path
    assertEquals(true, filePath.contains(DocController.WMC_URL));

    _requestGet.setRequestURI(DOMAIN_NAME + filePath); // fake URI, Rest style

    _controller.getWMCFile(_requestGet, _responseGet);
    assertEquals(200, _responseGet.getStatus()); // 200 OK
    assertEquals(fileContent, _responseGet.getContentAsString().trim()); // content sent is
    // back
  }
  @Test
  public void request_content_image_that_binary_is_on_main_version() throws Exception {
    // setup: content
    byte[] bytes = loadImage("Arn.JPG");
    ContentKey contentKey =
        createImageContent(
            "MyImage.jpg", 2, bytes, "ImageCategory", new DateTime(2011, 6, 27, 10, 0, 0, 0), null);

    // setup: draft version of content
    ContentEntity content = fixture.findContentByKey(contentKey);

    BinaryDataEntity binaryDataOfMainVersion = content.getMainVersion().getBinaryData("source");

    // exercise & verify
    String imageRequestPath =
        "_image/" + contentKey + "/binary/" + binaryDataOfMainVersion.getKey() + ".jpg";
    setPathInfoAndRequestURI(httpServletRequest, imageRequestPath);
    httpServletRequest.setParameter("_background", "0xffffff");
    httpServletRequest.setParameter("_quality", "100");

    imageController.handleRequestInternal(httpServletRequest, httpServletResponse);

    assertEquals(HttpServletResponse.SC_OK, httpServletResponse.getStatus());
    assertTrue("Content Length", httpServletResponse.getContentLength() > 0);
    assertEquals("image/jpg", httpServletResponse.getContentType());
  }
 @Test
 public void testCommenceWithUnauthorizedWithAccept() throws Exception {
   request.addHeader(HttpHeaders.ACCEPT, "application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
   authenticationEntryPoint.commence(request, response, null);
   assertEquals(HttpStatus.UNAUTHORIZED.value(), response.getStatus());
   assertNotNull(response.getHeader(HttpHeaders.WWW_AUTHENTICATE));
 }
  /**
   * Test a complete scenario. User sends sld file content via POST and gets back the generated file
   * path. Then user asks via GET to get back the sld file stored on the server
   *
   * @throws Exception
   */
  @Test
  public void testSLDService() throws Exception {

    // valid sld file
    String sldContent =
        "<StyledLayerDescriptor version=\"1.1.0\" xsi:schemaLocation=\"http://schemas.opengis.net/sld/1.1.0/StyledLayerDescriptor.xsd\" xmlns=\"http://www.opengis.net/sld\" xmlns:ogc=\"http://www.opengis.net/ogc\" xmlns:se=\"http://www.opengis.net/se\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> <NamedLayer><se:Name>OCEANSEA_1M:Foundation</se:Name><UserStyle><se:Name>GEOSYM</se:Name><IsDefault>1</IsDefault><se:FeatureTypeStyle><se:FeatureTypeName>Foundation</se:FeatureTypeName><se:Rule><se:Name>main</se:Name><se:PolygonSymbolizer uom=\"http://www.opengis.net/sld/units/pixel\"><se:Name>MySymbol</se:Name><se:Description><se:Title>Example Symbol</se:Title><se:Abstract>This is just a simple example.</se:Abstract></se:Description><se:Geometry><ogc:PropertyName>GEOMETRY</ogc:PropertyName></se:Geometry><se:Fill><se:SvgParameter name=\"fill\">#96C3F5</se:SvgParameter></se:Fill></se:PolygonSymbolizer></se:Rule></se:FeatureTypeStyle></UserStyle></NamedLayer></StyledLayerDescriptor>";

    _requestPost.setRequestURI(DOMAIN_NAME + DocController.SLD_URL); // fake URI, Rest style
    _requestPost.setContent(sldContent.getBytes()); // fake body containing sld file
    _requestPost.setContentType("application/vnd.ogc.sld+xml");

    _controller.doSLDPost(_requestPost, _responsePost);
    assertEquals(201, _responsePost.getStatus()); // 201 Created

    String sResp = _responsePost.getContentAsString();

    // the response is actually a JSON object
    JSONObject oResp = new JSONObject(sResp);
    String filePath = (String) oResp.get(DocController.FILEPATH_VARNAME);

    // file name contains absolute url + CSV service path
    assertEquals(true, filePath.contains(DocController.SLD_URL));

    _requestGet.setRequestURI(DOMAIN_NAME + filePath); // fake URI, Rest style

    _controller.getSLDFile(_requestGet, _responseGet);
    assertEquals(200, _responseGet.getStatus()); // 200 OK
    assertEquals(sldContent, _responseGet.getContentAsString().trim()); // content sent is
    // back
  }
 @Test
 public void shouldReturnXmlAndErrorMessageWhenPostOfPipelineAsInvalidPartialXml()
     throws Exception {
   groupName = BasicPipelineConfigs.DEFAULT_GROUP;
   configHelper.addPipeline("pipeline", "stage", "build1", "build2");
   String badXml =
       "<pipeline name=\"cruise\" labeltemplate=\"invalid\">\n"
           + "  <materials>\n"
           + "    <svn url=\"file:///tmp/foo\" checkexternals=\"true\" />\n"
           + "  </materials>\n"
           + "  <stage name=\"dev\">\n"
           + "    <jobs>\n"
           + "      <job name=\"linux\" />\n"
           + "      <job name=\"windows\" />\n"
           + "    </jobs>\n"
           + "  </stage>\n"
           + "</pipeline>";
   String md5 = goConfigDao.md5OfConfigFile();
   ModelAndView mav = controller.postPipelineAsXmlPartial(0, groupName, badXml, md5, response);
   assertThat(response.getStatus(), is(SC_CONFLICT));
   assertThat(response.getContentType(), is(RESPONSE_CHARSET_JSON));
   Map<String, String> json = (Map) mav.getModel().get("json");
   assertThat(json.get("result").toString(), containsString("Label is invalid"));
   assertThat(json.get("originalContent"), is(badXml));
 }
  @Test
  public void postGroupAsXmlPartial_shouldEnforcePipelineGroupAdminPermissionsForPipelineTemplates()
      throws Exception {
    String md5 = setUpPipelineGroupsWithAdminPermissions();

    ConfigElementImplementationRegistry registry =
        ConfigElementImplementationRegistryMother.withNoPlugins();
    XmlUtils.validate(
        new FileInputStream(configHelper.getConfigFile()),
        GoConfigSchema.getCurrentSchema(),
        new XsdErrorTranslator(),
        new SAXBuilder(),
        registry.xsds());
    controller.postGroupAsXmlPartial(
        TemplatesConfig.PIPELINE_TEMPLATES_FAKE_GROUP_NAME, NEW_TEMPLATES, md5, response);

    assertThat(response.getStatus(), is(SC_UNAUTHORIZED));
    XmlUtils.validate(
        new FileInputStream(configHelper.getConfigFile()),
        GoConfigSchema.getCurrentSchema(),
        new XsdErrorTranslator(),
        new SAXBuilder(),
        registry.xsds());

    setCurrentUser("admin");
    controller.postGroupAsXmlPartial(
        TemplatesConfig.PIPELINE_TEMPLATES_FAKE_GROUP_NAME, NEW_TEMPLATES, md5, response);
    assertThat(response.getStatus(), is(SC_OK));
  }
  @Test
  public void verifyExpiredAccessToken() throws Exception {
    final Principal principal =
        org.jasig.cas.authentication.TestUtils.getPrincipal(ID, new HashMap<String, Object>());
    final Authentication authentication = new OAuthAuthentication(ZonedDateTime.now(), principal);
    final DefaultAccessTokenFactory expiringAccessTokenFactory = new DefaultAccessTokenFactory();
    expiringAccessTokenFactory.setExpirationPolicy(
        new ExpirationPolicy() {
          @Override
          public boolean isExpired(final TicketState ticketState) {
            return true;
          }
        });
    final AccessTokenImpl accessToken =
        (AccessTokenImpl) expiringAccessTokenFactory.create(TestUtils.getService(), authentication);
    oAuth20ProfileController.getTicketRegistry().addTicket(accessToken);

    final MockHttpServletRequest mockRequest =
        new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.PROFILE_URL);
    mockRequest.setParameter(OAuthConstants.ACCESS_TOKEN, accessToken.getId());
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    oAuth20ProfileController.handleRequest(mockRequest, mockResponse);
    assertEquals(200, mockResponse.getStatus());
    assertEquals(
        "{\"error\":\"" + OAuthConstants.EXPIRED_ACCESS_TOKEN + "\"}",
        mockResponse.getContentAsString());
  }
  @Test
  public void testFilterProcessesUrlVariationsRespected() throws Exception {
    // Setup our HTTP request
    MockHttpServletRequest request = createMockAuthenticationRequest();
    request.setServletPath("/j_OTHER_LOCATION");
    request.setRequestURI("/mycontext/j_OTHER_LOCATION");

    // Setup our filter configuration
    MockFilterConfig config = new MockFilterConfig(null, null);

    // Setup our expectation that the filter chain will not be invoked, as we redirect to
    // defaultTargetUrl
    MockFilterChain chain = new MockFilterChain(false);
    MockHttpServletResponse response = new MockHttpServletResponse();

    // Setup our test object, to grant access
    MockAuthenticationFilter filter = new MockAuthenticationFilter(true);
    filter.setFilterProcessesUrl("/j_OTHER_LOCATION");
    filter.setAuthenticationSuccessHandler(successHandler);

    // Test
    filter.doFilter(request, response, chain);
    assertEquals("/mycontext/logged_in.jsp", response.getRedirectedUrl());
    assertNotNull(SecurityContextHolder.getContext().getAuthentication());
    assertEquals(
        "test", SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
  }
Example #16
0
  public void testRedirectedUrlDoesNotIncludeJsessionid() throws Exception {
    commence();

    assertFalse(
        "jsessionid present in response URL: " + response.getRedirectedUrl(),
        response.getRedirectedUrl().contains("jsessionid"));
  }
  public void testCoverageContents() throws Exception {
    final Long processId = issueProcessAndWaitForTermination();

    final String request = RESTLET_PATH + "/" + processId.longValue();

    final MockHttpServletResponse response = getAsServletResponse(request);
    assertEquals(Status.SUCCESS_OK, Status.valueOf(response.getStatus()));
    assertEquals(MediaType.APPLICATION_ZIP, MediaType.valueOf(response.getContentType()));

    final ByteArrayInputStream responseStream = getBinaryInputStream(response);
    File dataDirectoryRoot = super.getTestData().getDataDirectoryRoot();
    File file = new File(dataDirectoryRoot, "testCoverageContents.zip");
    super.getTestData().copyTo(responseStream, file.getName());

    ZipFile zipFile = new ZipFile(file);
    try {
      // TODO: change this expectation once we normalize the raster file name
      String rasterName = RASTER_LAYER.getPrefix() + ":" + RASTER_LAYER.getLocalPart() + ".tiff";
      ZipEntry nextEntry = zipFile.getEntry(rasterName);
      assertNotNull(nextEntry);
      InputStream coverageInputStream = zipFile.getInputStream(nextEntry);
      // Use a file, geotiffreader might not work well reading out of a plain input stream
      File covFile = new File(file.getParentFile(), "coverage.tiff");
      IOUtils.copy(coverageInputStream, covFile);
      GeoTiffReader geoTiffReader = new GeoTiffReader(covFile);
      GridCoverage2D coverage = geoTiffReader.read(null);
      CoordinateReferenceSystem crs = coverage.getCoordinateReferenceSystem();
      assertEquals(CRS.decode("EPSG:4326", true), crs);
    } finally {
      zipFile.close();
    }
  }
Example #18
0
  public void testRedirectedUrlDoesIncludeService() throws Exception {
    commence();

    assertTrue(
        "service not present in response URL: " + response.getRedirectedUrl(),
        response.getRedirectedUrl().contains("service=" + URLEncoder.encode(SERVICE, "UTF-8")));
  }
  @Test
  public void checkAgentStatusShouldIncludeMd5Checksum_forAgent_forLauncher_whenChecksumsAreCached()
      throws Exception {
    when(pluginsZip.md5()).thenReturn("plugins-zip-md5");

    controller.checkAgentStatus(response);

    try (InputStream stream =
        new TFSJarDetector.DevelopmentServerTFSJarDetector(systemEnvironment)
            .getJarURL()
            .openStream()) {
      assertEquals(
          md5DigestOfStream(stream),
          response.getHeader(SystemEnvironment.AGENT_TFS_SDK_MD5_HEADER));
    }

    try (InputStream stream = JarDetector.create(systemEnvironment, "agent-launcher.jar")) {
      assertEquals(
          md5DigestOfStream(stream),
          response.getHeader(SystemEnvironment.AGENT_LAUNCHER_CONTENT_MD5_HEADER));
    }

    try (InputStream stream = JarDetector.create(systemEnvironment, "agent.jar")) {
      assertEquals(
          md5DigestOfStream(stream),
          response.getHeader(SystemEnvironment.AGENT_CONTENT_MD5_HEADER));
    }

    assertEquals(
        "plugins-zip-md5", response.getHeader(SystemEnvironment.AGENT_PLUGINS_ZIP_MD5_HEADER));
    assertEquals("8443", response.getHeader("Cruise-Server-Ssl-Port"));
  }
 @Test
 public void testGetTranslations() throws Exception {
   MockHttpServletResponse response = new MockHttpServletResponse();
   translationController.getTranslations(Locale.ENGLISH, response);
   assertThat(response.getStatus(), is(200));
   assertThat(response.getContentAsString(), isNotEmpty());
 }
Example #21
0
  public void testGetUserWithoutUsername() throws Exception {
    MockHttpServletRequest request = createMockRequest("GET", "/user/");
    MockHttpServletResponse response = new MockHttpServletResponse();
    servlet.service(request, response);

    assertTrue(response.getStatus() == MockHttpServletResponse.SC_NOT_FOUND);
  }
  @Test
  public void testParams() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/params");
    Object handler = null;
    try {
      handler = this.handlerMapping.getHandler(request);
    } catch (Exception e) {
      // There is no matching handlers and some default handler
      // See
      // org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping#handleNoMatch
      assertTrue(e instanceof UnsatisfiedServletRequestParameterException);
    }

    request = new MockHttpServletRequest("GET", "/params");
    request.addParameter("param1", "1");
    request.addParameter("param2", "1");

    handler = this.handlerMapping.getHandler(request).getHandler();

    MockHttpServletResponse response = new MockHttpServletResponse();

    this.handlerAdapter.handle(request, response, handler);
    String testResponse = response.getContentAsString();
    assertEquals("User=1;account=1", testResponse);

    request = new MockHttpServletRequest("GET", "/params");
    request.addParameter("param1", "1");
    handler = this.handlerMapping.getHandler(request).getHandler();

    response = new MockHttpServletResponse();

    this.handlerAdapter.handle(request, response, handler);
    testResponse = response.getContentAsString();
    assertEquals("User=1", testResponse);
  }
Example #23
0
  public void testGetAccount() throws Exception {
    User u1 = testHelper.makeDummyUser();
    u1 = userService.createUser(u1);

    logInUser(u1);

    MockHttpServletRequest request = createMockRequest("GET", "/account");
    MockHttpServletResponse response = new MockHttpServletResponse();
    servlet.service(request, response);

    assertEquals(response.getStatus(), MockHttpServletResponse.SC_OK);
    assertNotNull(response.getHeader("ETag"));

    CmpUser user = createUserFromXml(readXmlResponse(response));
    assertNotNull("user null", user);
    assertNotNull("user has no username", user.getUsername());
    assertEquals("usernames don't match", user.getUsername(), u1.getUsername());
    assertNotNull("user has no first name", user.getFirstName());
    assertEquals("first names don't match", user.getFirstName(), u1.getFirstName());
    assertNotNull("user has no last name", user.getLastName());
    assertEquals("last names don't match", user.getLastName(), u1.getLastName());
    assertNotNull("user has no email", user.getEmail());
    assertEquals("emails don't match", user.getEmail(), u1.getEmail());
    assertNotNull("user has no url", user.getUrl());
    assertNotNull("user has no homedir url", user.getHomedirUrl());
  }
  @Test
  public void testProduces() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/produces");
    request.addHeader("Accept", "application/xml");
    Object handler = this.handlerMapping.getHandler(request).getHandler();

    // See org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping#handleMatch
    assertEquals(
        Collections.singleton(MediaType.APPLICATION_XML),
        request.getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE));

    MockHttpServletResponse response = new MockHttpServletResponse();

    this.handlerAdapter.handle(request, response, handler);
    String testResponse = response.getContentAsString();
    assertEquals("<test>XML</test>", testResponse);

    request = new MockHttpServletRequest("GET", "/produces");
    request.addHeader("Accept", "application/json");
    handler = this.handlerMapping.getHandler(request).getHandler();

    // See org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping#handleMatch
    assertNull(
        "Negated expression should not be listed as a producible type",
        request.getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE));

    response = new MockHttpServletResponse();

    this.handlerAdapter.handle(request, response, handler);
    testResponse = response.getContentAsString();
    assertEquals("{\"json\":\"body\"}", testResponse);
  }
  @Test
  public void verifyOK() throws Exception {
    final MockHttpServletRequest mockRequest =
        new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.CODE, CODE);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();

    ((OAuth20WrapperController) oauth20WrapperController)
        .getServicesManager()
        .save(getRegisteredService(REDIRECT_URI, CLIENT_SECRET));

    final Map<String, Object> map = new HashMap<>();
    map.put(NAME, VALUE);
    final List<String> list = Arrays.asList(VALUE, VALUE);
    map.put(NAME2, list);

    final Principal p = org.jasig.cas.authentication.TestUtils.getPrincipal(ID, map);
    final TicketGrantingTicketImpl impl =
        new TicketGrantingTicketImpl(
            TGT_ID,
            org.jasig.cas.authentication.TestUtils.getAuthentication(p),
            new NeverExpiresExpirationPolicy());

    ((OAuth20WrapperController) oauth20WrapperController)
        .getTicketRegistry()
        .addTicket(
            new ServiceTicketImpl(
                CODE,
                impl,
                org.jasig.cas.authentication.TestUtils.getService(),
                false,
                new ExpirationPolicy() {
                  private static final long serialVersionUID = -7321055962209199811L;

                  @Override
                  public boolean isExpired(final TicketState ticketState) {
                    return false;
                  }
                }));

    oauth20WrapperController.handleRequest(mockRequest, mockResponse);

    ((OAuth20WrapperController) oauth20WrapperController).getTicketRegistry().deleteTicket(CODE);

    assertEquals("text/plain", mockResponse.getContentType());
    assertEquals(200, mockResponse.getStatus());
    final String body = mockResponse.getContentAsString();

    assertTrue(
        body.startsWith(
            OAuthConstants.ACCESS_TOKEN + '=' + TGT_ID + '&' + OAuthConstants.EXPIRES + '='));
    // delta = 2 seconds
    final int delta = 2;
    final int timeLeft =
        Integer.parseInt(StringUtils.substringAfter(body, '&' + OAuthConstants.EXPIRES + '='));
    assertTrue(timeLeft >= TIMEOUT - 10 - delta);
  }
 @Test(expected = IllegalArgumentException.class)
 public void verifyDeleteServiceNoService() throws Exception {
   final MockHttpServletResponse response = new MockHttpServletResponse();
   this.controller.deleteRegisteredService(1200, response);
   assertNull(this.servicesManager.findServiceBy(1200));
   assertFalse(response.getContentAsString().contains("serviceName"));
 }
 @Test
 public void customSuffix() throws Exception {
   registerAndRefreshContext("spring.groovy.template.suffix:.groovytemplate");
   MockHttpServletResponse response = render("suffixed");
   String result = response.getContentAsString();
   assertThat(result, containsString("suffixed"));
 }
  @Test
  public void testNormalOperationWithDefaultFilterProcessesUrl() throws Exception {
    // Setup our HTTP request
    MockHttpServletRequest request = createMockAuthenticationRequest();
    HttpSession sessionPreAuth = request.getSession();

    // Setup our filter configuration
    MockFilterConfig config = new MockFilterConfig(null, null);

    // Setup our expectation that the filter chain will not be invoked, as we redirect to
    // defaultTargetUrl
    MockFilterChain chain = new MockFilterChain(false);
    MockHttpServletResponse response = new MockHttpServletResponse();

    // Setup our test object, to grant access
    MockAuthenticationFilter filter = new MockAuthenticationFilter(true);

    filter.setFilterProcessesUrl("/j_mock_post");
    filter.setSessionAuthenticationStrategy(mock(SessionAuthenticationStrategy.class));
    filter.setAuthenticationSuccessHandler(successHandler);
    filter.setAuthenticationFailureHandler(failureHandler);
    filter.setAuthenticationManager(mock(AuthenticationManager.class));
    filter.afterPropertiesSet();

    // Test
    filter.doFilter(request, response, chain);
    assertEquals("/mycontext/logged_in.jsp", response.getRedirectedUrl());
    assertNotNull(SecurityContextHolder.getContext().getAuthentication());
    assertEquals(
        "test", SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
    // Should still have the same session
    assertEquals(sessionPreAuth, request.getSession());
  }
  /**
   * Tests getting the project's collections
   *
   * @throws InvalidXmlException
   * @throws BizInternalException
   * @throws BizPolicyException
   * @throws IOException
   */
  @Test
  public void testGetProjectsCollections()
      throws InvalidXmlException, BizInternalException, BizPolicyException, IOException {

    final String mimeType = "application/xml";
    final MockHttpServletRequest mockReq =
        newMockRequest("GET", projectOne.getId() + "/collections", "test.org", 80);
    MockHttpServletResponse resp = new MockHttpServletResponse();

    when(requestUtil.buildRequestUrl(any(HttpServletRequest.class)))
        .thenReturn(projectOne.getId() + "/collections");

    controller.setAuthenticatedUser(admin);
    controller.handleProjectCollectionsGetRequest(
        projectOne.getId(), mimeType, null, mockReq, resp);

    assertNotNull(resp);
    assertEquals(resp.getErrorMessage(), 200, resp.getStatus());
    Bop returnedBop =
        businessObjectBuilder.buildBusinessObjectPackage(
            new ByteArrayInputStream(resp.getContentAsByteArray()));
    assertNotNull(returnedBop);

    Set<Collection> collections = returnedBop.getCollections();
    assertNotNull(collections);
    assertEquals(1, collections.size());
  }
 @Test
 public void includesViewResolution() throws Exception {
   registerAndRefreshContext();
   MockHttpServletResponse response = render("includes");
   String result = response.getContentAsString();
   assertThat(result, containsString("here"));
   assertThat(response.getContentType(), equalTo("text/html;charset=UTF-8"));
 }