org.apache.commons.io.IOUtils#resourceToString ( )源码实例Demo

下面列出了org.apache.commons.io.IOUtils#resourceToString ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@Before
public void setup() throws IOException {
	xsuaaToken = new XsuaaToken(IOUtils.resourceToString("/xsuaaCCAccessTokenRSA256.txt", UTF_8));

	mockConfiguration = Mockito.mock(OAuth2ServiceConfiguration.class);
	when(mockConfiguration.getService()).thenReturn(Service.XSUAA);

	tokenKeyServiceMock = Mockito.mock(OAuth2TokenKeyService.class);
	when(tokenKeyServiceMock
			.retrieveTokenKeys(any()))
					.thenReturn(IOUtils.resourceToString("/jsonWebTokenKeys.json", UTF_8));

	cut = new JwtSignatureValidator(
			mockConfiguration,
			OAuth2TokenKeyServiceWithCache.getInstance().withTokenKeyService(tokenKeyServiceMock),
			OidcConfigurationServiceWithCache.getInstance()
					.withOidcConfigurationService(Mockito.mock(OidcConfigurationService.class)));
}
 
@Test
public void validationFails_withXsuaaCombiningValidator() throws IOException {
	String vcapServices = IOUtils.resourceToString("/vcapXsuaaServiceSingleBinding.json", UTF_8);
	JsonObject serviceJsonObject = new DefaultJsonObject(vcapServices).getJsonObjects(Service.XSUAA.getCFName())
			.get(0);
	Map<String, String> credentialsMap = serviceJsonObject.getJsonObject(CFConstants.CREDENTIALS).getKeyValueMap();

	OAuth2ServiceConfiguration configuration = OAuth2ServiceConfigurationBuilder.forService(Service.XSUAA)
			.withProperties(credentialsMap)
			.build();

	CombiningValidator<Token> tokenValidator = JwtValidatorBuilder.getInstance(configuration)
			.withHttpClient(httpClientMock)
			.build();

	Token xsuaaToken = spy(new XsuaaToken(
			IOUtils.resourceToString("/xsuaaUserAccessTokenRSA256.txt", StandardCharsets.UTF_8)));

	ValidationResult result = tokenValidator.validate(xsuaaToken);
	assertThat(result.isValid()).isTrue();
}
 
@Before
public void setup() throws IOException {
	/**
	 * Header -------- { "alg": "RS256", } Payload -------- { "iss":
	 * "http://xsa-a272d86a-0f74-448c-93d1-6b78903d1543/UAA/oauth/token" }
	 */
	xsaToken = new XsuaaToken(
			IOUtils.resourceToString("/xsuaaXsaAccessTokenRSA256_signedWithVerificationKey.txt", UTF_8));

	mockConfiguration = Mockito.mock(OAuth2ServiceConfiguration.class);
	when(mockConfiguration.getService()).thenReturn(Service.XSUAA);
	when(mockConfiguration.isLegacyMode()).thenReturn(true);
	when(mockConfiguration.getUrl()).thenReturn(PROVIDER_URI);

	tokenKeyServiceMock = Mockito.mock(OAuth2TokenKeyService.class);
	when(tokenKeyServiceMock
			.retrieveTokenKeys(JKU_URI))
					.thenReturn(IOUtils.resourceToString("/jsonWebTokenKeys.json", UTF_8));

	cut = new JwtSignatureValidator(
			mockConfiguration,
			OAuth2TokenKeyServiceWithCache.getInstance().withTokenKeyService(tokenKeyServiceMock),
			OidcConfigurationServiceWithCache.getInstance()
					.withOidcConfigurationService(Mockito.mock(OidcConfigurationService.class)));
}
 
源代码4 项目: Prism4j   文件: TestUtils.java
@NotNull
public static Case readCase(@NotNull String file) {

    final String raw;
    try {
        raw = IOUtils.resourceToString(file, StandardCharsets.UTF_8, TestUtils.class.getClassLoader());
    } catch (Throwable t) {
        throw new RuntimeException(t);
    }

    if (raw == null
            || raw.length() == 0) {
        throw new RuntimeException("Test file has no contents, file: " + file);
    }

    final String[] split = raw.split(DELIMITER);
    if (split.length < 2) {
        throw new RuntimeException("Test file seems to have wrong delimiter, file: " + file);
    }

    final String input = split[0].trim();
    final JsonArray simplifiedOutput = GSON.fromJson(split[1].trim(), JsonArray.class);
    final String description = split[2].trim();

    return new Case(input, simplifiedOutput, description);
}
 
源代码5 项目: Markwon   文件: TaskListTest.java
@SuppressWarnings("SameParameterValue")
@NonNull
private static String read(@NonNull String name) {
    try {
        return IOUtils.resourceToString("tests/" + name, StandardCharsets.UTF_8, TaskListDrawable.class.getClassLoader());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
@Test
public void getIasKeys() throws IOException, InvalidKeySpecException, NoSuchAlgorithmException {
	jsonWebTokenKeys = IOUtils.resourceToString("/iasJsonWebTokenKeys.json", StandardCharsets.UTF_8);
	JsonWebKeySet jwks = JsonWebKeySetFactory.createFromJson(jsonWebTokenKeys);
	JsonWebKey jwk = jwks.getKeyByAlgorithmAndId(JwtSignatureAlgorithm.RS256, null);
	assertThat(jwk.getKeyAlgorithm().type(), equalTo("RSA"));
	assertThat(jwk.getPublicKey().getAlgorithm(), equalTo(jwk.getKeyAlgorithm().type()));
	assertThat(jwk.getId(), equalTo(JsonWebKey.DEFAULT_KEY_ID));
}
 
public CFEnvParserTest() throws IOException {
	String vcapXsuaa = IOUtils.resourceToString("/vcapXsuaaServiceSingleBinding.json", UTF_8);

	JsonObject serviceJsonObject = new DefaultJsonObject(vcapXsuaa).getJsonObjects(Service.XSUAA.getCFName())
			.get(0);
	cut = CFEnvParser.extract(Service.XSUAA, serviceJsonObject);
}
 
protected static String readPrivateKeyFromFile() {
	String privateKey;
	try {
		privateKey = IOUtils.resourceToString(PRIVATE_KEY_FILE, StandardCharsets.UTF_8); // PEM format
	} catch (IOException e) {
		throw new IllegalStateException("privateKey could not be read from " + PRIVATE_KEY_FILE, e);
	}
	return privateKey;
}
 
@Test
public void ignoreApiAccessPlan() throws IOException {
	String vcapMultipleBindings = IOUtils.resourceToString("/vcap_multipleBindings.json", Charset.forName("UTF-8"));
	XsuaaServicesParser cut = new XsuaaServicesParser(vcapMultipleBindings);
	Properties properties = cut.parseCredentials();
	assertThat(properties.getProperty("clientid")).isEqualTo("client-id");
}
 
@Test(expected = IllegalStateException.class)
public void doNotAllowBrokerAndApplicationPlan() throws IOException {
	String vcapMultipleBindings = IOUtils.resourceToString("/vcap_multipleBindings.json", Charset.forName("UTF-8"));
	vcapMultipleBindings = vcapMultipleBindings.replace("apiaccess", "broker");
	XsuaaServicesParser cut = new XsuaaServicesParser(vcapMultipleBindings);
	cut.parseCredentials();
}
 
源代码11 项目: Prism4j   文件: PrismBundler.java
@NotNull
private static String grammarLocatorTemplate() {
    try {
        return IOUtils.resourceToString("/GrammarLocator.template.java", StandardCharsets.UTF_8);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
@Test
public void iasTokenValidationSucceeds_withIasCombiningValidator() throws IOException {
	CloseableHttpResponse oidcResponse = HttpClientTestFactory
			.createHttpResponse("{\"jwks_uri\" : \"https://application.auth.com/oauth2/certs\"}");
	CloseableHttpResponse tokenKeysResponse = HttpClientTestFactory
			.createHttpResponse(IOUtils.resourceToString("/iasJsonWebTokenKeys.json", UTF_8));

	when(httpClientMock.execute(any(HttpGet.class)))
			.thenReturn(oidcResponse)
			.thenReturn(tokenKeysResponse);

	String vcapServices = IOUtils.resourceToString("/vcapIasServiceSingleBinding.json", UTF_8);
	JsonObject serviceJsonObject = new DefaultJsonObject(vcapServices).getJsonObjects(Service.IAS.getCFName())
			.get(0);
	Map<String, String> credentialsMap = serviceJsonObject.getJsonObject(CFConstants.CREDENTIALS).getKeyValueMap();

	OAuth2ServiceConfiguration configuration = OAuth2ServiceConfigurationBuilder.forService(Service.IAS)
			.withProperties(credentialsMap)
			.build();

	CombiningValidator<Token> tokenValidator = JwtValidatorBuilder.getInstance(configuration)
			.withHttpClient(httpClientMock)
			.build();

	SapIdToken iasToken = new SapIdToken(
			IOUtils.resourceToString("/iasOidcTokenRSA256.txt", StandardCharsets.UTF_8));

	ValidationResult result = tokenValidator.validate(iasToken);
	assertThat(result.isValid()).isTrue();
}
 
@Before
public void setup() throws IOException {
	/**
	 * Header -------- { "alg": "RS256", "jku":
	 * "https://authentication.stagingaws.hanavlab.ondemand.com/token_keys", "kid":
	 * "key-id-1" } Payload -------- { "iss":
	 * "http://localhost:8080/uaa/oauth/token" }
	 */
	xsuaaToken = new XsuaaToken(IOUtils.resourceToString("/xsuaaCCAccessTokenRSA256.txt", UTF_8));
	/**
	 * Header -------- { "jku": "http://localhost:65148/token_keys", "alg": "RS256"
	 * }
	 */
	xsuaaTokenSignedWithVerificationKey = new XsuaaToken(
			IOUtils.resourceToString("/xsuaaAccessTokenRSA256_signedWithVerificationKey.txt", UTF_8));

	mockConfiguration = Mockito.mock(OAuth2ServiceConfiguration.class);
	when(mockConfiguration.getService()).thenReturn(Service.XSUAA);

	tokenKeyServiceMock = Mockito.mock(OAuth2TokenKeyService.class);
	when(tokenKeyServiceMock
			.retrieveTokenKeys(URI.create("https://authentication.stagingaws.hanavlab.ondemand.com/token_keys")))
					.thenReturn(IOUtils.resourceToString("/jsonWebTokenKeys.json", UTF_8));

	cut = new JwtSignatureValidator(
			mockConfiguration,
			OAuth2TokenKeyServiceWithCache.getInstance().withTokenKeyService(tokenKeyServiceMock),
			OidcConfigurationServiceWithCache.getInstance()
					.withOidcConfigurationService(Mockito.mock(OidcConfigurationService.class)));
}
 
@Test
public void validationFails_whenNoJkuHeaderButIssuerIsGiven() throws IOException {
	/**
	 *
	 * Header -------- { "alg": "RS256" } Payload -------- { "iss":
	 * "https://application.myauth.com" }
	 */
	Token tokenWithoutJkuButIssuer = new SapIdToken(IOUtils.resourceToString("/iasOidcTokenRSA256.txt", UTF_8));
	ValidationResult result = cut.validate(tokenWithoutJkuButIssuer);
	assertThat(result.isErroneous(), is(true));
	assertThat(result.getErrorDescription(),
			containsString("Token does not provide the required 'jku' header or 'issuer' claim."));
}
 
@Test
public void decode_whenJwksContainsFragment_throwsException() throws IOException {
	String token = IOUtils.resourceToString("/token_cc.txt", StandardCharsets.UTF_8);

	XsuaaJwtDecoder cut = (XsuaaJwtDecoder)new XsuaaJwtDecoderBuilder(configuration).build();
	cut.setTokenInfoExtractor(new TokenInfoExtractorImpl("https://subdomain.myauth.ondemand.com/token_keys#token_keys"));

	assertThatThrownBy(() -> cut.decode(token)).isInstanceOf(JwtException.class)
			.hasMessageContaining("Jwt token does not contain a valid 'jku' header parameter:");

}
 
public XSUserInfoAdapterTest() throws IOException {
	emptyToken = new XsuaaToken(IOUtils.resourceToString("/xsuaaEmptyToken.txt", UTF_8));
	token = new XsuaaToken(IOUtils.resourceToString("/xsuaaUserInfoAdapterToken.txt", UTF_8));
}
 
public DefaultOidcConfigurationServiceTest() throws IOException {
	jsonOidcConfiguration = IOUtils.resourceToString("/oidcConfiguration.json", StandardCharsets.UTF_8);
}
 
@Before
public void setUp() throws IOException {
	token = new XsuaaToken(IOUtils.resourceToString("/xsuaaUserAccessTokenRSA256.txt", UTF_8));
	sapIdToken = new SapIdToken(IOUtils.resourceToString("/iasOidcTokenRSA256.txt", UTF_8));
	SpringSecurityContext.clear();
}
 
@Test
public void getPrincipalShouldBeEqualForSameUser() throws IOException {
	Token userToken2 = new XsuaaToken(IOUtils.resourceToString("/xsuaaUserAccessTokenRSA256.txt", UTF_8));
	assertThat(userToken.getPrincipal()).isEqualTo(userToken2.getPrincipal());
}
 
protected String readFromFile(String path) throws IOException {
	return IOUtils.resourceToString(path, StandardCharsets.UTF_8);
}