@GET @Path("{toItemID}/{itemID : .+}") @Produces({MediaType.TEXT_PLAIN, "text/csv", MediaType.APPLICATION_JSON}) public List<Double> get( @PathParam("toItemID") String toItemID, @PathParam("itemID") List<PathSegment> pathSegmentsList) throws OryxServingException { ALSServingModel alsServingModel = getALSServingModel(); float[] toItemFeatures = alsServingModel.getItemVector(toItemID); checkExists(toItemFeatures != null, toItemID); double toItemFeaturesNorm = VectorMath.norm(toItemFeatures); return pathSegmentsList.stream().map(item -> { float[] itemFeatures = alsServingModel.getItemVector(item.getPath()); if (itemFeatures == null) { return 0.0; } else { double value = VectorMath.cosineSimilarity(itemFeatures, toItemFeatures, toItemFeaturesNorm); Preconditions.checkState(!(Double.isInfinite(value) || Double.isNaN(value)), "Bad similarity"); return value; } }).collect(Collectors.toList()); }
@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 PersoniumCoreException.Server.READ_DELETE_ONLY; }
/** * ReadDeleteOnlyモード時に$batchに対するPOSTメソッドが実行された場合はPersoniumCoreExceptionが発生しないこと. * @throws Exception . */ @Test public void ReadDeleteOnlyモード時に$batchに対するPOSTメソッドが実行された場合はPersoniumCoreExceptionが発生しないこと() throws Exception { PowerMockito.spy(ReadDeleteModeLockManager.class); PowerMockito.when(ReadDeleteModeLockManager.class, "isReadDeleteOnlyMode").thenReturn(true); try { List<PathSegment> pathSegment = getPathSegmentList(new String[] {"cell", "box", "col", "odata", "$batch" }); PersoniumReadDeleteModeManager.checkReadDeleteOnlyMode(HttpMethod.POST, pathSegment); // 1階層パスを深くしても例外が発生しないことを確認 pathSegment = getPathSegmentList(new String[] {"cell", "box", "col", "col", "odata", "$batch" }); PersoniumReadDeleteModeManager.checkReadDeleteOnlyMode(HttpMethod.POST, pathSegment); } catch (PersoniumCoreException e) { fail(e.getMessage()); } }
/** * Extracts the list of dimensions from the url dimension path segments and "show" matrix params and generates a map * of dimension to dimension fields which needs to be annotated on the response. * <p> * If no "show" matrix param has been set, it returns the default dimension fields configured for the dimension. * * @param apiDimensionPathSegments Path segments for the dimensions * @param dimensionDictionary Dimension dictionary to look the dimensions up in * * @return A map of dimension to requested dimension fields */ protected LinkedHashMap<Dimension, LinkedHashSet<DimensionField>> generateDimensionFields( @NotNull List<PathSegment> apiDimensionPathSegments, @NotNull DimensionDictionary dimensionDictionary ) { try (TimedPhase timer = RequestLog.startTiming("GeneratingDimensionFields")) { return apiDimensionPathSegments.stream() .filter(pathSegment -> !pathSegment.getPath().isEmpty()) .collect(Collectors.toMap( pathSegment -> dimensionDictionary.findByApiName(pathSegment.getPath()), pathSegment -> bindShowClause(pathSegment, dimensionDictionary), (LinkedHashSet<DimensionField> e, LinkedHashSet<DimensionField> i) -> { e.addAll(i); return e; }, LinkedHashMap::new )); } }
/** * This method will get the path segments and the interval (if it is part of the request) from the apiRequest and * create a content-disposition header value with a proposed filename in the following format. * <p> * If the path segments are ["data", "datasource", "granularity", "dim1"] and the query params have interval * {"dateTime": "a/b"}, then the result would be "attachment; filename=data-datasource-granularity-dim1_a_b.csv". * For a dimension query without a "dateTime" query param and path segments * ["dimensions", "datasource", "dim1"], then the result would be * "attachment; filename=dimensions-datasource-dim1.csv". * * @param uriInfo UriInfo of the request * * @return A content disposition header telling the browser the name of the CSV file to be downloaded */ public static String getCsvContentDispositionValue(UriInfo uriInfo) { String uriPath = uriInfo.getPathSegments().stream() .map(PathSegment::getPath) .collect(Collectors.joining("-")); String interval = uriInfo.getQueryParameters().getFirst("dateTime"); if (interval == null) { interval = ""; } else { // Chrome treats ',' as duplicate header so replace it with '__' to make chrome happy. interval = "_" + interval.replace("/", "_").replace(",", "__"); } return "attachment; filename=" + uriPath + interval + ".csv"; }
@Test @Parameters({ // "fe944b98-18b1-11e5-9d51-1f35c61c7a23, fe944b98-18b1-11e5-9d51-1f35c61c7a23, true", // same UUIDs "fe944b98-18b1-11e5-9d51-1f35c61c7a23, 27947b26-18b2-11e5-be1c-c7fb9bd13f9b, false" // different UUIDs }) public void testValidationOfUUIDinURIShouldMatchUUIDinPrototype(String uriId, String protoId, boolean valid) { final PathSegment mockedPathSegment = mock(PathSegment.class); when(mockedPathSegment.getPath()).thenReturn(protoId); final UriInfo mockedUriInfo = mock(UriInfo.class); when(mockedUriInfo.getPathSegments()).thenReturn(Lists.newArrayList(mockedPathSegment)); final ResourcePrototype mockedPrototype = mock(ResourcePrototype.class); when(mockedPrototype.getId()).thenReturn(new UUIDParam(uriId)); assertThat(new Validator(mockedUriInfo).isValid(mockedPrototype, null), is(valid)); verify(mockedUriInfo, atLeastOnce()).getPathSegments(); verify(mockedPrototype).getId(); }
/** * Construct the path for the file. This is the entire path excluding the app * id. * * @param segments * @return */ private String constructPathFromSegments(List<PathSegment> segments) { // Now construct up the path from the segments. // We are NOT going to include the app id. Therefore if you upload a file // with a path of appid/myDir/myFile.html, the path will be stored as // myDir/myFile.html. This is so that when you get the filename on the // manifest, it won't matter what is the root directory of your app on your // device. Otherwise you might have to strip the first path segment or do // something similar. StringBuilder sb = new StringBuilder(); int i = 0; for (PathSegment segment : segments) { sb.append(segment.getPath()); if (i < segments.size() - 1) { sb.append(BasicConsts.FORWARDSLASH); } i++; } String wholePath = sb.toString(); return wholePath; }
/** * Construct the path for the file. This is the entire path excluding the app * id. * * @param segments * @return */ private String constructPathFromSegments(List<PathSegment> segments) { // Now construct up the path from the segments. // We are NOT going to include the app id. Therefore if you upload a file // with a path of /myDir/myFile.html, the path will be stored as // myDir/myFile.html. This is so that when you get the filename on the // manifest, it won't matter what is the root directory of your app on your // device. Otherwise you might have to strip the first path segment or do // something similar. StringBuilder sb = new StringBuilder(); int i = 0; for (PathSegment segment : segments) { sb.append(segment.getPath()); if (i < segments.size() - 1) { sb.append(BasicConsts.FORWARDSLASH); } i++; } String wholePath = sb.toString(); return wholePath; }
@GET @Path("/criteria/{search_criteria}") @Produces({MediaType.APPLICATION_JSON}) public SearchResult getErrorsByCriteria(@PathParam("search_criteria") PathSegment argCriteria, @QueryParam("fromDate") String fromDate, @QueryParam("toDate") String toDate, @QueryParam("sortField") String sortField, @QueryParam("sortAsc") Boolean sortAsc, @QueryParam("start") Integer start, @QueryParam("results") Integer maxResults) { SearchCriteria criteria = getCriteria(argCriteria); String sortBy = StringUtils.isBlank(sortField) ? "timestamp" : sortField; Boolean sortAscending = sortAsc==null ? true : sortAsc; LOGGER.info("search criteria: {} sortBy: {} asc=: {}", criteria, sortBy, sortAscending); return client.get().searchMessagesByCriteria(criteria, getDate(fromDate), getDate(toDate), sortBy, sortAscending, start, maxResults); }
private SearchCriteria getCriteria(PathSegment searchCriteria) { SearchCriteria criteria = new SearchCriteria(); List<Criterion> criteriaList = new ArrayList<Criterion>(); MultivaluedMap<String, String> map = searchCriteria.getMatrixParameters(); for (Map.Entry<String, List<String>> entry : map.entrySet()) { for (String value : entry.getValue()) { Criterion criterion = new Criterion(); if (!SearchField.isPreDefined(entry.getKey())) { criterion.setCustomKey(entry.getKey()); criterion.setValue(value); } else { getPredefinedCriteria(entry, value, criterion); } criteriaList.add(criterion); } } criteria.setCriteria(criteriaList.toArray(new Criterion[0])); LOGGER.debug("criteria: {}", criteria.toString()); return criteria; }
/** * Get a named directory entry from a workflow run. * * @param run * The run whose working directory is to be used as the root of * the search. * @param d * The path segments describing what to look up. * @return The directory entry whose name is equal to the last part of the * path; an empty path will retrieve the working directory handle * itself. * @throws NoDirectoryEntryException * If there is no such entry. * @throws FilesystemAccessException * If the directory isn't specified or isn't readable. */ public DirectoryEntry getDirEntry(TavernaRun run, List<PathSegment> d) throws FilesystemAccessException, NoDirectoryEntryException { Directory dir = run.getWorkingDirectory(); if (d == null || d.isEmpty()) return dir; DirectoryEntry found = dir; boolean mustBeLast = false; // Must be nested loops; avoids problems with %-encoded "/" chars for (PathSegment segment : d) for (String bit : segment.getPath().split("/")) { if (mustBeLast) throw new FilesystemAccessException(TYPE_ERROR); found = getEntryFromDir(bit, dir); dir = null; if (found instanceof Directory) { dir = (Directory) found; mustBeLast = false; } else mustBeLast = true; } return found; }
/** * Make a description of the given input port. * * @param inputPort */ public InDesc(Input inputPort, UriInfo ui) { super(true); name = inputPort.getName(); if (inputPort.getFile() != null) { assignment = new InDesc.File(); assignment.contents = inputPort.getFile(); } else { assignment = new InDesc.Value(); assignment.contents = inputPort.getValue(); } // .../runs/{id}/input/input/{name} -> // .../runs/{id}/input/expected#{name} UriBuilder ub = ui.getBaseUriBuilder(); List<PathSegment> segments = ui.getPathSegments(); for (PathSegment s : segments.subList(0, segments.size() - 2)) ub.segment(s.getPath()); ub.fragment(name); descriptorRef = new Uri(ub).ref; }
@Override public JobValidationData validateFromUrl(String sessionId, String url, PathSegment pathSegment) throws NotConnectedRestException { File tmpWorkflowFile = null; try { checkAccess(sessionId); String jobXml = downloadWorkflowContent(sessionId, url); tmpWorkflowFile = File.createTempFile("job", "d"); IOUtils.write(jobXml, new FileOutputStream(tmpWorkflowFile)); Map<String, String> jobVariables = workflowVariablesTransformer.getWorkflowVariablesFromPathSegment(pathSegment); return jobValidator.validateJobDescriptor(tmpWorkflowFile, jobVariables); } catch (JobCreationRestException | IOException e) { JobValidationData validation = new JobValidationData(); validation.setErrorMessage("Error while reading workflow at url: " + url); validation.setStackTrace(getStackTrace(e)); return validation; } finally { FileUtils.deleteQuietly(tmpWorkflowFile); } }
/** * Returns the metadata of the catalog entry. * * @response.representation.200.qname {http://www.example.com}catalogEntryVO * @response.representation.200.mediaType application/xml, application/json * @response.representation.200.doc The catalog entry * @response.representation.200.example {@link org.olat.connectors.rest.catalog.Examples#SAMPLE_CATALOGENTRYVO} * @response.representation.401.doc The path could not be resolved to a valid catalog entry * @param path * The path * @param uriInfo * The URI informations * @return The response */ @GET @Path("{path:.*}") @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Response getCatalogEntry(@PathParam("path") final List<PathSegment> path, @Context final UriInfo uriInfo) { if (path.isEmpty()) { return getRoots(); } final Long ceKey = getCatalogEntryKeyFromPath(path); if (ceKey == null) { return Response.serverError().status(Status.NOT_ACCEPTABLE).build(); } final CatalogEntry ce = catalogService.loadCatalogEntry(ceKey); if (ce == null) { return Response.serverError().status(Status.NOT_FOUND).build(); } final CatalogEntryVO vo = link(get(ce), uriInfo); return Response.ok(vo).build(); }
@GET @Path("test/{dataSet}") @Produces({"text/html"}) public String testPathParam(@DefaultValue("SevenScannersRun-2015-05-11.json.gz") @PathParam("dataSet") PathSegment dataSet) { StringBuilder response = new StringBuilder("<html><title>ReplayService.replayData</title><body><h1>dataSet="); response.append(dataSet.getPath()); response.append("</h1>"); response.append("<h2>Path Parameters</h2><ul>"); for (String key : dataSet.getMatrixParameters().keySet()) { response.append("<li>"); response.append(key); response.append("="); response.append(dataSet.getMatrixParameters().getFirst(key)); response.append("</li>"); } response.append("</ul>"); return response.toString(); }
private String getPath(UriInfo uriInfo) { MultivaluedMap<String, String> pathParameters = uriInfo.getPathParameters(true); final Map<String, String> valuesToParams = pathParameters.entrySet().stream() .map(entry -> entry.getValue().stream() .collect(toMap(Function.identity(), value -> "{" + entry.getKey() + "}"))) .reduce(new HashMap<>(), (m1, m2) -> { m1.putAll(m2); return m1; }); return uriInfo.getPathSegments(true).stream() .map(PathSegment::getPath) .map(path -> { if (valuesToParams.containsKey(path)) { return valuesToParams.get(path); } return path; }) .collect(joining("/")); }
/** * This method calculates the string literal of the requested path of the * resource. * * @param path list of path segment (eg: <_system,governance,sample.xml> * @return concatenated string representation of the path variable */ protected String getResourcePath(List<PathSegment> path) { if (path == null || !(path.size() > 0)) { return null; } String resourcePath = ""; StringBuilder strBuilder = new StringBuilder(); strBuilder.append(resourcePath); for (PathSegment pathSegment : path) { strBuilder.append("/"); strBuilder.append(pathSegment); } resourcePath = strBuilder.toString(); if (resourcePath.length() == 0) { resourcePath = "/"; } return resourcePath; }
/** * Method createParentLink. Create link to the parent resource * * @param baseObject * JSONObject * @param rel * String * @param uriInfo * UriInfo * @return JSONObject * @throws JSONException */ public static JSONObject createParentLink(JSONObject baseObject, String rel, UriInfo uriInfo) throws JSONException { // TODO : use URIBuilder for path composition // remove last segment and recreate the path String href = ""; List<PathSegment> listSegments = uriInfo.getPathSegments(); listSegments.remove(listSegments.size() - 1); for (PathSegment xp : listSegments) { href += xp.getPath() + "/"; } href = href.substring(0, href.length() - 1); // add the link return createLink(baseObject, href, rel); }
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( "{itemName}/_settings") @Produces({MediaType.APPLICATION_JSON,"application/javascript"}) @RequireApplicationAccess @JSONP public ApiResponse executeGetOnIndex( @Context UriInfo ui, @PathParam("itemName") PathSegment itemName, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { if(logger.isTraceEnabled()){ logger.trace( "CollectionResource.executeGetOnSettings" ); } addItemToServiceContext( ui, itemName ); ApiResponse response = createApiResponse(); response.setAction( "get" ); response.setApplication( services.getApplication() ); response.setParams( ui.getQueryParameters() ); executeServiceGetRequestForSettings( ui,response,ServiceAction.GET,null ); return response; }
@POST @Path("{itemName}/_reindex") @Produces({ MediaType.APPLICATION_JSON,"application/javascript"}) @RequireSystemAccess @JSONP public ApiResponse executePostForReindexing( @Context UriInfo ui, String body, @PathParam("itemName") PathSegment itemName, @QueryParam("callback") @DefaultValue("callback") String callback ) throws Exception { addItemToServiceContext( ui, itemName ); IndexResource indexResource = new IndexResource(injector); return indexResource.rebuildIndexesPost( services.getApplicationId().toString(),itemName.getPath(),false,callback ); }
@Override @Path("{entityId: [A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}}") public AbstractContextResource addIdParameter(@Context UriInfo ui, @PathParam("entityId") PathSegment entityId) throws Exception { if (logger.isTraceEnabled()) { logger.trace("NotifiersResource.addIdParameter"); } UUID itemId = UUID.fromString(entityId.getPath()); addParameter(getServiceParameters(), itemId); addMatrixParams(getServiceParameters(), ui, entityId); return getSubResource(NotifierResource.class).init( Identifier.fromUUID(itemId)); }
@Override @Path(RootResource.ENTITY_ID_PATH) public AbstractContextResource addIdParameter( @Context UriInfo ui, @PathParam("entityId") PathSegment entityId ) throws Exception { if(logger.isTraceEnabled()){ logger.trace( "ServiceResource.addIdParameter" ); } UUID itemId = UUID.fromString( entityId.getPath() ); addParameter( getServiceParameters(), itemId ); addMatrixParams( getServiceParameters(), ui, entityId ); return getSubResource( UserResource.class ).init( Identifier.fromUUID( itemId ) ); }
@Override @Path("{itemName}") public AbstractContextResource addNameParameter( @Context UriInfo ui, @PathParam("itemName") PathSegment itemName ) throws Exception { // check for user extension String resourceClass = USER_EXTENSION_RESOURCE_PREFIX + StringUtils.capitalize( itemName.getPath() ) + "Resource"; AbstractUserExtensionResource extensionResource = null; try { @SuppressWarnings("unchecked") Class<AbstractUserExtensionResource> extensionCls = ( Class<AbstractUserExtensionResource> ) Class.forName( resourceClass ); extensionResource = getSubResource( extensionCls ); } catch ( Exception e ) { // intentionally empty } if ( extensionResource != null ) { return extensionResource; } return super.addNameParameter( ui, itemName ); }
private boolean shouldSkipMutationToEnableSearch( List<PathSegment> segments, String queryParameters) { boolean skipMutation = false; if (segments.size() == NUM_SEGMENTS_IN_ONE_PART_REQUEST) { String[] queries = queryParameters != null ? queryParameters .split("&") : new String[0]; for (String query : queries) { if (!query .matches("(limit|offset|expandDepth|includeFields|excludeFields|sortBy|sortOrder|optionalFields|views|includeCustom|selector)=.+")) { final int baseResourceIndex = 1; } } } return skipMutation; }
/** * 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 List<String> cleanPath(List<PathSegment> segs) { if (segs == null || segs.isEmpty()) { return Collections.<String> emptyList(); } List<String> paths = new ArrayList<String>(); // first one is version, system calls (un-versioned) have been handled elsewhere for (int i = 1; i < segs.size(); ++i) { if (segs.get(i) != null) { String path = segs.get(i).getPath(); if (path != null && !path.isEmpty()) { paths.add(path); } } } return paths; }
/** * 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; }
private boolean isSystemCall(List<PathSegment> pathSegments) { /** * assuming all resource endpoints are versioned */ if (pathSegments == null || pathSegments.size() == 0) { // /api/rest/ root access? return false; } // all data model resources are versioned if (isVersionString(pathSegments.get(0).getPath())) { return false; } return true; }
public void translate(ContainerRequest request) { String uri = request.getPath(); List<PathSegment> segments = request.getPathSegments(); String version = PathConstants.V1; if (!segments.isEmpty()) { version = segments.get(0).getPath(); } for (Map.Entry<String, URITranslation> entry : uriTranslationMap.entrySet()) { String key = entry.getKey(); if (uri.contains(key)) { String newPath = uriTranslationMap.get(key).translate(request.getPath()); if (!newPath.equals(uri)) { request.setUris(request.getBaseUri(), request.getBaseUriBuilder().path(version).path(newPath).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()); } } } } }
private ContainerRequest updateContainerRequest(ContainerRequest containerRequest, List<PathSegment> segments, String newVersion) { //add the new version UriBuilder builder = containerRequest.getBaseUriBuilder().path(newVersion); //add the rest of the request for (PathSegment segment : segments) { builder.path(segment.getPath()); } if (containerRequest.getRequestUri().getQuery() != null && !containerRequest.getRequestUri().getQuery().isEmpty()) { builder.replaceQuery(containerRequest.getRequestUri().getQuery()); } containerRequest.getProperties().put(REQUESTED_PATH, containerRequest.getPath()); containerRequest.setUris(containerRequest.getBaseUri(), builder.build()); return containerRequest; }
@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)); }
@Test public void testGetResourceVersion() { List<PathSegment> segments = getPathSegmentList("v1/students"); MutatedContainer mutated = mock(MutatedContainer.class); when(mutated.getPath()).thenReturn("/studentSectionAssociations/1234/students"); assertEquals("Should match", "v1", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.0/students"); assertEquals("Should match", "v1.0", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.1/students"); assertEquals("Should match", "v1.1", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.3/students"); assertEquals("Should match", "v1.3", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.1/students"); when(mutated.getPath()).thenReturn(null); assertEquals("Should match", "v1.1", endpointMutator.getResourceVersion(segments, mutated)); }
@Test public void testGetResourceVersionForPublicResources() { List<PathSegment> segments = getPathSegmentList("v1/assessments"); MutatedContainer mutated = mock(MutatedContainer.class); when(mutated.getPath()).thenReturn("/search/assessments"); assertEquals("Should match", "v1", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.0/assessments"); assertEquals("Should match", "v1.1", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.1/assessments"); assertEquals("Should match", "v1.1", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.3/assessments"); assertEquals("Should match", "v1.3", endpointMutator.getResourceVersion(segments, mutated)); }
@Test(expected = NotFoundException.class) public void testNoPathSegments() throws URISyntaxException { // Test /api/rest with no additional path segments. SLIPrincipal principle = mock(SLIPrincipal.class); ClientToken clientToken = mock(ClientToken.class); when(clientToken.getClientId()).thenReturn("theAppId"); OAuth2Authentication auth = mock(OAuth2Authentication.class); when(auth.getPrincipal()).thenReturn(principle); when(auth.getClientAuthentication()).thenReturn(clientToken); ContainerRequest request = mock(ContainerRequest.class); List<PathSegment> segments = Collections.emptyList(); when(request.getPathSegments()).thenReturn(segments); when(request.getMethod()).thenReturn("GET"); when(request.getRequestUri()).thenReturn(new URI("http://not.valid.inbloom.org")); endpointMutator.mutateURI(auth, request); }
@Test public void testDeterministicRewrite() { // no user entity needed when(principal.getEntity()).thenReturn(null); Map<String, Object> body = new HashMap<String, Object>(); body.put("staffUniqueStateId", "teacher"); Entity teacher = repo.create("teacher", body, "staff"); PathSegment v1 = Mockito.mock(PathSegment.class); when(v1.getPath()).thenReturn("/staff"); Assert.assertEquals("Endpoint should be rewritten to /teachers/id", createMutatedContainer("/teachers/" + teacher.getEntityId(), "staffUniqueStateId=teacher"), mutator.mutate(Arrays.asList(v1), "staffUniqueStateId=teacher", principal, null)); body.put("staffUniqueStateId", "staff"); teacher = repo.create("staff", body, "staff"); v1 = Mockito.mock(PathSegment.class); when(v1.getPath()).thenReturn("/staff"); Assert.assertEquals("Endpoint should be rewritten to /staff/id", createMutatedContainer("/staff/" + teacher.getEntityId(), "staffUniqueStateId=staff"), mutator.mutate(Arrays.asList(v1), "staffUniqueStateId=staff", principal, null)); }
@Test // One part requests to the 'educationOrganizations' endpoint by a user with the APP_AUTHORIZE right // from an admin application should NOT be mutated public void testMutateSkipForAppAuthRightAdminApp() { SecurityUtil.setUserContext(SecurityUtil.UserContext.STAFF_CONTEXT); Map<String, Object> body = new HashMap<String, Object>(); body.put("staffUniqueStateId", "staff"); teacher = repo.create("staff", body, "staff"); PathSegment v1 = Mockito.mock(PathSegment.class); when(v1.getPath()).thenReturn("/v1"); PathSegment edorgs = Mockito.mock(PathSegment.class); when(edorgs.getPath()).thenReturn("/educationOrganizations"); when(principal.getEntity()).thenReturn(staff); Map<String, Collection<GrantedAuthority>> edOrgRights = generateSimpleEdOrgRightsMap("theEdOrg", Right.APP_AUTHORIZE); when(principal.getEdOrgRights()).thenReturn(edOrgRights); MutatedContainer mutated = mutator.mutate(Arrays.asList(v1,edorgs), null, principal, ADMIN_APP_ID); System.out.println("The path is : " + mutated.getPath() + ", qparams : " + mutated.getQueryParameters()); Assert.assertEquals("Endpoint should NOT have been rewritten to " + mutated.getPath(), createMutatedContainer(null, ""), mutated); }