下面列出了怎么用javax.ws.rs.core.UriBuilderException的API类实例代码及写法,或者点击链接到github查看源代码。
private URI doBuild(boolean fromEncoded, boolean encodePathSlash, Object... values) {
if (values == null) {
throw new IllegalArgumentException("Template parameter values are set to null");
}
for (int i = 0; i < values.length; i++) {
if (values[i] == null) {
throw new IllegalArgumentException("Template parameter value at position " + i + " is set to null");
}
}
UriParts parts = doBuildUriParts(fromEncoded, encodePathSlash, false, values);
try {
return buildURI(fromEncoded, parts.path, parts.query, parts.fragment);
} catch (URISyntaxException ex) {
throw new UriBuilderException("URI can not be built", ex);
}
}
/**
* This method will check the provided context path headers against an allow list (provided in nifi.properties) and throw an exception if the requested context path is not registered.
*
* @param uri the request URI
* @param request the HTTP request
* @param allowedContextPaths comma-separated list of valid context paths
* @return the resource path
* @throws UriBuilderException if the requested context path is not registered (header poisoning)
*/
public static String getResourcePath(URI uri, HttpServletRequest request, String allowedContextPaths) throws UriBuilderException {
String resourcePath = uri.getPath();
// Determine and normalize the context path
String determinedContextPath = determineContextPath(request);
determinedContextPath = normalizeContextPath(determinedContextPath);
// If present, check it and prepend to the resource path
if (StringUtils.isNotBlank(determinedContextPath)) {
verifyContextPath(allowedContextPaths, determinedContextPath);
// Determine the complete resource path
resourcePath = determinedContextPath + resourcePath;
}
return resourcePath;
}
@Override
public URI buildFromMap(Map<String, ?> values, boolean encodeSlashInPath) {
checkArgument(values != null, "Null values aren't allowed");
String uri;
encodeFragment();
if (ssp != null) {
uri = createUriFromSspWithValues(values, true);
} else {
preparePath();
uri = createUriWithValues(values, true, encodeSlashInPath);
}
try {
return new URI(uri);
} catch (URISyntaxException e) {
throw new UriBuilderException(e);
}
}
@Override
public URI buildFromEncodedMap(Map<String, ?> values) {
checkArgument(values != null, "Null values aren't allowed");
String uri;
encodeFragment();
if (ssp != null) {
uri = createUriFromSspWithValues(values, false);
} else {
preparePath();
uri = createUriWithValues(values, false, false);
}
try {
return new URI(uri);
} catch (URISyntaxException e) {
throw new UriBuilderException(e);
}
}
@Override
public URI build(Object[] values, boolean encodeSlashInPath) {
checkArgument(values != null, "Null values aren't allowed");
String uri;
encodeFragment();
if (ssp != null) {
uri = createUriFromSspWithValues(values, true);
} else {
preparePath();
uri = createUriWithValues(values, true, encodeSlashInPath);
}
try {
return new URI(uri);
} catch (URISyntaxException e) {
throw new UriBuilderException(e);
}
}
@Override
public URI buildFromEncoded(Object... values) {
checkArgument(values != null, "Null values aren't allowed");
String uri;
encodeFragment();
if (ssp != null) {
uri = createUriFromSspWithValues(values, false);
} else {
preparePath();
uri = createUriWithValues(values, false, false);
}
try {
return new URI(uri);
} catch (URISyntaxException e) {
throw new UriBuilderException(e);
}
}
private void parseMatrixParams(String matrixString) {
if (!isNullOrEmpty(matrixString)) {
int p = 0;
final int length = matrixString.length();
while (p < length) {
if (charAtIs(matrixString, p, '=')) {
throw new UriBuilderException("Matrix parameter name is empty");
}
int n = scan(matrixString, p, ';', length);
if (n > p) {
final String pair = matrixString.substring(p, n);
final int eq = scan(pair, 0, '=', pair.length());
if (eq == pair.length() || eq == (pair.length() - 1)) {
matrixParam(false, pair);
} else {
matrixParam(false, pair.substring(0, eq), pair.substring(eq + 1));
}
}
p = n + 1;
}
}
}
private SamlClientBuilder logIntoUnsignedSalesAppViaIdp() throws IllegalArgumentException, UriBuilderException {
return new SamlClientBuilder()
.authnRequest(getAuthServerSamlEndpoint(REALM_NAME), SAML_CLIENT_ID_SALES_POST, SAML_ASSERTION_CONSUMER_URL_SALES_POST, POST).build()
// Virtually perform login at IdP (return artificial SAML response)
.login().idp(SAML_BROKER_ALIAS).build()
.processSamlResponse(REDIRECT)
.transformObject(this::createAuthnResponse)
.targetAttributeSamlResponse()
.targetUri(getSamlBrokerUrl(REALM_NAME))
.build()
.updateProfile().username("a").email("[email protected]").firstName("A").lastName("B").build()
.followOneRedirect()
// Now returning back to the app
.processSamlResponse(POST)
.transformObject(this::extractNameIdAndSessionIndexAndTerminate)
.build();
}
public AuthenticationSessionModel createAuthenticationSessionForClient(String clientId)
throws UriBuilderException, IllegalArgumentException {
AuthenticationSessionModel authSession;
// set up the account service as the endpoint to call.
ClientModel client = clientId != null ? realm.getClientByClientId(clientId) : SystemClientUtil.getSystemClient(realm);
RootAuthenticationSessionModel rootAuthSession = new AuthenticationSessionManager(session).createAuthenticationSession(realm, true);
authSession = rootAuthSession.createAuthenticationSession(client);
authSession.setAction(AuthenticationSessionModel.Action.AUTHENTICATE.name());
authSession.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
String redirectUri = Urls.accountBase(uriInfo.getBaseUri()).path("/").build(realm.getName()).toString();
authSession.setRedirectUri(redirectUri);
authSession.setClientNote(OIDCLoginProtocol.REDIRECT_URI_PARAM, redirectUri);
authSession.setClientNote(OIDCLoginProtocol.RESPONSE_TYPE_PARAM, OAuth2Constants.CODE);
authSession.setClientNote(OIDCLoginProtocol.ISSUER, Urls.realmIssuer(uriInfo.getBaseUri(), realm.getName()));
return authSession;
}
/**
* Helper method to configure the OAuth accessCode/implicit flow parameters
* @param clientId OAuth2 client ID: Identifies the client making the request.
* Client applications may be scoped to a limited set of system access.
* @param scopes the list of requested scopes. Values include {@link OAuth#Scope_SIGNATURE}, {@link OAuth#Scope_EXTENDED}, {@link OAuth#Scope_IMPERSONATION}. You can also pass any advanced scope.
* @param redirectUri this determines where to deliver the response containing the authorization code or access token.
* @param responseType determines the response type of the authorization request.
* <br><i>Note</i>: these response types are mutually exclusive for a client application.
* A public/native client application may only request a response type of "token";
* a private/trusted client application may only request a response type of "code".
* @param state Allows for arbitrary state that may be useful to your application.
* The value in this parameter will be round-tripped along with the response so you can make sure it didn't change.
*/
public URI getAuthorizationUri(String clientId, java.util.List<String> scopes, String redirectUri, String responseType, String state) throws IllegalArgumentException, UriBuilderException {
String formattedScopes = (scopes == null || scopes.size() < 1) ? "" : scopes.get(0);
StringBuilder sb = new StringBuilder(formattedScopes);
for (int i = 1; i < scopes.size(); i++) {
sb.append("%20" + scopes.get(i));
}
UriBuilder builder = UriBuilder.fromUri(getOAuthBasePath())
.scheme("https")
.path("/oauth/auth")
.queryParam("response_type", responseType)
.queryParam("scope", sb.toString())
.queryParam("client_id", clientId)
.queryParam("redirect_uri", redirectUri);
if (state != null) {
builder = builder.queryParam("state", state);
}
return builder.build();
}
private URI createURI(String uri) {
try {
return new URI(uri);
} catch (URISyntaxException ex) {
throw new UriBuilderException(ex);
}
}
private URI doBuildFromMap(Map<String, ? extends Object> map, boolean fromEncoded,
boolean encodePathSlash)
throws IllegalArgumentException, UriBuilderException {
try {
Map<String, Object> alreadyResolvedTs = getResolvedTemplates(resolvedTemplates);
Map<String, Object> alreadyResolvedTsPathEnc = getResolvedTemplates(resolvedTemplatesPathEnc);
Map<String, Object> alreadyResolvedEncTs = getResolvedTemplates(resolvedEncodedTemplates);
String thePath = buildPath();
thePath = substituteMapped(thePath, map, alreadyResolvedTs, alreadyResolvedTsPathEnc,
alreadyResolvedEncTs, false, fromEncoded, encodePathSlash);
String theQuery = buildQuery();
if (theQuery != null) {
theQuery = substituteMapped(theQuery, map, alreadyResolvedTs, alreadyResolvedTsPathEnc,
alreadyResolvedEncTs, true, fromEncoded, false);
}
String theFragment = fragment == null
? null : substituteMapped(fragment, map, alreadyResolvedTs, alreadyResolvedTsPathEnc,
alreadyResolvedEncTs, true, fromEncoded, encodePathSlash);
return buildURI(fromEncoded, thePath, theQuery, theFragment);
} catch (URISyntaxException ex) {
throw new UriBuilderException("URI can not be built", ex);
}
}
@Override
public URI buildFromEncodedMap(Map<String, ?> map) throws IllegalArgumentException,
UriBuilderException {
Map<String, String> decodedMap = new HashMap<>(map.size());
for (Map.Entry<String, ? extends Object> entry : map.entrySet()) {
if (entry.getValue() == null) {
throw new IllegalArgumentException("Value is null");
}
String theValue = entry.getValue().toString();
if (theValue.contains("/")) {
// protecting '/' from being encoded here assumes that a given value may constitute multiple
// path segments - very questionable especially given that queries and fragments may also
// contain template vars - technically this can be covered by checking where a given template
// var is coming from and act accordingly. Confusing nonetheless.
StringBuilder buf = new StringBuilder();
String[] values = theValue.split("/");
for (int i = 0; i < values.length; i++) {
buf.append(HttpUtils.encodePartiallyEncoded(values[i], false));
if (i + 1 < values.length) {
buf.append('/');
}
}
decodedMap.put(entry.getKey(), buf.toString());
} else {
decodedMap.put(entry.getKey(), HttpUtils.encodePartiallyEncoded(theValue, false));
}
}
return doBuildFromMap(decodedMap, true, false);
}
@Test
@Ignore("to be fixed for TCK")
public void testNoArgsThrowsUriBuilderExceptionTest() {
Link.Builder builder = Link.fromUri("http://:@");
try {
Link link = builder.build();
fail("No exception has been thrown for link " + link);
} catch (UriBuilderException e) {
//expected
}
}
/**
* Throws an exception if the provided context path is not in the allowed context paths list.
*
* @param allowedContextPaths a comma-delimited list of valid context paths
* @param determinedContextPath the normalized context path from a header
* @throws UriBuilderException if the context path is not safe
*/
public static void verifyContextPath(String allowedContextPaths, String determinedContextPath) throws UriBuilderException {
// If blank, ignore
if (StringUtils.isBlank(determinedContextPath)) {
return;
}
// Check it against the allowed list
List<String> individualContextPaths = Arrays.asList(StringUtils.split(allowedContextPaths, ","));
if (!individualContextPaths.contains(determinedContextPath)) {
final String msg = "The provided context path [" + determinedContextPath + "] was not registered as allowed [" + allowedContextPaths + "]";
logger.error(msg);
throw new UriBuilderException(msg);
}
}
/**
* Returns a "safe" context path value from the request headers to use in a proxy environment.
* This is used on the JSP to build the resource paths for the external resources (CSS, JS, etc.).
* If no headers are present specifying this value, it is an empty string.
*
* @param request the HTTP request
* @param allowedContextPaths the comma-separated list of allowed context paths
* @param jspDisplayName the display name of the resource for log messages
* @return the context path safe to be printed to the page
*/
public static String sanitizeContextPath(ServletRequest request, String allowedContextPaths, String jspDisplayName) {
if (StringUtils.isBlank(jspDisplayName)) {
jspDisplayName = "JSP page";
}
String contextPath = normalizeContextPath(determineContextPath((HttpServletRequest) request));
try {
verifyContextPath(allowedContextPaths, contextPath);
return contextPath;
} catch (UriBuilderException e) {
logger.error("Error determining context path on " + jspDisplayName + ": " + e.getMessage());
return "";
}
}
AuthenticationSessionModel createAuthenticationSessionForClient(String clientID)
throws UriBuilderException, IllegalArgumentException {
AuthenticationSessionModel authSession;
ClientModel client = session.realms().getClientByClientId(clientID, realm);
String redirectUri;
if (client == null) {
client = SystemClientUtil.getSystemClient(realm);
redirectUri = Urls.accountBase(session.getContext().getUri().getBaseUri()).path("/").build(realm.getName()).toString();
} else {
redirectUri = RedirectUtils.getFirstValidRedirectUri(session, client.getRootUrl(), client.getRedirectUris());
}
RootAuthenticationSessionModel rootAuthSession = new AuthenticationSessionManager(session).createAuthenticationSession(realm, true);
authSession = rootAuthSession.createAuthenticationSession(client);
authSession.setAction(AuthenticationSessionModel.Action.AUTHENTICATE.name());
//authSession.setNote(AuthenticationManager.END_AFTER_REQUIRED_ACTIONS, "true");
authSession.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
authSession.setRedirectUri(redirectUri);
authSession.setClientNote(OIDCLoginProtocol.RESPONSE_TYPE_PARAM, OAuth2Constants.CODE);
authSession.setClientNote(OIDCLoginProtocol.REDIRECT_URI_PARAM, redirectUri);
authSession.setClientNote(OIDCLoginProtocol.ISSUER, Urls.realmIssuer(session.getContext().getUri().getBaseUri(), realm.getName()));
return authSession;
}
@Test
public void ImplicitLoginTest() {
System.out.println("\nImplicitLoginTest:\n" + "===========================================");
//ApiClient apiClient = new ApiClient(BaseUrl);
try {
// after successful login you should compare the value of URI decoded "state" query param
// with the one you create here; they should match.
//String randomState = "*^.$DGj*)+}Jk";
java.util.List<String> scopes = new ArrayList<String>();
scopes.add(OAuth.Scope_SIGNATURE);
// get DocuSign OAuth authorization url
//URI oAuthLoginUri = apiClient.getAuthorizationUri(IntegratorKeyImplicit, scopes, RedirectURI, OAuth.TOKEN, randomState);
// open DocuSign OAuth login in the browser
//Desktop.getDesktop().browse(oAuthLoginUri);
// IMPORTANT: after the login, DocuSign will send back a new
// access token in the hash fragment of the redirect URI.
// You should set up a client-side handler that handles window.location change to get
// that token and pass it to the ApiClient object as shown in the next
// lines:
//String token = "<once_you_get_the_oauth_token_put_it_here>";
// now that the API client has an OAuth token, let's use it in all
// DocuSign APIs
/*apiClient.setAccessToken(oAuthToken.getAccessToken(), oAuthToken.getExpiresIn());
UserInfo userInfo = apiClient.getUserInfo(token);
Assert.assertNotSame(null, userInfo);
Assert.assertNotNull(userInfo.getAccounts());
Assert.assertTrue(userInfo.getAccounts().size() > 0);
System.out.println("UserInfo: " + userInfo);
// parse first account's baseUrl
// below code required for production, no effect in demo (same
// domain)
apiClient.setBasePath(userInfo.getAccounts().get(0).getBaseUri() + "/restapi");
Configuration.setDefaultApiClient(apiClient);*/
} catch (UriBuilderException ex) {
System.out.println("UriBuilderException: " + ex);
} catch (Exception e) {
Assert.fail("Exception: " + e.getLocalizedMessage());
}
}
@Override
public Iterable<ListBlobItem> listBlobs(String prefix,
boolean useFlatBlobListing, EnumSet<BlobListingDetails> listingDetails,
BlobRequestOptions options, OperationContext opContext)
throws URISyntaxException, StorageException {
ArrayList<ListBlobItem> ret = new ArrayList<ListBlobItem>();
URI searchUri = null;
if (prefix == null) {
searchUri = uri;
} else {
try {
searchUri = UriBuilder.fromUri(uri).path(prefix).build();
} catch (UriBuilderException e) {
throw new AssertionError("Failed to encode path: " + prefix);
}
}
String fullPrefix = convertUriToDecodedString(searchUri);
boolean includeMetadata = listingDetails.contains(BlobListingDetails.METADATA);
HashSet<String> addedDirectories = new HashSet<String>();
for (InMemoryBlockBlobStore.ListBlobEntry current : backingStore.listBlobs(
fullPrefix, includeMetadata)) {
int indexOfSlash = current.getKey().indexOf('/', fullPrefix.length());
if (useFlatBlobListing || indexOfSlash < 0) {
if (current.isPageBlob()) {
ret.add(new MockCloudPageBlobWrapper(
convertKeyToEncodedUri(current.getKey()),
current.getMetadata(),
current.getContentLength()));
} else {
ret.add(new MockCloudBlockBlobWrapper(
convertKeyToEncodedUri(current.getKey()),
current.getMetadata(),
current.getContentLength()));
}
} else {
String directoryName = current.getKey().substring(0, indexOfSlash);
if (!addedDirectories.contains(directoryName)) {
addedDirectories.add(current.getKey());
ret.add(new MockCloudBlobDirectoryWrapper(new URI(
directoryName + "/")));
}
}
}
return ret;
}
@Override
public Iterable<ListBlobItem> listBlobs(String prefix,
boolean useFlatBlobListing, EnumSet<BlobListingDetails> listingDetails,
BlobRequestOptions options, OperationContext opContext)
throws URISyntaxException, StorageException {
ArrayList<ListBlobItem> ret = new ArrayList<ListBlobItem>();
URI searchUri = null;
if (prefix == null) {
searchUri = uri;
} else {
try {
searchUri = UriBuilder.fromUri(uri).path(prefix).build();
} catch (UriBuilderException e) {
throw new AssertionError("Failed to encode path: " + prefix);
}
}
String fullPrefix = convertUriToDecodedString(searchUri);
boolean includeMetadata = listingDetails.contains(BlobListingDetails.METADATA);
HashSet<String> addedDirectories = new HashSet<String>();
for (InMemoryBlockBlobStore.ListBlobEntry current : backingStore.listBlobs(
fullPrefix, includeMetadata)) {
int indexOfSlash = current.getKey().indexOf('/', fullPrefix.length());
if (useFlatBlobListing || indexOfSlash < 0) {
if (current.isPageBlob()) {
ret.add(new MockCloudPageBlobWrapper(
convertKeyToEncodedUri(current.getKey()),
current.getMetadata(),
current.getContentLength()));
} else {
ret.add(new MockCloudBlockBlobWrapper(
convertKeyToEncodedUri(current.getKey()),
current.getMetadata(),
current.getContentLength()));
}
} else {
String directoryName = current.getKey().substring(0, indexOfSlash);
if (!addedDirectories.contains(directoryName)) {
addedDirectories.add(current.getKey());
ret.add(new MockCloudBlobDirectoryWrapper(new URI(
directoryName + "/")));
}
}
}
return ret;
}
@Override
public URI buildFromEncodedMap(Map<String, ?> values) throws IllegalArgumentException, UriBuilderException {
// EMODB-MODIFICATION: Templates are not supported, so buildFromMap is not supported
throw new UnsupportedOperationException("Templates not supported");
}
@Override
public URI build(Object... values) throws IllegalArgumentException, UriBuilderException {
return doBuild(false, true, values);
}
@Override
public URI buildFromEncoded(Object... values) throws IllegalArgumentException, UriBuilderException {
return doBuild(true, false, values);
}
@Override
public URI buildFromMap(Map<String, ?> map) throws IllegalArgumentException,
UriBuilderException {
return doBuildFromMap(map, false, true);
}
@Override
public URI build(Object[] vars, boolean encodePathSlash) throws IllegalArgumentException, UriBuilderException {
return doBuild(false, encodePathSlash, vars);
}
@Override
public URI buildFromMap(Map<String, ?> map, boolean encodePathSlash) throws IllegalArgumentException,
UriBuilderException {
return doBuildFromMap(map, false, encodePathSlash);
}
@Override
public Link build(Object... values) throws UriBuilderException {
checkArgument(values != null, "Null values aren't allowed");
URI myUri = resolveLinkUri(values);
return new LinkImpl(myUri, params);
}
protected URI getAuthServerSamlEndpoint(String realm) throws IllegalArgumentException, UriBuilderException {
return RealmsResource
.protocolUrl(UriBuilder.fromUri(getAuthServerRoot()))
.build(realm, SamlProtocol.LOGIN_PROTOCOL);
}
protected URI getAuthServerRealmBase(String realm) throws IllegalArgumentException, UriBuilderException {
return RealmsResource
.realmBaseUrl(UriBuilder.fromUri(getAuthServerRoot()))
.build(realm);
}
private URI getAuthServerSamlEndpoint(String realm) throws IllegalArgumentException, UriBuilderException {
return RealmsResource
.protocolUrl(UriBuilder.fromUri(getAuthServerRoot()))
.build(realm, SamlProtocol.LOGIN_PROTOCOL);
}