下面列出了怎么用javax.ws.rs.core.PathSegment的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Mutates the API call (not to a base entity) to a more-specific (and
* generally more constrained) URI based on the user's role.
*
* @param segments
* List of Path Segments representing request URI.
* @param queryParameters
* String containing query parameters.
* @param user
* User requesting resource.
* @return MutatedContainer representing {mutated path (if necessary),
* mutated parameters (if necessary)}, where path or parameters will
* be null if they didn't need to be rewritten.
*/
private MutatedContainer mutateUriBasedOnRole(List<PathSegment> segments,
String queryParameters, Entity user)
throws IllegalArgumentException {
MutatedContainer mutatedPathAndParameters = null;
if (mutateToTeacher()) {
mutatedPathAndParameters = mutateTeacherRequest(segments,
queryParameters, user);
} else if (mutateToStaff()) {
mutatedPathAndParameters = mutateStaffRequest(segments,
queryParameters, user);
} else if (isStudent(user) || isParent(user)) {
mutatedPathAndParameters = mutateStudentParentRequest(
stringifyPathSegments(segments), queryParameters, user);
}
return mutatedPathAndParameters;
}
private void addItemToServiceContext( UriInfo ui, PathSegment itemName ) throws Exception {
// The below is duplicated because it could change in the future
// and is probably not all needed but not determined yet.
if ( itemName.getPath().startsWith( "{" ) ) {
Query query = Query.fromJsonString( itemName.getPath() );
if ( query != null ) {
ServiceParameter.addParameter( getServiceParameters(), query );
}
}
else {
ServiceParameter.addParameter( getServiceParameters(), itemName.getPath() );
}
addMatrixParams( getServiceParameters(), ui, itemName );
}
@GET
@Path("{userID}/{itemID : .+}")
@Produces({MediaType.TEXT_PLAIN, "text/csv", MediaType.APPLICATION_JSON})
public List<Double> get(@PathParam("userID") String userID,
@PathParam("itemID") List<PathSegment> pathSegmentsList)
throws OryxServingException {
ALSServingModel model = getALSServingModel();
float[] userFeatures = model.getUserVector(userID);
checkExists(userFeatures != null, userID);
return pathSegmentsList.stream().map(pathSegment -> {
float[] itemFeatures = model.getItemVector(pathSegment.getPath());
if (itemFeatures == null) {
return 0.0;
} else {
double value = VectorMath.dot(itemFeatures, userFeatures);
Preconditions.checkState(!(Double.isInfinite(value) || Double.isNaN(value)), "Bad estimate");
return value;
}
}).collect(Collectors.toList());
}
/**
* PCSの動作モードがReadDeleteOnlyモードの場合は、参照系リクエストのみ許可する.
* 許可されていない場合は例外を発生させてExceptionMapperにて処理する.
* @param method リクエストメソッド
* @param pathSegment パスセグメント
*/
public static void checkReadDeleteOnlyMode(String method, List<PathSegment> pathSegment) {
// ReadDeleteOnlyモードでなければ処理を許可する
if (!ReadDeleteModeLockManager.isReadDeleteOnlyMode()) {
return;
}
// 認証処理はPOSTメソッドだが書き込みは行わないので例外として許可する
if (isAuthPath(pathSegment)) {
return;
}
// $batchはPOSTメソッドだが参照と削除のリクエストも実行可能であるため
// $batch内部で書き込み系処理をエラーとする
if (isBatchPath(pathSegment)) {
return;
}
// ReadDeleteOnlyモード時に、許可メソッドであれば処理を許可する
if (ACCEPT_METHODS.contains(method)) {
return;
}
throw DcCoreException.Server.READ_DELETE_ONLY;
}
@GET
@Path("/{name}/{path: .*}")
@Produces(MediaType.APPLICATION_JSON)
public void get(
@PathParam("name") String name,
@PathParam("path") List<PathSegment> path,
@Suspended AsyncResponse response) {
getPrimitive(name).thenCompose(tree -> tree.get(getDocumentPath(path))).whenComplete((result, error) -> {
if (error == null) {
response.resume(Response.ok(new VersionedResult(result)).build());
} else {
LOGGER.warn("{}", error);
response.resume(Response.serverError().build());
}
});
}
/**
* Throws a QueryParseException if the end user tried to query an endpoint that does
* not support querying.
*
*
* @param uriInfo
*/
protected void validatePublicResourceQuery(final UriInfo uriInfo) {
List<PathSegment> uriPathSegments = uriInfo.getPathSegments();
if (uriPathSegments != null) {
// if of the form "v1/foo"
if (uriPathSegments.size() == 2) {
String endpoint = uriPathSegments.get(1).getPath();
// if that endpoint does not allow querying
if (this.resourceEndPoint.getQueryingDisallowedEndPoints().contains(endpoint)) {
ApiQuery apiQuery = new ApiQuery(uriInfo);
// if the user tried to execute a query/filter
if (apiQuery.getCriteria().size() > 0) {
throw new QueryParseException("Querying not allowed", apiQuery.toString());
}
}
}
}
}
public static String fromPathSegment(PathSegment ps) {
if (PathSegmentImpl.class.isAssignableFrom(ps.getClass())) {
return ((PathSegmentImpl)ps).getOriginalPath();
}
StringBuilder sb = new StringBuilder();
sb.append(ps.getPath());
for (Map.Entry<String, List<String>> entry : ps.getMatrixParameters().entrySet()) {
for (String value : entry.getValue()) {
sb.append(';').append(entry.getKey());
if (value != null) {
sb.append('=').append(value);
}
}
}
return sb.toString();
}
/**
* white list student accessible URL. Can't do it in validateUserHasContextToRequestedEntity
* because we must also block some url that only has 2 segment, i.e.
* disciplineActions/disciplineIncidents
*
* @param request
* @return if url is accessible to students principals
*/
public boolean isUrlBlocked(ContainerRequest request) {
List<PathSegment> segs = cleanEmptySegments(request.getPathSegments());
if (isSystemCall(segs)) {
// do not block system calls
return false;
}
if (SecurityUtil.isStudent()) {
return !studentAccessValidator.isAllowed(request);
} else if (SecurityUtil.isParent()) {
return !parentAccessValidator.isAllowed(request);
}
return false;
}
@Test
public void testGetResourceVersionForSearch() {
List<PathSegment> segments = getPathSegmentList("v1/search");
MutatedContainer mutated = mock(MutatedContainer.class);
when(mutated.getPath()).thenReturn("/search");
assertEquals("Should match", "v1", endpointMutator.getResourceVersion(segments, mutated));
segments = getPathSegmentList("v1.0/search");
assertEquals("Should match", "v1.0", endpointMutator.getResourceVersion(segments, mutated));
segments = getPathSegmentList("v1.1/search");
assertEquals("Should match", "v1.1", endpointMutator.getResourceVersion(segments, mutated));
segments = getPathSegmentList("v1.3/search");
assertEquals("Should match", "v1.3", endpointMutator.getResourceVersion(segments, mutated));
}
/**
* Delete settings for a collection.
*/
@DELETE
@Path( "{itemName}/_settings" )
@Produces({ MediaType.APPLICATION_JSON,"application/javascript"})
@RequireApplicationAccess
@JSONP
public ApiResponse executeDeleteOnSettingsWithCollectionName(
@Context UriInfo ui,
@PathParam("itemName") PathSegment itemName,
String body,
@QueryParam("callback") @DefaultValue("callback") String callback )
throws Exception {
if(logger.isTraceEnabled()){
logger.trace( "CollectionResource.executeDeleteOnSettingsWithCollectionName" );
}
addItemToServiceContext( ui, itemName );
ApiResponse response = createApiResponse();
response.setAction( "delete" );
response.setApplication( services.getApplication() );
response.setParams( ui.getQueryParameters() );
emf.getEntityManager( services.getApplicationId() ).deleteCollectionSettings( itemName.getPath().toLowerCase() );
return response;
}
/**
* ReadDeleteOnlyモードではない状態でPROPPATCHメソッドが実行された場合はDcCoreExceptionが発生しないこと.
* @throws Exception .
*/
@Test
public void ReadDeleteOnlyモードではない状態でPROPPATCHメソッドが実行された場合はDcCoreExceptionが発生しないこと() throws Exception {
PowerMockito.spy(ReadDeleteModeLockManager.class);
PowerMockito.when(ReadDeleteModeLockManager.class, "isReadDeleteOnlyMode").thenReturn(false);
List<PathSegment> pathSegment = getPathSegmentList(new String[] {"cell", "box", "odata", "entity" });
try {
DcReadDeleteModeManager.checkReadDeleteOnlyMode(
com.fujitsu.dc.common.utils.DcCoreUtils.HttpMethod.PROPPATCH, pathSegment);
} catch (DcCoreException e) {
fail(e.getMessage());
}
}
/**
* ReadDeleteOnlyモード時にMKCOLメソッドが実行された場合はDcCoreExceptionが発生すること.
* @throws Exception .
*/
@Test(expected = DcCoreException.class)
public void ReadDeleteOnlyモード時にMKCOLメソッドが実行された場合は503が返却されること() throws Exception {
PowerMockito.spy(ReadDeleteModeLockManager.class);
PowerMockito.when(ReadDeleteModeLockManager.class, "isReadDeleteOnlyMode").thenReturn(true);
List<PathSegment> pathSegment = getPathSegmentList(new String[] {"cell", "box", "odata", "entity" });
DcReadDeleteModeManager.checkReadDeleteOnlyMode(com.fujitsu.dc.common.utils.DcCoreUtils.HttpMethod.MKCOL,
pathSegment);
}
/**
* From a list of segments, use all but the last item, joined in a String.
* @param segments the path segments
* @return the path
*/
public static String getAllButLastSegment(final List<PathSegment> segments) {
if (segments.isEmpty()) {
return "";
}
return segments.subList(0, segments.size() - 1).stream().map(PathSegment::getPath)
.collect(joining("/"));
}
private PathSegment asPathSegment(final String segment) {
return new PathSegment() {
@Override
public String getPath() {
return segment;
}
@Override
public MultivaluedMap<String, String> getMatrixParameters() {
return new MultivaluedHashMap<>();
}
};
}
private List<PathSegment> getPathSegmentList(String path) {
String[] paths = path.split("/");
List<PathSegment> segments = new ArrayList<PathSegment>();
for (String part : paths) {
PathSegment segment = mock(PathSegment.class);
when(segment.getPath()).thenReturn(part);
segments.add(segment);
}
return segments;
}
/**
* ReadDeleteOnlyモード時にDELETEメソッドが実行された場合はDcCoreExceptionが発生しないこと.
* @throws Exception .
*/
@Test
public void ReadDeleteOnlyモード時にDELETEメソッドが実行された場合はDcCoreExceptionが発生しないこと() throws Exception {
PowerMockito.spy(ReadDeleteModeLockManager.class);
PowerMockito.when(ReadDeleteModeLockManager.class, "isReadDeleteOnlyMode").thenReturn(true);
List<PathSegment> pathSegment = getPathSegmentList(new String[] {"cell", "box", "odata", "entity" });
try {
DcReadDeleteModeManager.checkReadDeleteOnlyMode(HttpMethod.DELETE, pathSegment);
} catch (DcCoreException e) {
fail(e.getMessage());
}
}
@Test
public void testBulkExtractWithMajorApiVersion() throws URISyntaxException {
UriBuilder builder = mock(UriBuilder.class);
when(builder.path(anyString())).thenReturn(builder);
String latestApiVersion = versionFilter.getLatestApiVersion("v1.1");
String latestApiMajorVersion = latestApiVersion.split("\\.")[0];
URI uri = new URI("http://api/rest/" + latestApiMajorVersion + "/bulk");
PathSegment segment1 = mock(PathSegment.class);
when(segment1.getPath()).thenReturn(latestApiMajorVersion);
PathSegment segment2 = mock(PathSegment.class);
when(segment2.getPath()).thenReturn("bulk");
List<PathSegment> segments = new ArrayList<PathSegment>();
segments.add(segment1);
segments.add(segment2);
when(containerRequest.getPathSegments()).thenReturn(segments);
when(containerRequest.getBaseUriBuilder()).thenReturn(builder);
when(containerRequest.getRequestUri()).thenReturn(uri);
when(containerRequest.getPath()).thenReturn("http://api/rest/" + latestApiMajorVersion + "/bulk");
when(containerRequest.getProperties()).thenReturn(new HashMap<String, Object>());
ContainerRequest request = versionFilter.filter(containerRequest);
verify(containerRequest).setUris((URI) any(), (URI) any());
verify(builder).build();
verify(builder, times(1)).path(latestApiVersion);
verify(builder, times(1)).path("bulk");
assertEquals("Should match", "http://api/rest/" + latestApiMajorVersion + "/bulk",
request.getProperties().get(REQUESTED_PATH));
}
@GET
@Path("/matrix/{make}/{model}/{year}")
@Produces("text/plain")
public String getFromMatrixParam(@PathParam("make") String make,
@PathParam("model") PathSegment car,
@MatrixParam("color") Color color,
@PathParam("year") String year)
{
return "A " + color + " " + year + " " + make + " " + car.getPath();
}
/**
* ReadDeleteOnlyモード時にPUTメソッドが実行された場合はDcCoreExceptionが発生すること.
* @throws Exception .
*/
@Test(expected = DcCoreException.class)
public void ReadDeleteOnlyモード時にPUTメソッドが実行された場合は503が返却されること() throws Exception {
PowerMockito.spy(ReadDeleteModeLockManager.class);
PowerMockito.when(ReadDeleteModeLockManager.class, "isReadDeleteOnlyMode").thenReturn(true);
List<PathSegment> pathSegment = getPathSegmentList(new String[] {"cell", "box", "odata", "entity" });
DcReadDeleteModeManager.checkReadDeleteOnlyMode(HttpMethod.PUT, pathSegment);
}
@GET
@Path("/uriinfo/{make}/{model}/{year}")
@Produces("text/plain")
public String getFromUriInfo(@Context UriInfo info)
{
String make = info.getPathParameters().getFirst("make");
String year = info.getPathParameters().getFirst("year");
PathSegment model = info.getPathSegments().get(3);
String color = model.getMatrixParameters().getFirst("color");
return "A " + color + " " + year + " " + make + " " + model.getPath();
}
@Override
public boolean shouldSkip(HttpServletRequest request) {
List<PathSegment> pathSegments = UriComponent.parsePathSegments(request.getRequestURI(), false);
int notEmptyPathSergments = 0;
for (PathSegment pathSegment : pathSegments) {
if (pathSegment.getPath() != null && !pathSegment.getPath().isEmpty()) {
notEmptyPathSergments++;
}
}
return notEmptyPathSergments == segmentNumber;
}
@Before
public void setUp() throws Exception {
studentValidator = Mockito.mock(StudentAccessValidator.class);
request = Mockito.mock(ContainerRequest.class);
MockitoAnnotations.initMocks(this);
when(request.getMethod()).thenReturn(ResourceMethod.GET.toString());
when(request.getQueryParameters()).thenReturn(new MultivaluedMapImpl());
when(request.getPathSegments()).thenAnswer(new Answer<List<PathSegment>>() {
@Override
public List<PathSegment> answer(InvocationOnMock invocation) throws Throwable {
return buildSegment();
}
});
}
/**
* ReadDeleteOnlyモード時にPOSTメソッドが実行された場合はDcCoreExceptionが発生すること.
* @throws Exception .
*/
@Test(expected = DcCoreException.class)
public void ReadDeleteOnlyモード時にPOSTメソッドが実行された場合は503が返却されること() throws Exception {
PowerMockito.spy(ReadDeleteModeLockManager.class);
PowerMockito.when(ReadDeleteModeLockManager.class, "isReadDeleteOnlyMode").thenReturn(true);
List<PathSegment> pathSegment = getPathSegmentList(new String[] {"cell", "box", "odata", "entity" });
DcReadDeleteModeManager.checkReadDeleteOnlyMode(HttpMethod.POST, pathSegment);
}
/**
* Submits a job to the scheduler
* @param sessionId a valid session id
* @param multipart a form with the job file as form data
* @return the <code>jobid</code> of the newly created job
*/
@POST
@Path("{path:submit}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
JobIdData submit(@HeaderParam("sessionid") String sessionId, @PathParam("path") PathSegment pathSegment,
MultipartFormDataInput multipart) throws JobCreationRestException, NotConnectedRestException,
PermissionRestException, SubmissionClosedRestException, IOException;
/**
* ReadDeleteOnlyモードではない状態でPUTメソッドが実行された場合はDcCoreExceptionが発生しないこと.
* @throws Exception .
*/
@Test
public void ReadDeleteOnlyモードではない状態でPUTメソッドが実行された場合はDcCoreExceptionが発生しないこと() throws Exception {
PowerMockito.spy(ReadDeleteModeLockManager.class);
PowerMockito.when(ReadDeleteModeLockManager.class, "isReadDeleteOnlyMode").thenReturn(false);
List<PathSegment> pathSegment = getPathSegmentList(new String[] {"cell", "box", "odata", "entity" });
try {
DcReadDeleteModeManager.checkReadDeleteOnlyMode(HttpMethod.PUT, pathSegment);
} catch (DcCoreException e) {
fail(e.getMessage());
}
}
@Override
@Path("{itemName}")
public AbstractContextResource addNameParameter( @Context UriInfo ui, @PathParam("itemName") PathSegment itemName)
throws Exception {
if(logger.isTraceEnabled()){
logger.trace( "ServiceResource.addNameParameter" );
logger.trace( "Current segment is {}", itemName.getPath() );
}
if ( itemName.getPath().startsWith( "{" ) ) {
Query query = Query.fromJsonString( itemName.getPath() );
if ( query != null ) {
addParameter( getServiceParameters(), query );
}
addMatrixParams( getServiceParameters(), ui, itemName );
return getSubResource( ServiceResource.class );
}
addParameter( getServiceParameters(), itemName.getPath() );
addMatrixParams( getServiceParameters(), ui, itemName );
String forceString = ui.getQueryParameters().getFirst("force");
Identifier id;
if (forceString != null && "email".equals(forceString.toLowerCase())) {
id = Identifier.fromEmail(itemName.getPath().toLowerCase());
} else if (forceString != null && "name".equals(forceString.toLowerCase())) {
id = Identifier.fromName(itemName.getPath().toLowerCase());
} else {
id = Identifier.from(itemName.getPath());
}
if ( id == null ) {
throw new IllegalArgumentException( "Not a valid user identifier: " + itemName.getPath() );
}
return getSubResource( UserResource.class ).init( id );
}
@Test
public void testNonRewrite() {
PathSegment segment1 = mock(PathSegment.class);
when(segment1.getPath()).thenReturn("v5");
PathSegment segment2 = mock(PathSegment.class);
when(segment2.getPath()).thenReturn("students");
List<PathSegment> segments = Arrays.asList(segment1, segment2);
when(containerRequest.getPathSegments()).thenReturn(segments);
when(containerRequest.getProperties()).thenReturn(new HashMap<String, Object>());
ContainerRequest request = versionFilter.filter(containerRequest);
verify(containerRequest, never()).setUris((URI) any(), (URI) any());
assertNull("Should be null", request.getProperties().get(REQUESTED_PATH));
}
@Test
public void parsesPathSegmentsFromString() {
PathSegment pathSegment = PathSegmentImpl.fromString(pathSegmentString, decode);
MultivaluedMap<String, String> matrixParameters = pathSegment.getMatrixParameters();
assertEquals(expectedPath, pathSegment.getPath());
assertEquals(expectedMatrixParameters.size() / 2, matrixParameters.size());
for (int i = 0; i < expectedMatrixParameters.size(); i += 2) {
String expectedMatrixParameterName = expectedMatrixParameters.get(i);
String expectedMatrixParameterValue = expectedMatrixParameters.get(i + 1);
assertEquals(expectedMatrixParameterValue, matrixParameters.getFirst(expectedMatrixParameterName));
}
}
static List<Pair<String, Double>> parsePathSegments(List<PathSegment> pathSegments) {
return pathSegments.stream().map(segment -> {
String s = segment.getPath();
int offset = s.indexOf('=');
return offset < 0 ?
new Pair<>(s, 1.0) :
new Pair<>(s.substring(0, offset), Double.parseDouble(s.substring(offset + 1)));
}).collect(Collectors.toList());
}
@Path( RootResource.ENTITY_ID_PATH + "/errors" )
public FileErrorsResource getIncludes( @Context UriInfo ui, @PathParam( "entityId" ) PathSegment entityId )
throws Exception {
final UUID fileImportId = UUID.fromString( entityId.getPath() );
return getSubResource( FileErrorsResource.class ).init( application, importId,fileImportId );
}