예제 #1
0
  @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");
  }
  /**
   * 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());
  }
예제 #3
0
 protected byte[] getBinary(MockHttpServletResponse response) {
   //        try {
   return response.getContentAsByteArray();
   //        } catch (Exception e) {
   //            throw new RuntimeException("Whoops, did you change the MockRunner version? " +
   //                     "If so, you might want to change this method too", e);
   //        }
 }
예제 #4
0
  @Test
  public void testExec() {
    try {
      ApplicationContext waco = getApplicationContext();
      GetGroupRequest req = new GetGroupRequest(waco, "getgroup");

      // Invalid request
      MockHttpServletRequest httpRequest = new MockHttpServletRequest();
      MockHttpServletResponse httpResponse = new MockHttpServletResponse();

      req.exec(httpRequest, httpResponse);
      InputStream fis = new ByteArrayInputStream(httpResponse.getContentAsByteArray());

      // create JiBX unmarshal context
      IBindingFactory bfact = BindingDirectory.getFactory(GetGroupResponse.class);
      IUnmarshallingContext unMarshallingContext = bfact.createUnmarshallingContext();

      // unmarshal to GetGroupResponse
      GetGroupResponse unMarshallingResult =
          (GetGroupResponse) unMarshallingContext.unmarshalDocument(fis, "UTF-8");

      assertEquals(ResponseStatusCode.ERROR, unMarshallingResult.getStatus());

      // Valid request
      httpRequest = new MockHttpServletRequest();
      httpResponse = new MockHttpServletResponse();

      httpRequest.setParameter("uuid", "dddddddd");
      req.exec(httpRequest, httpResponse);
      fis = new ByteArrayInputStream(httpResponse.getContentAsByteArray());

      // unmarshal to GetGroupResponse
      unMarshallingResult = (GetGroupResponse) unMarshallingContext.unmarshalDocument(fis, "UTF-8");

      assertEquals(ResponseStatusCode.OK, unMarshallingResult.getStatus());
    } catch (Exception e) {
      e.printStackTrace();
      fail();
    }
  }
예제 #5
0
  public static Object sendAndReceive(
      RouterController controller,
      MockHttpServletRequest request,
      final String action,
      String method,
      boolean namedParameter,
      Object data,
      final Object result) {

    MockHttpServletResponse response = new MockHttpServletResponse();

    int tid = (int) (Math.random() * 1000);
    Map<String, Object> edRequest = createRequestJson(action, method, namedParameter, tid, data);

    request.setContent(ControllerUtil.writeAsByte(edRequest));
    try {
      controller.router(request, response, Locale.ENGLISH);
    } catch (IOException e) {
      fail("call controller.router: " + e.getMessage());
    }
    List<ExtDirectResponse> responses = readDirectResponses(response.getContentAsByteArray());
    assertThat(responses).hasSize(1);

    ExtDirectResponse edResponse = responses.get(0);

    assertThat(edResponse.getAction()).isEqualTo(action);
    assertThat(edResponse.getMethod()).isEqualTo(method);
    assertThat(edResponse.getTid()).isEqualTo(tid);
    assertThat(edResponse.getWhere()).isNull();

    if (result == null) {
      assertThat(edResponse.getType()).isEqualTo("exception");
      assertThat(edResponse.getResult()).isNull();
      assertThat(edResponse.getMessage()).isEqualTo("Server Error");
    } else {
      assertThat(edResponse.getType()).isEqualTo("rpc");
      assertThat(edResponse.getMessage()).isNull();
      if (result == Void.TYPE) {
        assertThat(edResponse.getResult()).isNull();
      } else if (result instanceof Class<?>) {
        Object r = ControllerUtil.convertValue(edResponse.getResult(), (Class<?>) result);
        return r;
      } else if (result instanceof TypeReference) {
        Object r = ControllerUtil.convertValue(edResponse.getResult(), (TypeReference<?>) result);
        return r;
      } else {
        assertThat(edResponse.getResult()).isEqualTo(result);
      }
    }

    return edResponse.getResult();
  }
  @Test
  public void contentShouldIncludeMd5Checksum_forAgentLauncher() throws Exception {
    controller.downloadAgentLauncher(response);
    assertEquals("8443", response.getHeader("Cruise-Server-Ssl-Port"));
    assertEquals("application/octet-stream", response.getContentType());

    try (InputStream stream = JarDetector.create(systemEnvironment, "agent-launcher.jar")) {
      assertEquals(md5DigestOfStream(stream), response.getHeader("Content-MD5"));
    }
    try (InputStream is = JarDetector.create(systemEnvironment, "agent-launcher.jar")) {
      assertTrue(Arrays.equals(IOUtils.toByteArray(is), response.getContentAsByteArray()));
    }
  }
  @Test
  public void shouldRenderTheTfsJar() throws Exception {
    controller.downloadTfsImplJar(response);
    assertEquals("application/octet-stream", response.getContentType());

    try (InputStream stream =
        new TFSJarDetector.DevelopmentServerTFSJarDetector(systemEnvironment)
            .getJarURL()
            .openStream()) {
      assertEquals(md5DigestOfStream(stream), response.getHeader("Content-MD5"));
    }
    try (InputStream is =
        new TFSJarDetector.DevelopmentServerTFSJarDetector(systemEnvironment)
            .getJarURL()
            .openStream()) {
      assertTrue(Arrays.equals(IOUtils.toByteArray(is), response.getContentAsByteArray()));
    }
  }
  /**
   * Tests adding a project through the API
   *
   * @throws InvalidXmlException
   * @throws BizInternalException
   * @throws BizPolicyException
   * @throws IOException
   */
  @Test
  public void testAddProject()
      throws InvalidXmlException, BizInternalException, BizPolicyException, IOException {
    Project newProject = new Project();
    newProject.setName("Test Project To Add");
    newProject.setDescription("adding this project");
    List<String> numbers = new ArrayList<String>();
    numbers.add("1");
    numbers.add("2");
    newProject.setNumbers(numbers);
    newProject.setFundingEntity("The Fed");
    newProject.setStartDate(new DateTime(2012, 5, 4, 0, 0));
    newProject.setEndDate(new DateTime(2013, 12, 23, 0, 0));
    newProject.addPi(admin.getId());

    final String mimeType = "application/xml";
    final MockHttpServletRequest mockReq = newMockRequest("POST", "/project", "test.org", 80);
    MockHttpServletResponse resp = new MockHttpServletResponse();

    ByteArrayOutputStream sink = new ByteArrayOutputStream();
    businessObjectBuilder.buildProject(newProject, sink);

    controller.setAuthenticatedUser(admin);
    controller.handleProjectPostRequest(mimeType, sink.toByteArray(), mockReq, resp);

    assertNotNull(resp);

    assertEquals(201, resp.getStatus());
    Bop bop =
        businessObjectBuilder.buildBusinessObjectPackage(
            new ByteArrayInputStream(resp.getContentAsByteArray()));

    assertNotNull(bop);

    Set<Project> projects = bop.getProjects();
    assertNotNull(projects);
    assertEquals(1, projects.size());

    Project returnedProject = projects.iterator().next();

    // Have to set the original project id to the id set by the biz service.
    newProject.setId(returnedProject.getId());
    assertEquals(newProject, returnedProject);
  }
  /**
   * Tests that the project metadata is successfully updated.
   *
   * @throws InvalidXmlException
   * @throws ProjectServiceException
   * @throws BizPolicyException
   * @throws IOException
   */
  @Test
  public void testUpdateProject()
      throws InvalidXmlException, BizInternalException, BizPolicyException, IOException {

    Project newProject = new Project(projectOne);
    newProject.setName("Update");
    newProject.setDescription("foo-update");
    newProject.setEndDate(new DateTime(2014, 2, 10, 0, 0));

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

    ByteArrayOutputStream sink = new ByteArrayOutputStream();
    businessObjectBuilder.buildProject(newProject, sink);

    controller.setAuthenticatedUser(admin);
    controller.handleUpdateProjectRequest(
        projectOne.getId(), mimeType, sink.toByteArray(), mockReq, resp);

    assertNotNull(resp);
    assertEquals(resp.getErrorMessage(), 200, resp.getStatus());

    Bop bop =
        businessObjectBuilder.buildBusinessObjectPackage(
            new ByteArrayInputStream(resp.getContentAsByteArray()));

    assertNotNull(bop);

    Set<Project> projects = bop.getProjects();
    assertNotNull(projects);
    assertEquals(1, projects.size());

    Project returnedProject = projects.iterator().next();
    assertNotNull(returnedProject);

    assertTrue(returnedProject.getName().equalsIgnoreCase(newProject.getName()));
    assertTrue(returnedProject.getDescription().equalsIgnoreCase(newProject.getDescription()));
    assertTrue(returnedProject.getEndDate().equals(newProject.getEndDate()));

    assertTrue(returnedProject.getFundingEntity().equalsIgnoreCase(newProject.getFundingEntity()));
  }
  /**
   * Test getting a project
   *
   * @throws InvalidXmlException
   * @throws BizInternalException
   * @throws BizPolicyException
   * @throws IOException
   */
  @Test
  public void testGetProject()
      throws InvalidXmlException, BizInternalException, BizPolicyException, IOException {

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

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

    assertNotNull(resp);
    assertEquals(resp.getErrorMessage(), 200, resp.getStatus());
    Bop bop =
        businessObjectBuilder.buildBusinessObjectPackage(
            new ByteArrayInputStream(resp.getContentAsByteArray()));
    assertNotNull(bop);
    assertEquals(1, bop.getProjects().size());
    assertEquals(projectOne, bop.getProjects().iterator().next());
  }
예제 #11
0
  @Test
  public void testDoFilterNoCompression() throws Exception {
    MockHttpServletRequest request =
        new MockHttpServletRequest(HttpMethod.POST.name(), "http://localhost:8080/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);

    String unzipped = new String(response.getContentAsByteArray());
    Assert.assertEquals(unzipped, "Should be compressed");
  }
예제 #12
0
  @Test
  public void renderAvatarShouldNotReturnNotModifiedAvatarInResponse()
      throws IOException, NotFoundException {
    JCUser user = getUser();
    user.setAvatar(validAvatar);
    user.setAvatarLastModificationTime(new DateTime(0));
    when(userService.get(anyLong())).thenReturn(user);
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addHeader(avatarController.IF_MODIFIED_SINCE_HEADER, new Date(1000));

    avatarController.renderAvatar(request, response, 0L);

    assertEquals(response.getStatus(), HttpServletResponse.SC_NOT_MODIFIED);
    assertNotSame(response.getContentAsByteArray(), validAvatar);
    assertEquals(response.getHeader("Pragma"), "public");
    List<String> cacheControlHeaders = response.getHeaders("Cache-Control");
    assertTrue(cacheControlHeaders.contains("public"));
    assertTrue(cacheControlHeaders.contains("must-revalidate"));
    assertTrue(cacheControlHeaders.contains("max-age=0"));
    assertNotNull(response.getHeader("Expires")); // System.currentTimeMillis() is used
    assertNotNull(response.getHeader("Last-Modified")); // depends on current timezone
  }
예제 #13
0
  public Tuple service(String method, String path, Map<String, String> headers, byte[] data) {

    WebDAVStorage webDAVStorage = new DLWebDAVStorageImpl();

    webDAVStorage.setToken("document_library");

    WebDAVUtil.addStorage(webDAVStorage);

    WebDAVServlet webDAVServlet = new WebDAVServlet();

    String requestURI = _CONTEXT_PATH + _SERVLET_PATH + _PATH_INFO_PREFACE + path;

    MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(method, requestURI);

    mockHttpServletRequest.setContextPath(_CONTEXT_PATH);
    mockHttpServletRequest.setServletPath(_SERVLET_PATH);
    mockHttpServletRequest.setPathInfo(_PATH_INFO_PREFACE + path);

    try {
      mockHttpServletRequest.setRemoteUser(String.valueOf(TestPropsValues.getUserId()));
    } catch (Exception e) {
      Assert.fail("User ID cannot be initialized");
    }

    if (headers == null) {
      headers = new HashMap<String, String>();
    }

    headers.put(HttpHeaders.USER_AGENT, getUserAgent());

    try {
      throw new Exception();
    } catch (Exception e) {
      StackTraceElement[] stackTraceElements = e.getStackTrace();

      for (StackTraceElement stackTraceElement : stackTraceElements) {
        String methodName = stackTraceElement.getMethodName();

        if (methodName.equals("setUp")
            || methodName.equals("tearDown")
            || methodName.startsWith("test")) {

          String testName =
              StringUtil.extractLast(stackTraceElement.getClassName(), CharPool.PERIOD);

          testName =
              StringUtil.replace(testName, new String[] {"WebDAV", "Test"}, new String[] {"", ""});

          headers.put(
              "X-Litmus",
              testName
                  + ": ("
                  + stackTraceElement.getMethodName()
                  + ":"
                  + stackTraceElement.getLineNumber()
                  + ")");

          break;
        }
      }
    }

    if (data != null) {
      mockHttpServletRequest.setContent(data);

      String contentType = headers.remove(HttpHeaders.CONTENT_TYPE);

      if (contentType != null) {
        mockHttpServletRequest.setContentType(contentType);
      } else {
        mockHttpServletRequest.setContentType(ContentTypes.TEXT_PLAIN);
      }
    }

    for (Map.Entry<String, String> entry : headers.entrySet()) {
      String key = entry.getKey();
      String value = entry.getValue();

      mockHttpServletRequest.addHeader(key, value);
    }

    try {
      MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();

      webDAVServlet.service(mockHttpServletRequest, mockHttpServletResponse);

      int statusCode = mockHttpServletResponse.getStatus();
      byte[] responseBody = mockHttpServletResponse.getContentAsByteArray();

      Map<String, String> responseHeaders = new HashMap<String, String>();

      for (String name : mockHttpServletResponse.getHeaderNames()) {
        responseHeaders.put(name, (String) mockHttpServletResponse.getHeader(name));
      }

      return new Tuple(statusCode, responseBody, responseHeaders);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return null;
  }
  /**
   * Test getting all the projects for a user
   *
   * @throws InvalidXmlException
   * @throws BizInternalException
   * @throws BizPolicyException
   * @throws IOException
   * @throws ServletException
   */
  @Test
  public void testGetAllProjects()
      throws InvalidXmlException, BizPolicyException, IOException, ServletException {

    // Test getting the list of project without logging in
    final String mimeType = "application/xml";
    final MockHttpServletRequest mockReq = newMockRequest("GET", "/project", "test.org", 80);
    MockHttpServletResponse resp = new MockHttpServletResponse();

    controller.handleEmptyGetRequest(mimeType, null, mockReq, resp);

    assertNotNull(resp);
    assertEquals(401, resp.getStatus());

    // Test getting a single project
    ProjectBizService bizService = mock(ProjectBizService.class);
    HashSet<Project> projects = new HashSet<Project>();
    projects.add(projectOne);

    when(bizService.findByAdmin(admin)).thenReturn(projects);
    controller.setBizService(bizService);

    controller.setAuthenticatedUser(admin);
    resp = new MockHttpServletResponse();
    controller.handleEmptyGetRequest(mimeType, null, mockReq, resp);
    assertNotNull(resp);
    assertEquals(200, resp.getStatus());

    Bop bop =
        businessObjectBuilder.buildBusinessObjectPackage(
            new ByteArrayInputStream(resp.getContentAsByteArray()));
    assertNotNull(bop);
    assertEquals(1, bop.getProjects().size());

    // Test a query that returns no projects

    projects.clear();

    when(bizService.findByAdmin(user)).thenReturn(projects);
    controller.setAuthenticatedUser(user);
    resp = new MockHttpServletResponse();
    controller.handleEmptyGetRequest(mimeType, null, mockReq, resp);
    assertNotNull(resp);
    assertEquals(200, resp.getStatus());

    bop =
        businessObjectBuilder.buildBusinessObjectPackage(
            new ByteArrayInputStream(resp.getContentAsByteArray()));
    assertNotNull(bop);
    assertEquals(0, bop.getProjects().size());

    // Test admin sees all projects in the system
    Project newProject = new Project();
    newProject.setId(testProjectIdTwo);
    newProject.setName("Second_Test_Project");
    newProject.setDescription("foo");
    List<String> numbers = new ArrayList<String>();
    numbers.add("54321");
    numbers.add("9876");
    newProject.setNumbers(numbers);
    newProject.setFundingEntity("moo");
    newProject.setStartDate(new DateTime(2012, 5, 4, 0, 0));
    newProject.setEndDate(new DateTime(2013, 12, 23, 0, 0));
    newProject.addPi(user.getId());
    projectService.create(newProject);

    controller.setBizService(projectBizService);
    controller.setAuthenticatedUser(admin);
    resp = new MockHttpServletResponse();
    controller.handleEmptyGetRequest(mimeType, null, mockReq, resp);
    assertNotNull(resp);
    assertEquals(200, resp.getStatus());

    bop =
        businessObjectBuilder.buildBusinessObjectPackage(
            new ByteArrayInputStream(resp.getContentAsByteArray()));
    assertNotNull(bop);
    assertEquals(projectService.getAll().size(), bop.getProjects().size());
  }
  /**
   * Tests that admin can be added and removed from a project
   *
   * @throws IOException
   * @throws BizPolicyException
   * @throws ProjectServiceException
   * @throws InvalidXmlException
   * @throws BizInternalException
   */
  @Test
  public void testUpdateProjectAdmin()
      throws InvalidXmlException, ProjectServiceException, BizPolicyException, IOException,
          BizInternalException {

    // Test adding an admin to the project.
    Project newProject = new Project(projectOne);
    newProject.addPi(user.getId());

    final String mimeType = "application/xml";
    final MockHttpServletRequest mockReq =
        newMockRequest("PUT", projectOne.getId(), "test.org", 80);

    MockHttpServletResponse resp = new MockHttpServletResponse();

    ByteArrayOutputStream sink = new ByteArrayOutputStream();
    businessObjectBuilder.buildProject(newProject, sink);

    controller.setAuthenticatedUser(admin);
    controller.handleUpdateProjectRequest(
        newProject.getId(), mimeType, sink.toByteArray(), mockReq, resp);

    assertNotNull(resp);
    assertEquals(resp.getErrorMessage(), 200, resp.getStatus());

    Bop bop =
        businessObjectBuilder.buildBusinessObjectPackage(
            new ByteArrayInputStream(resp.getContentAsByteArray()));

    assertNotNull(bop);

    Set<Project> projects = bop.getProjects();
    assertNotNull(projects);
    assertEquals(1, projects.size());

    Project returnedProject = projects.iterator().next();
    assertNotNull(returnedProject);

    assertEquals(newProject.getPis().size(), returnedProject.getPis().size());

    // Test removing an admin from the project.
    newProject.removePi(user.getId());

    resp = new MockHttpServletResponse();

    sink = new ByteArrayOutputStream();
    businessObjectBuilder.buildProject(newProject, sink);

    controller.setAuthenticatedUser(admin);
    controller.handleUpdateProjectRequest(
        newProject.getId(), mimeType, sink.toByteArray(), mockReq, resp);

    assertNotNull(resp);
    bop =
        businessObjectBuilder.buildBusinessObjectPackage(
            new ByteArrayInputStream(resp.getContentAsByteArray()));

    assertNotNull(bop);

    projects = bop.getProjects();
    assertNotNull(projects);
    assertEquals(1, projects.size());

    returnedProject = projects.iterator().next();
    assertNotNull(returnedProject);

    assertEquals(newProject.getPis().size(), returnedProject.getPis().size());
  }