Java Code Examples for org.springframework.mock.web.MockHttpServletRequest#setContent()

The following examples show how to use org.springframework.mock.web.MockHttpServletRequest#setContent() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JsonRpcServerTest.java    From jsonrpc4j with MIT License 8 votes vote down vote up
@Test
public void testGzipRequest() throws IOException {
	MockHttpServletRequest request = new MockHttpServletRequest("POST", "/test-post");
	request.addHeader(CONTENT_ENCODING, "gzip");
	request.setContentType("application/json");
	byte[] bytes = "{\"jsonrpc\":\"2.0\",\"id\":123,\"method\":\"testMethod\",\"params\":[\"Whir?inaki\"]}".getBytes(StandardCharsets.UTF_8);

	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	GZIPOutputStream gos = new GZIPOutputStream(baos);
	gos.write(bytes);
	gos.close();

	request.setContent(baos.toByteArray());

	MockHttpServletResponse response = new MockHttpServletResponse();
	jsonRpcServer = new JsonRpcServer(Util.mapper, mockService, ServiceInterface.class, true);
	jsonRpcServer.handle(request, response);

	String responseContent = new String(response.getContentAsByteArray(), StandardCharsets.UTF_8);
	Assert.assertEquals(responseContent, "{\"jsonrpc\":\"2.0\",\"id\":123,\"result\":null}\n");
	Assert.assertNull(response.getHeader(CONTENT_ENCODING));
}
 
Example 2
Source File: NotificationSubjectHandlerMethodArgumentResolverTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void resolveArgument_wrongMessageType_reportsErrors() throws Exception {
	// Arrange
	NotificationSubjectHandlerMethodArgumentResolver resolver = new NotificationSubjectHandlerMethodArgumentResolver();

	byte[] subscriptionRequestJsonContent = FileCopyUtils.copyToByteArray(
			new ClassPathResource("subscriptionConfirmation.json", getClass())
					.getInputStream());
	MockHttpServletRequest servletRequest = new MockHttpServletRequest();
	servletRequest.setContent(subscriptionRequestJsonContent);

	MethodParameter methodParameter = new MethodParameter(
			ReflectionUtils.findMethod(NotificationMethods.class,
					"subscriptionMethod", NotificationStatus.class),
			0);

	// Assert
	assertThatThrownBy(() -> resolver.resolveArgument(methodParameter, null,
			new ServletWebRequest(servletRequest), null))
					.isInstanceOf(IllegalArgumentException.class)
					.hasMessageContaining(
							"@NotificationMessage annotated parameters are only allowed");
}
 
Example 3
Source File: JsonRpcServerTest.java    From jsonrpc4j with MIT License 6 votes vote down vote up
@Test
public void testCorruptRequest() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest("POST", "/test-post");
	request.setContentType("application/json");
	request.setContent("{NOT JSON}".getBytes(StandardCharsets.UTF_8));

	MockHttpServletResponse response = new MockHttpServletResponse();

	jsonRpcServer = new JsonRpcServer(Util.mapper, mockService, ServiceInterface.class, true);
	jsonRpcServer.handle(request, response);

	String content = response.getContentAsString();

	Assert.assertEquals(content, "{\"jsonrpc\":\"2.0\",\"id\":\"null\"," +
			"\"error\":{\"code\":-32700,\"message\":\"JSON parse error\"}}\n");
}
 
Example 4
Source File: JsonRpcServerTest.java    From jsonrpc4j with MIT License 6 votes vote down vote up
@Test
public void testGzipResponse() throws IOException {
	MockHttpServletRequest request = new MockHttpServletRequest("POST", "/test-post");
	request.addHeader(ACCEPT_ENCODING, "gzip");
	request.setContentType("application/json");
	request.setContent("{\"jsonrpc\":\"2.0\",\"id\":123,\"method\":\"testMethod\",\"params\":[\"Whir?inaki\"]}".getBytes(StandardCharsets.UTF_8));

	MockHttpServletResponse response = new MockHttpServletResponse();

	jsonRpcServer = new JsonRpcServer(Util.mapper, mockService, ServiceInterface.class, true);
	jsonRpcServer.handle(request, response);

	byte[] compressed = response.getContentAsByteArray();
	String sb = getCompressedResponseContent(compressed);

	Assert.assertEquals(sb, "{\"jsonrpc\":\"2.0\",\"id\":123,\"result\":null}");
	Assert.assertEquals("gzip", response.getHeader(CONTENT_ENCODING));
}
 
Example 5
Source File: JsonRpcServerTest.java    From jsonrpc4j with MIT License 6 votes vote down vote up
@Test
public void testGzipRequestAndResponse() throws IOException {
	MockHttpServletRequest request = new MockHttpServletRequest("POST", "/test-post");
	request.addHeader(CONTENT_ENCODING, "gzip");
	request.addHeader(ACCEPT_ENCODING, "gzip");
	request.setContentType("application/json");
	byte[] bytes = "{\"jsonrpc\":\"2.0\",\"id\":123,\"method\":\"testMethod\",\"params\":[\"Whir?inaki\"]}".getBytes(StandardCharsets.UTF_8);

	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	GZIPOutputStream gos = new GZIPOutputStream(baos);
	gos.write(bytes);
	gos.close();

	request.setContent(baos.toByteArray());

	MockHttpServletResponse response = new MockHttpServletResponse();
	jsonRpcServer = new JsonRpcServer(Util.mapper, mockService, ServiceInterface.class, true);
	jsonRpcServer.handle(request, response);

	byte[] compressed = response.getContentAsByteArray();
	String sb = getCompressedResponseContent(compressed);

	Assert.assertEquals(sb, "{\"jsonrpc\":\"2.0\",\"id\":123,\"result\":null}");
	Assert.assertEquals("gzip", response.getHeader(CONTENT_ENCODING));
}
 
Example 6
Source File: DefaultHttpStatusCodeProviderTest.java    From jsonrpc4j with MIT License 5 votes vote down vote up
public static void assertHttpStatusCodeForJsonRpcRequest(InputStream message, int expectedCode, JsonRpcServer server) throws Exception {
	MockHttpServletRequest req = new MockHttpServletRequest();
	MockHttpServletResponse res = new MockHttpServletResponse();
	req.setMethod(HttpMethod.POST.name());
	req.setContent(convertInputStreamToByteArray(message));
	server.handle(req, res);
	Assert.assertEquals(expectedCode, res.getStatus());
}
 
Example 7
Source File: SamlServiceTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyRequestBody() {
    final String body = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">"
        + "<SOAP-ENV:Header/><SOAP-ENV:Body><samlp:Request xmlns:samlp=\"urn:oasis:names:tc:SAML:1.0:protocol\" MajorVersion=\"1\" "
        + "MinorVersion=\"1\" RequestID=\"_192.168.16.51.1024506224022\" IssueInstant=\"2002-06-19T17:03:44.022Z\">"
        + "<samlp:AssertionArtifact>artifact</samlp:AssertionArtifact></samlp:Request></SOAP-ENV:Body></SOAP-ENV:Envelope>";
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.setContent(body.getBytes());

    final SamlService impl = SamlService.createServiceFrom(request);
    assertEquals("artifact", impl.getArtifactId());
    assertEquals("_192.168.16.51.1024506224022", impl.getRequestID());
}
 
Example 8
Source File: SamlServiceTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test
public void testRequestBody() {
    final String body = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">"
        + "<SOAP-ENV:Header/><SOAP-ENV:Body><samlp:Request xmlns:samlp=\"urn:oasis:names:tc:SAML:1.0:protocol\" MajorVersion=\"1\" "
        + "MinorVersion=\"1\" RequestID=\"_192.168.16.51.1024506224022\" IssueInstant=\"2002-06-19T17:03:44.022Z\">"
        + "<samlp:AssertionArtifact>artifact</samlp:AssertionArtifact></samlp:Request></SOAP-ENV:Body></SOAP-ENV:Envelope>";
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.setContent(body.getBytes());

    final SamlService impl = SamlService.createServiceFrom(request);
    assertEquals("artifact", impl.getArtifactId());
    assertEquals("_192.168.16.51.1024506224022", impl.getRequestID());
}
 
Example 9
Source File: IoUtilTest.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetRequestInputStream_headerWithPlaintext() throws Exception {
  MockHttpServletRequest request = new MockHttpServletRequest();
  request.setContent("test".getBytes(StandardCharsets.UTF_8));
  request.addHeader("Content-Encoding", "gzip");
  InputStream stream = IoUtil.getRequestInputStream(request);
  assertThat(stream).isNotInstanceOf(GZIPInputStream.class);
  assertThat(IoUtil.readStream(stream)).isEqualTo("test");
}
 
Example 10
Source File: WebDAVonContentUpdateTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Executes WebDAV method for testing
 * <p>
 * Sets content to request from a test file
 * 
 * @param methodName Method name to prepare, should be initialized (PUT, LOCK, UNLOCK are supported)
 * @param fileName the name of the file set to the context, can be used with path, i.e. "path/to/file/fileName.txt"
 * @param content If <b>not null</b> adds test content to the request
 * @param headers to set to request, can be null
 * @throws Exception
 */
private void executeMethod(String methodName, String fileName, byte[] content, Map<String, String> headers) throws Exception
{
    if (methodName == WebDAV.METHOD_PUT)
        method = new PutMethod();
    else if (methodName == WebDAV.METHOD_LOCK)
        method = new LockMethod();
    else if (methodName == WebDAV.METHOD_UNLOCK)
        method = new UnlockMethod();
    if (method != null)
    {
        request = new MockHttpServletRequest(methodName, "/alfresco/webdav/" + fileName);
        response = new MockHttpServletResponse();
        request.setServerPort(8080);
        request.setServletPath("/webdav");
        if (content != null)
        {
            request.setContent(content);
        }

        if (headers != null && !headers.isEmpty())
        {
            for (String key : headers.keySet())
            {
                request.addHeader(key, headers.get(key));
            }
        }

        method.setDetails(request, response, webDAVHelper, companyHomeNodeRef);

        method.execute();
    }
}
 
Example 11
Source File: CachedBodyHttpServletRequestUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void testGivenHttpServletRequestWithBody_whenCalledGetInputStream_ThenGetsServletInputStreamWithSameBody() throws IOException {
    // Given
    byte[] cachedBody = "{\"firstName\" :\"abc\",\"lastName\" : \"xyz\",\"age\" : 30\"}".getBytes();
    MockHttpServletRequest mockeddHttpServletRequest = new MockHttpServletRequest();
    mockeddHttpServletRequest.setContent(cachedBody);
    CachedBodyHttpServletRequest request = new CachedBodyHttpServletRequest(mockeddHttpServletRequest);

    // when
    InputStream inputStream = request.getInputStream();

    // then
    assertEquals(new String(cachedBody), new String(StreamUtils.copyToByteArray(inputStream)));
}
 
Example 12
Source File: IoUtilTest.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetRequestInputStream_emptyStream() throws Exception {
  MockHttpServletRequest request = new MockHttpServletRequest();
  request.setContent(new byte[0]);
  request.addHeader("Content-Encoding", "gzip");
  InputStream stream = IoUtil.getRequestInputStream(request);
  assertThat(stream).isNotInstanceOf(GZIPInputStream.class);
  assertThat(IoUtil.readStream(stream)).isEqualTo("");
}
 
Example 13
Source File: RequestLoggingFilterTest.java    From herd with Apache License 2.0 5 votes vote down vote up
private MockHttpServletRequest createServletRequest()
{
    MockHttpServletRequest request = new MockHttpServletRequest(null, "/test");
    request.setQueryString("param=value");
    request.setMethod("POST");
    MockHttpSession session = new MockHttpSession();
    request.setContent(PAYLOAD_CONTENT.getBytes());
    request.setSession(session);
    request.setRemoteUser("Test Remote User");
    return request;
}
 
Example 14
Source File: TestStatementsController.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void shouldUseTimeoutParameterForUpdateQueries() throws Exception {
	// prepare
	StatementsController controller = new StatementsController();

	final int maxExecution = 1;
	final MockHttpServletRequest request = new MockHttpServletRequest();
	request.setMethod(HttpMethod.POST.name());
	request.setContentType(Protocol.SPARQL_UPDATE_MIME_TYPE);
	request.addParameter(Protocol.TIMEOUT_PARAM_NAME, String.valueOf(maxExecution));
	final String updateString = "delete where { <monkey:pod> ?p ?o . }";
	request.setContent(updateString.getBytes(StandardCharsets.UTF_8));

	// prepare mocks
	final Repository repMock = Mockito.mock(Repository.class);
	final RepositoryConnection connectionMock = Mockito.mock(RepositoryConnection.class);
	final ParserConfig parserConfigMock = Mockito.mock(ParserConfig.class);
	final Update updateMock = Mockito.mock(Update.class);
	Mockito.when(repMock.getConnection()).thenReturn(connectionMock);
	Mockito.when(connectionMock.prepareUpdate(QueryLanguage.SPARQL, updateString, null)).thenReturn(updateMock);
	Mockito.when(connectionMock.getParserConfig()).thenReturn(parserConfigMock);

	// repository interceptor uses this attribute
	request.setAttribute("repository", repMock);

	// act
	controller.handleRequest(request, new MockHttpServletResponse());

	Mockito.verify(updateMock).setMaxExecutionTime(maxExecution);
}
 
Example 15
Source File: NotificationStatusHandlerMethodArgumentResolverTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Test
void resolveArgument_subscriptionRequest_createsValidSubscriptionStatus()
		throws Exception {
	// Arrange
	AmazonSNS amazonSns = mock(AmazonSNS.class);
	NotificationStatusHandlerMethodArgumentResolver resolver = new NotificationStatusHandlerMethodArgumentResolver(
			amazonSns);

	byte[] subscriptionRequestJsonContent = FileCopyUtils.copyToByteArray(
			new ClassPathResource("subscriptionConfirmation.json", getClass())
					.getInputStream());

	MockHttpServletRequest servletRequest = new MockHttpServletRequest();
	servletRequest.setContent(subscriptionRequestJsonContent);

	MethodParameter methodParameter = new MethodParameter(
			ReflectionUtils.findMethod(NotificationMethods.class,
					"subscriptionMethod", NotificationStatus.class),
			0);

	// Act
	Object resolvedArgument = resolver.resolveArgument(methodParameter, null,
			new ServletWebRequest(servletRequest), null);

	// Assert
	assertThat(resolvedArgument instanceof NotificationStatus).isTrue();
	((NotificationStatus) resolvedArgument).confirmSubscription();
	verify(amazonSns, times(1)).confirmSubscription(
			"arn:aws:sns:eu-west-1:111111111111:mySampleTopic",
			"1111111111111111111111111111111111111111111111"
					+ "1111111111111111111111111111111111111111111"
					+ "1111111111111111111111111111111111111111111"
					+ "1111111111111111111111111111111111111111111"
					+ "11111111111111111111111111111111111");
}
 
Example 16
Source File: MockZisRequestHandlerTest.java    From secure-data-service with Apache License 2.0 4 votes vote down vote up
private MockHttpServletRequest createMockRequest() {
    MockHttpServletRequest req = new MockHttpServletRequest("POST", "mockZis");
    req.setContent(MOCK_SIF_MESSAGE.getBytes());
    return req;
}
 
Example 17
Source File: RepositoryServletSecurityTest.java    From archiva with Apache License 2.0 4 votes vote down vote up
@Test
public void testPutWithInvalidUserAndGuestHasWriteAccess()
    throws Exception
{
    
    servlet.setDavSessionProvider( davSessionProvider );

    ArchivaDavResourceFactory archivaDavResourceFactory = (ArchivaDavResourceFactory) servlet.getResourceFactory();
    archivaDavResourceFactory.setHttpAuth( httpAuth );
    archivaDavResourceFactory.setServletAuth( servletAuth );

    servlet.setResourceFactory( archivaDavResourceFactory );

    AuthenticationResult result = new AuthenticationResult();

    EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
                                                       anyObject( HttpServletResponse.class ) ) ).andReturn(
        result );

    EasyMock.expect( servletAuth.isAuthenticated( anyObject( HttpServletRequest.class ),
                                                  anyObject( AuthenticationResult.class ) ) ).andThrow(
        new AuthenticationException( "Authentication error" ) );

    EasyMock.expect( servletAuth.isAuthorized( "guest", "internal",
                                               ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD ) ).andReturn(
        true );

    // ArchivaDavResourceFactory#isAuthorized()
    SecuritySession session = new DefaultSecuritySession();

    EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
                                                       anyObject( HttpServletResponse.class ) ) ).andReturn(
        result );

    EasyMock.expect( httpAuth.getSecuritySession( anyObject( HttpSession.class ) ) ).andReturn( session );

    EasyMock.expect( servletAuth.isAuthenticated( anyObject( HttpServletRequest.class ), eq( result ) ) ).andThrow(
        new AuthenticationException( "Authentication error" ) );

    EasyMock.expect( httpAuth.getSessionUser( anyObject( HttpSession.class ) ) ).andReturn( null );

    // check if guest has write access
    EasyMock.expect( servletAuth.isAuthorized( "guest", "internal",
                                               ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD ) ).andReturn(
        true );

    httpAuthControl.replay();
    servletAuthControl.replay();

    InputStream is = getClass().getResourceAsStream( "/artifact.jar" );
    assertNotNull( "artifact.jar inputstream", is );

    MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
    mockHttpServletRequest.addHeader( "User-Agent", "foo" );
    mockHttpServletRequest.setMethod( "PUT" );
    mockHttpServletRequest.setRequestURI( "/repository/internal/path/to/artifact.jar" );
    mockHttpServletRequest.setContent( IOUtils.toByteArray( is ) );
    mockHttpServletRequest.setContentType( "application/octet-stream" );

    MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();

    servlet.service( mockHttpServletRequest, mockHttpServletResponse );

    httpAuthControl.verify();
    servletAuthControl.verify();

    assertEquals( HttpServletResponse.SC_CREATED, mockHttpServletResponse.getStatus() );
}
 
Example 18
Source File: ParamsExtractorTests.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void testMultiPartPostExtractor() throws Exception
{
    ResourceWebScriptPost extractor = new ResourceWebScriptPost();
    extractor.setAssistant(assistant);
    extractor.setLocator(locator);

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

    WebScriptRequest request = mock(WebScriptRequest.class);
    when(request.getServiceMatch()).thenReturn(new Match(null, templateVars, null));

    File file = TempFileProvider.createTempFile("ParamsExtractorTests-", ".txt");
    PrintWriter writer = new PrintWriter(file);
    writer.println("Multipart Mock test.");
    writer.close();

    MultiPartRequest reqBody = MultiPartBuilder.create()
                .setFileData(new FileData(file.getName(), file, MimetypeMap.MIMETYPE_TEXT_PLAIN))
                .build();

    MockHttpServletRequest mockRequest = new MockHttpServletRequest("POST", "");
    mockRequest.setContent(reqBody.getBody());
    mockRequest.setContentType(reqBody.getContentType());

    when(request.getContentType()).thenReturn("multipart/form-data");
    when(request.parseContent()).thenReturn(new FormData(mockRequest));

    Params params = extractor.extractParams(mockEntity(), request);
    assertNotNull(params);
    Object passed = params.getPassedIn();
    assertNotNull(passed);
    assertTrue(FormData.class.isAssignableFrom(passed.getClass()));
    FormData formData = (FormData) passed;
    assertTrue(formData.getIsMultiPart());

    // No entity id for POST
    templateVars.put(ResourceLocator.ENTITY_ID, "1234");
    try
    {
        params = extractor.extractParams(mockEntity(), request);
        fail("Should not get here. No entity id for POST");
    }
    catch (UnsupportedResourceOperationException uoe)
    {
        assertNotNull(uoe);
    }

    params = extractor.extractParams(mockRelationship(), request);
    assertNotNull(params);
    assertEquals("1234", params.getEntityId());
    passed = params.getPassedIn();
    assertNotNull(passed);
    assertTrue(FormData.class.isAssignableFrom(passed.getClass()));
    formData = (FormData) passed;
    assertTrue(formData.getIsMultiPart());
}
 
Example 19
Source File: BaseNotificationMessageHandlerMethodArgumentResolverTest.java    From spring-cloud-aws with Apache License 2.0 4 votes vote down vote up
@Test
void resolveArgument_NotificationMessage_createsObjectWithAllFields()
		throws Exception {
	// Arrange
	AbstractNotificationMessageHandlerMethodArgumentResolver resolver;
	resolver = new AbstractNotificationMessageHandlerMethodArgumentResolver() {

		@Override
		protected Object doResolveArgumentFromNotificationMessage(JsonNode content,
				HttpInputMessage request, Class<?> parameterType) {
			return content;
		}

		@Override
		public boolean supportsParameter(MethodParameter parameter) {
			return true;
		}
	};

	MockHttpServletRequest servletRequest = new MockHttpServletRequest();
	ServletWebRequest servletWebRequest = new ServletWebRequest(servletRequest);

	byte[] fileContent = FileCopyUtils
			.copyToByteArray(new ClassPathResource("notificationMessage.json",
					AbstractNotificationMessageHandlerMethodArgumentResolver.class)
							.getInputStream());

	servletRequest.setContent(fileContent);

	MethodParameter methodParameter = new MethodParameter(
			ReflectionUtils.findMethod(NotificationMethods.class,
					"subscriptionMethod", NotificationStatus.class),
			0);
	// Act
	ObjectNode content = (ObjectNode) resolver.resolveArgument(methodParameter, null,
			servletWebRequest, null);

	// Assert
	assertThat(content.get("Type").asText()).isEqualTo("Notification");
	assertThat(content.get("MessageId").asText())
			.isEqualTo("f2c15fec-c617-5b08-b54d-13c4099fec60");
	assertThat(content.get("TopicArn").asText())
			.isEqualTo("arn:aws:sns:eu-west-1:111111111111:mySampleTopic");
	assertThat(content.get("Subject").asText()).isEqualTo("asdasd");
	assertThat(content.get("Message").asText()).isEqualTo("asdasd");
	assertThat(content.get("Timestamp").asText())
			.isEqualTo("2014-06-28T14:12:24.418Z");
	assertThat(content.get("SignatureVersion").asText()).isEqualTo("1");
	assertThat(content.get("Signature").asText())
			.isEqualTo("XDvKSAnhxECrAmyIrs0Dsfbp/tnKD1IvoOOYTU28FtbUoxr"
					+ "/CgziuW87yZwTuSNNbHJbdD3BEjHS0vKewm0xBeQ0PToDkgtoORXo"
					+ "5RWnmShDQ2nhkthFhZnNulKtmFtRogjBtCwbz8sPnbOCSk21ruyXNd"
					+ "V2RUbdDalndAW002CWEQmYMxFSN6OXUtMueuT610aX+tqeYP4Z6+8WT"
					+ "WLWjAuVyy7rOI6KHYBcVDhKtskvTOPZ4tiVohtQdQbO2Gjuh1vbl"
					+ "RzzwMkfaoFTSWImd4pFXxEsv/fq9aGIlqq9xEryJ0w2huFwI5gxyhvGt0RnTd9YvmAEC+WzdJDOqaDNxg==");
	assertThat(content.get("SigningCertURL").asText()).isEqualTo(
			"https://sns.eu-west-1.amazonaws.com/SimpleNotificationService-e372f8ca30337fdb084e8ac449342c77.pem");
	assertThat(content.get("UnsubscribeURL").asText()).isEqualTo(
			"https://sns.eu-west-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn="
					+ "arn:aws:sns:eu-west-1:721324560415:mySampleTopic:9859a6c9-6083-4690-ab02-d1aead3442df");
}
 
Example 20
Source File: RepositoryServletSecurityTest.java    From archiva with Apache License 2.0 4 votes vote down vote up
@Test
public void testPutWithValidUserWithNoWriteAccess()
    throws Exception
{
    
    servlet.setDavSessionProvider( davSessionProvider );

    ArchivaDavResourceFactory archivaDavResourceFactory = (ArchivaDavResourceFactory) servlet.getResourceFactory();
    archivaDavResourceFactory.setHttpAuth( httpAuth );
    archivaDavResourceFactory.setServletAuth( servletAuth );
    servlet.setResourceFactory( archivaDavResourceFactory );

    AuthenticationResult result = new AuthenticationResult();

    EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
                                                       anyObject( HttpServletResponse.class ) ) ).andReturn(
        result );

    EasyMock.expect( servletAuth.isAuthenticated( anyObject( HttpServletRequest.class ),
                                                  anyObject( AuthenticationResult.class ) ) ).andReturn( true );

    // ArchivaDavResourceFactory#isAuthorized()
    SecuritySession session = new DefaultSecuritySession();

    EasyMock.expect( httpAuth.getAuthenticationResult( anyObject( HttpServletRequest.class ),
                                                       anyObject( HttpServletResponse.class ) ) ).andReturn(
        result );

    MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();

    EasyMock.expect( httpAuth.getSecuritySession( mockHttpServletRequest.getSession( true ) ) ).andReturn(
        session );

    EasyMock.expect( httpAuth.getSessionUser( mockHttpServletRequest.getSession() ) ).andReturn( new SimpleUser() );

    EasyMock.expect( servletAuth.isAuthenticated( anyObject( HttpServletRequest.class ), eq( result ) ) ).andReturn(
        true );

    EasyMock.expect(
        servletAuth.isAuthorized( anyObject( HttpServletRequest.class ), eq( session ), eq( "internal" ),
                                  eq( ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD ) ) ).andThrow(
        new UnauthorizedException( "User not authorized" ) );
    httpAuthControl.replay();
    servletAuthControl.replay();

    InputStream is = getClass().getResourceAsStream( "/artifact.jar" );
    assertNotNull( "artifact.jar inputstream", is );

    mockHttpServletRequest.addHeader( "User-Agent", "foo" );
    mockHttpServletRequest.setMethod( "PUT" );
    mockHttpServletRequest.setRequestURI( "/repository/internal/path/to/artifact.jar" );
    mockHttpServletRequest.setContent( IOUtils.toByteArray( is ) );
    mockHttpServletRequest.setContentType( "application/octet-stream" );

    MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();

    servlet.service( mockHttpServletRequest, mockHttpServletResponse );

    httpAuthControl.verify();
    servletAuthControl.verify();

    assertEquals( HttpServletResponse.SC_UNAUTHORIZED, mockHttpServletResponse.getStatus() );
}