下面列出了怎么用javax.ws.rs.core.UriBuilder的API类实例代码及写法,或者点击链接到github查看源代码。
private void setupServer(Application application) {
ResourceConfig rc = ResourceConfig.forApplication(application);
Properties serverProperties = readProperties();
int port = Integer.parseInt(serverProperties.getProperty(PORT_PROPERTY));
URI serverUri = UriBuilder.fromPath(ROOT_RESOURCE_PATH).scheme("http").host("localhost").port(port).build();
final HttpServer grizzlyServer = GrizzlyHttpServerFactory.createHttpServer(serverUri, rc);
try {
grizzlyServer.start();
} catch (IOException e) {
e.printStackTrace();
}
server = grizzlyServer;
}
/**
* List all entries in the OLAT repository
*
* @response.representation.200.qname {http://www.example.com}repositoryEntryVO
* @response.representation.200.mediaType text/plain, text/html, application/xml, application/json
* @response.representation.200.doc List all entries in the repository
* @response.representation.200.example {@link org.olat.connectors.rest.support.vo.Examples#SAMPLE_REPOENTRYVOes}
* @param uriInfo
* The URI information
* @param httpRequest
* The HTTP request
* @return
*/
@GET
@Produces({ MediaType.TEXT_HTML, MediaType.TEXT_PLAIN })
public Response getEntriesText(@Context final UriInfo uriInfo, @Context final HttpServletRequest httpRequest) {
try {
// list of courses open for everybody
final Roles roles = getRoles(httpRequest);
final List<String> types = new ArrayList<String>();
final List<RepositoryEntry> coursRepos = RepositoryServiceImpl.getInstance().genericANDQueryWithRolesRestriction("*", "*", "*", types, roles, null);
final StringBuilder sb = new StringBuilder();
sb.append("Course List\n");
for (final RepositoryEntry repoE : coursRepos) {
final UriBuilder baseUriBuilder = uriInfo.getBaseUriBuilder();
final URI repoUri = baseUriBuilder.path(RepositoryEntriesResource.class).path(repoE.getKey().toString()).build();
sb.append("<a href=\"").append(repoUri).append(">").append(repoE.getDisplayname()).append("(").append(repoE.getKey()).append(")").append("</a>")
.append("\n");
}
return Response.ok(sb.toString()).build();
} catch (final Exception e) {
throw new WebApplicationException(e);
}
}
public static UserVO link(final UserVO userVO, final UriInfo uriInfo) {
if (uriInfo != null) {
final UriBuilder baseUriBuilder = uriInfo.getBaseUriBuilder();
final URI getUri = baseUriBuilder.path("users").path(userVO.getKey().toString()).build();
userVO.getLink().add(new LinkVO("self", getUri.toString(), ""));
userVO.getLink().add(new LinkVO("edit", getUri.toString(), ""));
userVO.getLink().add(new LinkVO("delete", getUri.toString(), ""));
final URI groupUri = baseUriBuilder.path("users").path(userVO.getKey().toString()).path("groups").build();
userVO.getLink().add(new LinkVO("self", groupUri.toString(), "Groups"));
final URI portraitUri = baseUriBuilder.path("users").path(userVO.getKey().toString()).path("portrait").build();
userVO.getLink().add(new LinkVO("self", portraitUri.toString(), "Portrait"));
}
return userVO;
}
@Test
public void accessTokenRequestCodeChallengeMethodMismatchPkceEnforced() throws Exception {
try {
setPkceActivationSettings("test-app", OAuth2Constants.PKCE_METHOD_S256);
String codeVerifier = "12345678e01234567890g2345678h012a4567j90123"; // 43
String codeChallenge = generateS256CodeChallenge(codeVerifier);
oauth.codeChallenge(codeChallenge);
oauth.codeChallengeMethod(OAuth2Constants.PKCE_METHOD_PLAIN);
UriBuilder b = UriBuilder.fromUri(oauth.getLoginFormUrl());
driver.navigate().to(b.build().toURL());
OAuthClient.AuthorizationEndpointResponse errorResponse = new OAuthClient.AuthorizationEndpointResponse(oauth);
Assert.assertTrue(errorResponse.isRedirected());
Assert.assertEquals(errorResponse.getError(), OAuthErrorException.INVALID_REQUEST);
Assert.assertEquals(errorResponse.getErrorDescription(), "Invalid parameter: code challenge method is not configured one");
events.expectLogin().error(Errors.INVALID_REQUEST).user((String) null).session((String) null).clearDetails().assertEvent();
} finally {
setPkceActivationSettings("test-app", null);
}
}
@Test
public void reportsSuccess() throws Exception {
final URI uri = UriBuilder.fromUri("http://localhost")
.port(APP.getAdminPort())
.path("healthcheck")
.build();
final WebTarget target = ClientBuilder.newClient().target(uri);
final Map<String, Map<String, Object>> result = target.request().get(Map.class);
final String healthCheckName = "cassandra.minimal-cluster";
assertThat(result).containsKey(healthCheckName);
Map<String, Object> cassandraStatus = result.get(healthCheckName);
assertThat(cassandraStatus).containsEntry("healthy", true);
}
@Override
public UriBuilder replaceQueryParam(String name, Object... values) {
checkSsp();
if (queryParams == null) {
queryParams = EmoUriComponent.decodeQuery(query.toString(), false);
query.setLength(0);
}
name = encode(name, EmoUriComponent.Type.QUERY_PARAM);
queryParams.remove(name);
if (values == null) {
return this;
}
for (Object value : values) {
if (value == null) {
throw new IllegalArgumentException("One or more of query value parameters are null");
}
queryParams.add(name, encode(value.toString(), EmoUriComponent.Type.QUERY_PARAM));
}
return this;
}
@org.junit.Test
public void testOIDCLoginForConfidentialClientWithRoles() throws Exception {
final UriBuilder authorizationUrl = oidcEndpointBuilder("/idp/authorize")
.queryParam("client_id", confidentialClientId)
.queryParam("response_type", "code")
.queryParam("scope", "openid")
.queryParam("claims", "roles");
// Login to the OIDC authorization endpoint + get the authorization code
final String authorizationCode = loginAndGetAuthorizationCode(authorizationUrl, "alice", "ecila");
// Now use the code to get an IdToken
final Map<String, Object> json =
getTokenJson(authorizationCode, confidentialClientId, confidentialClientSecret);
// Check the IdToken
validateIdToken(getIdToken(json), confidentialClientId, "User");
}
/**
* Creates a virtual network link from the JSON input stream.
*
* @param networkId network identifier
* @param stream virtual link JSON stream
* @return status of the request - CREATED if the JSON is correct,
* BAD_REQUEST if the JSON is invalid
* @onos.rsModel VirtualLink
*/
@POST
@Path("{networkId}/links")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createVirtualLink(@PathParam("networkId") long networkId,
InputStream stream) {
try {
ObjectNode jsonTree = readTreeFromStream(mapper(), stream);
JsonNode specifiedNetworkId = jsonTree.get("networkId");
if (specifiedNetworkId == null || specifiedNetworkId.asLong() != (networkId)) {
throw new IllegalArgumentException(INVALID_FIELD + "networkId");
}
final VirtualLink vlinkReq = codec(VirtualLink.class).decode(jsonTree, this);
vnetAdminService.createVirtualLink(vlinkReq.networkId(),
vlinkReq.src(), vlinkReq.dst());
UriBuilder locationBuilder = uriInfo.getBaseUriBuilder()
.path("vnets").path(specifiedNetworkId.asText())
.path("links");
return Response
.created(locationBuilder.build())
.build();
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
@Override
public void run() {
int maxRetry = 3;
while(maxRetry > 0) {
try {
client.setReadTimeout(30000);
client.setConnectTimeout(30000);
URI uri = UriBuilder.fromUri(url).build();
WebResource service = client.resource(uri);
responseBody = service.accept(MediaType.TEXT_PLAIN).get(String.class);
responseCode = "200";
logger.info("Successfully called service for " + url);
break;
} catch(Exception e) {
responseCode = "500";
responseBody = e.getMessage();
logger.error("Error occurred while contacting service " + url + " Msg :" + e.getMessage(), e);
maxRetry--;
}
}
}
/**
* Build a {@link URI} for the given page. Takes the absolute path from the given {@link UriInfo} and appends page and size
* query parameters from the given {@link Page}.
*
* @param creator a bytecode creator to be used for code generation
* @param uriInfo a {@link UriInfo} to be used for the absolute path extraction
* @param page a {@link Page} to be used for getting page number and size
* @return a page {@link URI}
*/
private static ResultHandle getPageUri(BytecodeCreator creator, ResultHandle uriInfo, ResultHandle page) {
ResultHandle uriBuilder = creator.invokeInterfaceMethod(
ofMethod(UriInfo.class, "getAbsolutePathBuilder", UriBuilder.class), uriInfo);
// Add page query parameter
ResultHandle index = creator.readInstanceField(FieldDescriptor.of(Page.class, "index", int.class), page);
creator.invokeVirtualMethod(
ofMethod(UriBuilder.class, "queryParam", UriBuilder.class, String.class, Object[].class),
uriBuilder, creator.load("page"), creator.marshalAsArray(Object.class, index));
// Add size query parameter
ResultHandle size = creator.readInstanceField(FieldDescriptor.of(Page.class, "size", int.class), page);
creator.invokeVirtualMethod(
ofMethod(UriBuilder.class, "queryParam", UriBuilder.class, String.class, Object[].class),
uriBuilder, creator.load("size"), creator.marshalAsArray(Object.class, size));
return creator.invokeVirtualMethod(
ofMethod(UriBuilder.class, "build", URI.class, Object[].class), uriBuilder, creator.newArray(Object.class, 0));
}
public ResourceOptionsDto availableOperations(UriInfo context) {
UriBuilder baseUriBuilder = context.getBaseUriBuilder()
.path(relativeRootResourcePath)
.path(FilterRestService.PATH);
ResourceOptionsDto resourceOptionsDto = new ResourceOptionsDto();
// GET /
URI baseUri = baseUriBuilder.build();
resourceOptionsDto.addReflexiveLink(baseUri, HttpMethod.GET, "list");
// GET /count
URI countUri = baseUriBuilder.clone().path("/count").build();
resourceOptionsDto.addReflexiveLink(countUri, HttpMethod.GET, "count");
// POST /create
if (isAuthorized(CREATE)) {
URI createUri = baseUriBuilder.clone().path("/create").build();
resourceOptionsDto.addReflexiveLink(createUri, HttpMethod.POST, "create");
}
return resourceOptionsDto;
}
public HttpResponse uploadFileForHttpResponse(Long petId, String additionalMetadata, File file) throws IOException {
// verify the required parameter 'petId' is set
if (petId == null) {
throw new IllegalArgumentException("Missing the required parameter 'petId' when calling uploadFile");
}
// create a map of path variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("petId", petId);
UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/pet/{petId}/uploadImage");
String localVarUrl = uriBuilder.buildFromMap(uriVariables).toString();
GenericUrl genericUrl = new GenericUrl(localVarUrl);
HttpContent content = new EmptyContent();
return apiClient.getHttpRequestFactory().buildRequest(HttpMethods.POST, genericUrl, content).execute();
}
@Override
public Response sendError(AuthenticationSessionModel authSession, Error error) {
try {
ClientModel client = authSession.getClient();
if ("true".equals(authSession.getClientNote(SAML_IDP_INITIATED_LOGIN))) {
if (error == Error.CANCELLED_BY_USER) {
UriBuilder builder = RealmsResource.protocolUrl(uriInfo).path(SamlService.class, "idpInitiatedSSO");
Map<String, String> params = new HashMap<>();
params.put("realm", realm.getName());
params.put("protocol", LOGIN_PROTOCOL);
params.put("client", client.getAttribute(SAML_IDP_INITIATED_SSO_URL_NAME));
URI redirect = builder.buildFromMap(params);
return Response.status(302).location(redirect).build();
} else {
return ErrorPage.error(session, authSession, Response.Status.BAD_REQUEST, translateErrorToIdpInitiatedErrorMessage(error));
}
} else {
return samlErrorMessage(
authSession, new SamlClient(client), isPostBinding(authSession),
authSession.getRedirectUri(), translateErrorToSAMLStatus(error), authSession.getClientNote(GeneralConstants.RELAY_STATE)
);
}
} finally {
new AuthenticationSessionManager(session).removeAuthenticationSession(realm, authSession, true);
}
}
/**
* Constructor.
* @param uriInfo UriInfo
* @param baseLevelsAbove 何階層上のパスをルートとするか
* @param add 追加パス情報
*/
public DcUriInfo(final UriInfo uriInfo, final int baseLevelsAbove, final String add) {
this.core = uriInfo;
String reqUrl = uriInfo.getRequestUri().toASCIIString();
if (reqUrl.endsWith("/")) {
reqUrl = reqUrl.substring(0, reqUrl.length() - 1);
}
String[] urlSplitted = reqUrl.split("/");
urlSplitted = (String[]) ArrayUtils.subarray(urlSplitted, 0, urlSplitted.length - baseLevelsAbove);
reqUrl = StringUtils.join(urlSplitted, "/") + "/";
if (add != null && add.length() != 0) {
reqUrl = reqUrl + add + "/";
}
this.baseUriBuilder = UriBuilder.fromUri(reqUrl);
}
@Test
public void test() {
URI streamResourceURI = UriBuilder.fromPath("//localhost:" + serverConfig.getPort() + "/ping")
.scheme(getURLScheme()).build();
Response response = client.target(streamResourceURI).request().buildGet().invoke();
assertEquals(200, response.getStatus());
}
@Path("start")
@POST
public Response start(@Context Sse sse) {
final UserEvent process = new UserEvent(sse);
POOL.put(process.getId(), process);
executor.submit(process);
final URI uri = UriBuilder.fromResource(ServerSentService.class).path("register/{id}").build(process.getId());
return Response.created(uri).build();
}
@POST
@Consumes("application/json")
public Response create(EventCategoryDTO dto)
{
EventCategory entity = dto.fromDTO(null, em);
em.persist(entity);
return Response.created(UriBuilder.fromResource(EventCategoryEndpoint.class).path(String.valueOf(entity.getId())).build()).build();
}
private String getAbsoluteTargetAddress(Message m) {
if (accessTokenServiceAddress == null) {
return new UriInfoImpl(m).getAbsolutePath().toString();
}
if (!accessTokenServiceAddress.startsWith("http")) {
String httpBasePath = (String)m.get("http.base.path");
return UriBuilder.fromUri(httpBasePath)
.path(accessTokenServiceAddress)
.build()
.toString();
}
return accessTokenServiceAddress;
}
public HttpResponse getTimeEntryForHttpResponse(String accessToken, String xeroTenantId, UUID projectId, UUID timeEntryId) throws IOException {
// verify the required parameter 'xeroTenantId' is set
if (xeroTenantId == null) {
throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling getTimeEntry");
}// verify the required parameter 'projectId' is set
if (projectId == null) {
throw new IllegalArgumentException("Missing the required parameter 'projectId' when calling getTimeEntry");
}// verify the required parameter 'timeEntryId' is set
if (timeEntryId == null) {
throw new IllegalArgumentException("Missing the required parameter 'timeEntryId' when calling getTimeEntry");
}
if (accessToken == null) {
throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling getTimeEntry");
}
HttpHeaders headers = new HttpHeaders();
headers.set("Xero-Tenant-Id", xeroTenantId);
headers.setAccept("application/json");
headers.setUserAgent(this.getUserAgent());
// create a map of path variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("projectId", projectId);
uriVariables.put("timeEntryId", timeEntryId);
UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/projects/{projectId}/time/{timeEntryId}");
String url = uriBuilder.buildFromMap(uriVariables).toString();
GenericUrl genericUrl = new GenericUrl(url);
if (logger.isDebugEnabled()) {
logger.debug("GET " + genericUrl.toString());
}
HttpContent content = null;
Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
HttpTransport transport = apiClient.getHttpTransport();
HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
return requestFactory.buildRequest(HttpMethods.GET, genericUrl, content).setHeaders(headers)
.setConnectTimeout(apiClient.getConnectionTimeout())
.setReadTimeout(apiClient.getReadTimeout()).execute();
}
@Override
public URI getActionUrl(String code) {
UriBuilder uriBuilder = LoginActionsService.loginActionsBaseUrl(getUriInfo())
.path(AuthenticationProcessor.this.flowPath)
.queryParam(LoginActionsService.SESSION_CODE, code)
.queryParam(Constants.EXECUTION, getExecution().getId())
.queryParam(Constants.CLIENT_ID, getAuthenticationSession().getClient().getClientId())
.queryParam(Constants.TAB_ID, getAuthenticationSession().getTabId());
if (getUriInfo().getQueryParameters().containsKey(LoginActionsService.AUTH_SESSION_ID)) {
uriBuilder.queryParam(LoginActionsService.AUTH_SESSION_ID, getAuthenticationSession().getParentSession().getId());
}
return uriBuilder
.build(getRealm().getName());
}
@Override
public UriBuilder userInfo(String ui) {
checkSsp();
this.userInfo = (ui != null)
? encode(ui, EmoUriComponent.Type.USER_INFO) : null;
return this;
}
private Response doDeploy(ModelRef modelRef, Model model){
boolean success;
Model oldModel = this.modelRegistry.get(modelRef);
if(oldModel != null){
success = this.modelRegistry.replace(modelRef, oldModel, model);
} else
{
success = this.modelRegistry.put(modelRef, model);
} // End if
if(!success){
logger.error("Concurrent modification");
throw new InternalServerErrorException();
}
ModelResponse entity = createModelResponse(modelRef.getId(), model, true);
if(oldModel != null){
return (Response.ok().entity(entity)).build();
} else
{
UriBuilder uriBuilder = (this.uriInfo.getBaseUriBuilder()).path(ModelResource.class).path(modelRef.getId());
URI uri = uriBuilder.build();
return (Response.created(uri).entity(entity)).build();
}
}
public HttpResponse getAssetTypesForHttpResponse(String accessToken, String xeroTenantId) throws IOException {
// verify the required parameter 'xeroTenantId' is set
if (xeroTenantId == null) {
throw new IllegalArgumentException("Missing the required parameter 'xeroTenantId' when calling getAssetTypes");
}
if (accessToken == null) {
throw new IllegalArgumentException("Missing the required parameter 'accessToken' when calling getAssetTypes");
}
HttpHeaders headers = new HttpHeaders();
headers.set("Xero-Tenant-Id", xeroTenantId);
headers.setAccept("application/json");
headers.setUserAgent(this.getUserAgent());
UriBuilder uriBuilder = UriBuilder.fromUri(apiClient.getBasePath() + "/AssetTypes");
String url = uriBuilder.build().toString();
GenericUrl genericUrl = new GenericUrl(url);
if (logger.isDebugEnabled()) {
logger.debug("GET " + genericUrl.toString());
}
HttpContent content = null;
Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accessToken);
HttpTransport transport = apiClient.getHttpTransport();
HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
return requestFactory.buildRequest(HttpMethods.GET, genericUrl, content).setHeaders(headers)
.setConnectTimeout(apiClient.getConnectionTimeout())
.setReadTimeout(apiClient.getReadTimeout()).execute();
}
private void setupMocks(String uri) throws URISyntaxException {
requestURI = new java.net.URI(uri);
MultivaluedMap map = new MultivaluedMapImpl();
uriInfo = mock(UriInfo.class);
when(uriInfo.getRequestUri()).thenReturn(requestURI);
when(uriInfo.getQueryParameters()).thenReturn(map);
when(uriInfo.getBaseUriBuilder()).thenAnswer(new Answer<UriBuilder>() {
@Override
public UriBuilder answer(InvocationOnMock invocation) throws Throwable {
return new UriBuilderImpl().path("base");
}
});
}
private URI buildUrI(String host, int port, String path, String appId, String appToken,
String nonce, String timestamp) throws Exception {
String signature = getSignature(appId, appToken, nonce, timestamp);
String urlStr = "http://" + host + ":" + port;
URI uri = UriBuilder.fromUri(urlStr)
.path(path)
.queryParam("app_id", appId)
.queryParam("nonce", nonce)
.queryParam("timestamp", timestamp)
.queryParam("signature", signature)
.build();
return uri;
}
@Override
public Response addRole(UriInfo ui, Role role) {
if (role.getEntitlements() != null && !role.getEntitlements().isEmpty()) {
LOG.warn("Role resource contains sub resource 'entitlements'");
throw new WebApplicationException(Status.BAD_REQUEST);
}
Role createdRole = roleDAO.addRole(role);
UriBuilder uriBuilder = UriBuilder.fromUri(ui.getRequestUri());
uriBuilder.path("{index}");
URI location = uriBuilder.build(createdRole.getName());
LOG.debug("Role '" + role.getName() + "' added");
return Response.created(location).entity(role).build();
}
public static LinkWithMetadata asLink(Task<?> t, UriBuilder ub) {
if (t==null) return null;
MutableMap<String,Object> data = new MutableMap<String,Object>();
data.put("id", t.getId());
if (t.getDisplayName()!=null) data.put("taskName", t.getDisplayName());
Entity entity = BrooklynTaskTags.getContextEntity(t);
if (entity!=null) {
data.put("entityId", entity.getId());
if (entity.getDisplayName()!=null) data.put("entityDisplayName", entity.getDisplayName());
}
URI taskUri = serviceUriBuilder(ub, ActivityApi.class, "get").build(t.getId());
return new LinkWithMetadata(taskUri.toString(), data);
}
private void updateIdentityProviderWithJwksUrl() {
IdentityProviderRepresentation idpRep = getIdentityProvider();
OIDCIdentityProviderConfigRep cfg = new OIDCIdentityProviderConfigRep(idpRep);
cfg.setValidateSignature(true);
cfg.setUseJwksUrl(true);
UriBuilder b = OIDCLoginProtocolService.certsUrl(UriBuilder.fromUri(OAuthClient.AUTH_SERVER_ROOT));
String jwksUrl = b.build(bc.providerRealmName()).toString();
cfg.setJwksUrl(jwksUrl);
updateIdentityProvider(idpRep);
}
@Test
public void testBuildWithNonEncodedSubstitutionValue8() {
UriBuilder ub = UriBuilder.fromPath("/");
URI uri = ub.replaceQueryParam("a", "%").build();
assertEquals("/?a=%25", uri.toString());
uri = ub.replaceQueryParam("a2", "{token}").build("{}");
assertEquals("/?a=%25&a2=%7B%7D", uri.toString());
}
@Override
public URI getRefreshExecutionUrl() {
UriBuilder uriBuilder = LoginActionsService.loginActionsBaseUrl(getUriInfo())
.path(AuthenticationProcessor.this.flowPath)
.queryParam(Constants.EXECUTION, getExecution().getId())
.queryParam(Constants.CLIENT_ID, getAuthenticationSession().getClient().getClientId())
.queryParam(Constants.TAB_ID, getAuthenticationSession().getTabId());
if (getUriInfo().getQueryParameters().containsKey(LoginActionsService.AUTH_SESSION_ID)) {
uriBuilder.queryParam(LoginActionsService.AUTH_SESSION_ID, getAuthenticationSession().getParentSession().getId());
}
return uriBuilder
.build(getRealm().getName());
}