From 82e63e687dd6e0ea206d816cb942908ddaf3e738 Mon Sep 17 00:00:00 2001 From: Arturo Bernal Date: Sat, 7 Nov 2026 13:45:30 +0100 Subject: [PATCH 1/9] JSPWIKI-1310 Add the search of the REST API version 1, described by an OpenAPI file that a test compares with the answers --- .../api/exceptions/ProviderException.java | 11 + jspwiki-main/pom.xml | 6 + .../org/apache/wiki/rest/ApiV1Servlet.java | 181 +++++++++ .../wiki/search/LuceneSearchProvider.java | 2 +- .../org/apache/wiki/rest/openapi.yaml | 128 +++++++ .../apache/wiki/rest/ApiV1ServletTest.java | 344 ++++++++++++++++++ jspwiki-war/src/main/webapp/WEB-INF/web.xml | 11 + pom.xml | 7 + 8 files changed, 689 insertions(+), 1 deletion(-) create mode 100644 jspwiki-main/src/main/java/org/apache/wiki/rest/ApiV1Servlet.java create mode 100644 jspwiki-main/src/main/resources/org/apache/wiki/rest/openapi.yaml create mode 100644 jspwiki-main/src/test/java/org/apache/wiki/rest/ApiV1ServletTest.java diff --git a/jspwiki-api/src/main/java/org/apache/wiki/api/exceptions/ProviderException.java b/jspwiki-api/src/main/java/org/apache/wiki/api/exceptions/ProviderException.java index 0fda596a5c..86cb06c900 100644 --- a/jspwiki-api/src/main/java/org/apache/wiki/api/exceptions/ProviderException.java +++ b/jspwiki-api/src/main/java/org/apache/wiki/api/exceptions/ProviderException.java @@ -37,4 +37,15 @@ public ProviderException( final String msg ) { super( msg ); } + /** + * Creates a ProviderException that tells what caused it. + * + * @param msg exception message. + * @param cause the exception that made the provider fail. + * @since 3.0.1 + */ + public ProviderException( final String msg, final Throwable cause ) { + super( msg, cause ); + } + } diff --git a/jspwiki-main/pom.xml b/jspwiki-main/pom.xml index 0e7da25e61..c41711a0ac 100644 --- a/jspwiki-main/pom.xml +++ b/jspwiki-main/pom.xml @@ -212,6 +212,12 @@ test + + org.yaml + snakeyaml + test + + org.hsqldb hsqldb diff --git a/jspwiki-main/src/main/java/org/apache/wiki/rest/ApiV1Servlet.java b/jspwiki-main/src/main/java/org/apache/wiki/rest/ApiV1Servlet.java new file mode 100644 index 0000000000..c3bd319c23 --- /dev/null +++ b/jspwiki-main/src/main/java/org/apache/wiki/rest/ApiV1Servlet.java @@ -0,0 +1,181 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ +package org.apache.wiki.rest; + +import com.google.gson.Gson; +import jakarta.servlet.ServletConfig; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.apache.commons.lang3.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.lucene.queryparser.classic.ParseException; +import org.apache.wiki.api.core.Context; +import org.apache.wiki.api.core.ContextEnum; +import org.apache.wiki.api.core.Engine; +import org.apache.wiki.api.core.Session; +import org.apache.wiki.api.exceptions.ProviderException; +import org.apache.wiki.api.search.SearchResult; +import org.apache.wiki.api.spi.Wiki; +import org.apache.wiki.auth.AuthorizationManager; +import org.apache.wiki.auth.permissions.PagePermission; +import org.apache.wiki.search.SearchManager; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +/** + * Version 1 of the REST API of the wiki, described by {@code openapi.yaml} in this package. It answers with JSON, also when it fails. + * A caller that is not allowed to read gets 401 if it is anonymous and 403 if it is logged in. + * + * @since 3.0.1 + */ +public class ApiV1Servlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + private static final Logger LOG = LogManager.getLogger( ApiV1Servlet.class ); + private static final Gson GSON = new Gson(); + + /** Number of entries returned when the request does not say how many it wants. */ + static final int DEFAULT_MAX = 20; + + private transient Engine engine; + + /** {@inheritDoc} */ + @Override + public void init( final ServletConfig config ) throws ServletException { + super.init( config ); + engine = Wiki.engine().find( config ); + } + + /** {@inheritDoc} */ + @Override + protected void doGet( final HttpServletRequest req, final HttpServletResponse resp ) throws IOException { + if( "/search".equals( req.getPathInfo() ) ) { + search( req, resp ); + } else { + error( resp, HttpServletResponse.SC_NOT_FOUND, "No such resource." ); + } + } + + private void search( final HttpServletRequest req, final HttpServletResponse resp ) throws IOException { + final Session session = Wiki.session().find( engine, req ); + if( !engine.getManager( AuthorizationManager.class ).checkPermission( session, PagePermission.VIEW ) ) { + denied( resp, session ); + return; + } + final String query = req.getParameter( "query" ); + if( StringUtils.isBlank( query ) ) { + error( resp, HttpServletResponse.SC_BAD_REQUEST, "The parameter query is required." ); + return; + } + final int max = max( req.getParameter( "max" ) ); + if( max < 1 ) { + error( resp, HttpServletResponse.SC_BAD_REQUEST, "The parameter max must be an integer greater than zero." ); + return; + } + + final Context context = Wiki.context().create( engine, req, ContextEnum.PAGE_VIEW.getRequestContext() ); + try { + final Collection< SearchResult > found = engine.getManager( SearchManager.class ).findPages( query, context ); + if( found == null ) { + // The Lucene provider logs a failure of its index, for instance before it is first built, and returns null + error( resp, HttpServletResponse.SC_SERVICE_UNAVAILABLE, "The search index is not available." ); + return; + } + final List< Hit > hits = new ArrayList<>(); + for( final SearchResult result : found ) { + if( hits.size() == max ) { + break; + } + hits.add( new Hit( result.getPage().getName(), result.getScore() ) ); + } + json( resp, HttpServletResponse.SC_OK, hits ); + } catch( final ProviderException e ) { + if( e.getCause() instanceof ParseException ) { + error( resp, HttpServletResponse.SC_BAD_REQUEST, "The parameter query is not a valid query." ); + } else { + LOG.error( "The search for the REST API failed", e ); + error( resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "The search failed." ); + } + } catch( final IOException e ) { + LOG.error( "The search for the REST API failed", e ); + error( resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "The search failed." ); + } + } + + /** Returns the value of the max parameter, the default when it is absent, and 0 when it is not a positive integer. */ + private static int max( final String value ) { + if( value == null ) { + return DEFAULT_MAX; + } + try { + return Math.max( 0, Integer.parseInt( value.trim() ) ); + } catch( final NumberFormatException e ) { + return 0; + } + } + + private static void denied( final HttpServletResponse resp, final Session session ) throws IOException { + if( session.isAuthenticated() ) { + error( resp, HttpServletResponse.SC_FORBIDDEN, "The permission to read is missing." ); + } else { + error( resp, HttpServletResponse.SC_UNAUTHORIZED, "Authentication is required." ); + } + } + + private static void error( final HttpServletResponse resp, final int status, final String message ) throws IOException { + json( resp, status, new Failure( status, message ) ); + } + + private static void json( final HttpServletResponse resp, final int status, final Object body ) throws IOException { + resp.setStatus( status ); + resp.setContentType( "application/json" ); + resp.setCharacterEncoding( StandardCharsets.UTF_8.name() ); + resp.getWriter().write( GSON.toJson( body ) ); + } + + /** An entry of the answer to a search. */ + private static final class Hit { + private final String page; + private final int score; + + Hit( final String page, final int score ) { + this.page = page; + this.score = score; + } + } + + /** The body of every answer that is not a success. */ + private static final class Failure { + private final int status; + private final String message; + + Failure( final int status, final String message ) { + this.status = status; + this.message = message; + } + } + +} diff --git a/jspwiki-main/src/main/java/org/apache/wiki/search/LuceneSearchProvider.java b/jspwiki-main/src/main/java/org/apache/wiki/search/LuceneSearchProvider.java index 45dfc9676b..ac69b8a3b9 100644 --- a/jspwiki-main/src/main/java/org/apache/wiki/search/LuceneSearchProvider.java +++ b/jspwiki-main/src/main/java/org/apache/wiki/search/LuceneSearchProvider.java @@ -526,7 +526,7 @@ public Collection< SearchResult > findPages( final String query, final int flags LOG.error( "Failed during lucene search", e ); } catch( final ParseException e ) { LOG.error( "Broken query; cannot parse query: {}", query, e ); - throw new ProviderException( "You have entered a query Lucene cannot process [" + query + "]: " + e.getMessage() ); + throw new ProviderException( "You have entered a query Lucene cannot process [" + query + "]: " + e.getMessage(), e ); } catch( final InvalidTokenOffsetsException e ) { LOG.error( "Tokens are incompatible with provided text ", e ); } diff --git a/jspwiki-main/src/main/resources/org/apache/wiki/rest/openapi.yaml b/jspwiki-main/src/main/resources/org/apache/wiki/rest/openapi.yaml new file mode 100644 index 0000000000..fc418fb642 --- /dev/null +++ b/jspwiki-main/src/main/resources/org/apache/wiki/rest/openapi.yaml @@ -0,0 +1,128 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# Description of the REST API of the wiki, JSPWIKI-1310. A test compares it with the answers of ApiV1Servlet. +openapi: 3.0.3 +info: + title: JSPWiki API + version: 1.0.0 + description: Search of the pages the caller may view. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: /api/v1 +security: + - sessionCookie: [] +paths: + /search: + get: + operationId: searchPages + summary: Search the pages the caller may view. + parameters: + - name: query + in: query + required: true + schema: + type: string + minLength: 1 + - $ref: '#/components/parameters/max' + responses: + '200': + description: Matching pages, best match first. Empty when nothing matches. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/SearchResult' + '400': + $ref: '#/components/responses/BadRequest' + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + '500': + $ref: '#/components/responses/InternalError' + '503': + $ref: '#/components/responses/Unavailable' +components: + securitySchemes: + sessionCookie: + type: apiKey + in: cookie + name: JSESSIONID + parameters: + max: + name: max + in: query + required: false + description: Maximum number of entries to return. + schema: + type: integer + minimum: 1 + default: 20 + schemas: + SearchResult: + type: object + required: [page, score] + properties: + page: + type: string + description: Name of the page. + score: + type: integer + description: Relevance of the page for the query. Higher is better. + Error: + type: object + required: [status, message] + properties: + status: + type: integer + message: + type: string + responses: + BadRequest: + description: A required parameter is missing or invalid. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + Unauthorized: + description: The caller is not authenticated and anonymous access is not allowed. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + Forbidden: + description: The caller is authenticated but lacks the permission. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + InternalError: + description: The request could not be served because of an error of the wiki. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + Unavailable: + description: The search index is not available, for instance right after the wiki has started. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' diff --git a/jspwiki-main/src/test/java/org/apache/wiki/rest/ApiV1ServletTest.java b/jspwiki-main/src/test/java/org/apache/wiki/rest/ApiV1ServletTest.java new file mode 100644 index 0000000000..c34652bd57 --- /dev/null +++ b/jspwiki-main/src/test/java/org/apache/wiki/rest/ApiV1ServletTest.java @@ -0,0 +1,344 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + */ +package org.apache.wiki.rest; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import jakarta.servlet.ServletConfig; +import jakarta.servlet.ServletContext; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.apache.wiki.HttpMockFactory; +import org.apache.wiki.TestEngine; +import org.apache.wiki.api.core.Session; +import org.apache.wiki.api.spi.Wiki; +import org.apache.wiki.auth.AuthenticationManager; +import org.apache.wiki.auth.AuthorizationManager; +import org.apache.wiki.auth.Users; +import org.apache.wiki.search.SearchManager; +import org.awaitility.Awaitility; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.Mockito; +import org.yaml.snakeyaml.Yaml; + +import java.io.InputStream; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +class ApiV1ServletTest { + + private static final Gson GSON = new Gson(); + private static final Map< String, Object > CONTRACT = contract(); + + private TestEngine engine; + + @AfterEach + void tearDown() { + if( engine != null ) { + engine.stop(); + } + } + + @Test + void searchAnswersWithTheContract() throws Exception { + startEngine( null ); + engine.saveText( "ApiSearchPage", "The dawn of the third age of mankind." ); + engine.saveText( "ApiSearchOther", "Another page about mankind." ); + + final Reply[] reply = new Reply[ 1 ]; + Awaitility.await( "both pages are indexed" ).until( () -> { + reply[ 0 ] = search( null, "query", "mankind" ); + return reply[ 0 ].json().getAsJsonArray().size() == 2; + } ); + + assertMatchesContract( "/search", reply[ 0 ] ); + Assertions.assertEquals( 200, reply[ 0 ].status ); + final JsonObject first = reply[ 0 ].json().getAsJsonArray().get( 0 ).getAsJsonObject(); + Assertions.assertTrue( first.get( "page" ).getAsString().startsWith( "ApiSearch" ) ); + } + + @Test + void searchWithoutMatchesAnswersWithAnEmptyList() throws Exception { + startEngine( null ); + + final Reply reply = search( null, "query", "nothingwillmatchthis" ); + + assertMatchesContract( "/search", reply ); + Assertions.assertEquals( 200, reply.status ); + Assertions.assertEquals( 0, reply.json().getAsJsonArray().size() ); + } + + @Test + void searchReturnsAtMostMaxEntries() throws Exception { + startEngine( null ); + engine.saveText( "ApiMaxOne", "common words here" ); + engine.saveText( "ApiMaxTwo", "common words there" ); + Awaitility.await( "both pages are indexed" ).until( () -> search( null, "query", "common" ).json().getAsJsonArray().size() == 2 ); + + final Reply reply = search( null, "query", "common", "max", "1" ); + + assertMatchesContract( "/search", reply ); + Assertions.assertEquals( 1, reply.json().getAsJsonArray().size() ); + } + + @Test + void searchWithoutQueryIsABadRequest() throws Exception { + startEngine( null ); + + final Reply reply = search( null ); + + assertMatchesContract( "/search", reply ); + Assertions.assertEquals( 400, reply.status ); + } + + @Test + void searchWithAQueryThatCannotBeParsedIsABadRequest() throws Exception { + startEngine( null ); + + final Reply reply = search( null, "query", "\"unbalanced" ); + + assertMatchesContract( "/search", reply ); + Assertions.assertEquals( 400, reply.status ); + } + + @Test + void searchWithAMaxThatIsNotAPositiveIntegerIsABadRequest() throws Exception { + startEngine( null ); + + for( final String max : new String[] { "0", "-3", "many", "" } ) { + final Reply reply = search( null, "query", "mankind", "max", max ); + + assertMatchesContract( "/search", reply ); + Assertions.assertEquals( 400, reply.status, "max=" + max ); + } + } + + @Test + void searchByAnAnonymousCallerWithoutPermissionIs401( @TempDir final Path dir ) throws Exception { + startEngine( policy( dir, "Authenticated" ) ); + + final Reply reply = search( null, "query", "mankind" ); + + assertMatchesContract( "/search", reply ); + Assertions.assertEquals( 401, reply.status ); + } + + @Test + void searchByALoggedInCallerWithoutPermissionIs403( @TempDir final Path dir ) throws Exception { + startEngine( policy( dir, "Admin" ) ); + final HttpServletRequest request = request( "query", "mankind" ); + final Session session = Wiki.session().find( engine, request ); + engine.getManager( AuthenticationManager.class ).login( session, request, Users.JANNE, Users.JANNE_PASS ); + Assertions.assertTrue( session.isAuthenticated() ); + + final Reply reply = call( request ); + + assertMatchesContract( "/search", reply ); + Assertions.assertEquals( 403, reply.status ); + } + + @Test + void searchBeforeTheIndexIsBuiltIs503() throws Exception { + startEngine( null, "600" ); + + final Reply reply = search( null, "query", "mankind" ); + + assertMatchesContract( "/search", reply ); + Assertions.assertEquals( 503, reply.status ); + } + + @Test + void anUnknownResourceIs404() throws Exception { + startEngine( null ); + final HttpServletRequest request = request(); + Mockito.doReturn( "/nothing" ).when( request ).getPathInfo(); + + final Reply reply = call( request ); + + Assertions.assertEquals( 404, reply.status ); + Assertions.assertEquals( 404, reply.json().getAsJsonObject().get( "status" ).getAsInt() ); + } + + @Test + void contractDeclaresTheParametersTheServletEnforces() { + final Map< String, Object > get = map( map( map( CONTRACT, "paths" ), "/search" ), "get" ); + final List< Object > parameters = list( get, "parameters" ); + + final Map< String, Object > query = map( parameters.get( 0 ), null ); + Assertions.assertEquals( "query", query.get( "name" ) ); + Assertions.assertEquals( Boolean.TRUE, query.get( "required" ) ); + + final Map< String, Object > max = resolve( parameters.get( 1 ) ); + Assertions.assertEquals( "max", max.get( "name" ) ); + Assertions.assertEquals( ApiV1Servlet.DEFAULT_MAX, map( max, "schema" ).get( "default" ) ); + Assertions.assertEquals( 1, map( max, "schema" ).get( "minimum" ) ); + } + + private void startEngine( final String policy ) { + startEngine( policy, "0" ); + } + + private void startEngine( final String policy, final String initialIndexDelay ) { + final Properties props = TestEngine.getTestProperties(); + props.setProperty( SearchManager.PROP_SEARCHPROVIDER, "LuceneSearchProvider" ); + props.setProperty( "jspwiki.lucene.indexdelay", "0" ); + props.setProperty( "jspwiki.lucene.initialdelay", initialIndexDelay ); + props.setProperty( "jspwiki.workDir", props.getProperty( "jspwiki.workDir" ) + System.currentTimeMillis() ); + props.setProperty( "jspwiki.fileSystemProvider.pageDir", props.getProperty( "jspwiki.fileSystemProvider.pageDir" ) + System.currentTimeMillis() ); + if( policy != null ) { + props.setProperty( AuthorizationManager.POLICY, policy ); + } + engine = TestEngine.build( props ); + } + + /** Writes a policy file that lets only the given role view the pages. */ + private static String policy( final Path dir, final String role ) throws Exception { + final Path file = dir.resolve( "api.policy" ); + Files.write( file, ( "grant principal org.apache.wiki.auth.authorize.Role \"" + role + "\" {\n" + + " permission org.apache.wiki.auth.permissions.PagePermission \"*:*\", \"view\";\n" + + "};\n" ).getBytes( StandardCharsets.UTF_8 ) ); + return file.toAbsolutePath().toString(); + } + + private HttpServletRequest request( final String... parameters ) { + final HttpServletRequest request = HttpMockFactory.createHttpRequest( "/JSPWiki", "/api/v1/search" ); + Mockito.doReturn( "GET" ).when( request ).getMethod(); + Mockito.doReturn( "/search" ).when( request ).getPathInfo(); + for( int i = 0; i < parameters.length; i += 2 ) { + Mockito.doReturn( parameters[ i + 1 ] ).when( request ).getParameter( parameters[ i ] ); + } + return request; + } + + private Reply search( final HttpServletRequest request, final String... parameters ) throws Exception { + return call( request != null ? request : request( parameters ) ); + } + + private Reply call( final HttpServletRequest request ) throws Exception { + // The context is a mock, so the engine that TestEngine stashed in it has to be handed over again + final ServletContext context = engine.getServletContext(); + Mockito.doReturn( engine ).when( context ).getAttribute( "org.apache.wiki.WikiEngine" ); + final ServletConfig config = Mockito.mock( ServletConfig.class ); + Mockito.doReturn( context ).when( config ).getServletContext(); + final ApiV1Servlet servlet = new ApiV1Servlet(); + servlet.init( config ); + + final Reply reply = new Reply(); + final HttpServletResponse response = Mockito.mock( HttpServletResponse.class ); + Mockito.doAnswer( invocation -> reply.status = invocation.getArgument( 0 ) ).when( response ).setStatus( Mockito.anyInt() ); + Mockito.doAnswer( invocation -> reply.contentType = invocation.getArgument( 0 ) ).when( response ).setContentType( Mockito.anyString() ); + Mockito.doReturn( new PrintWriter( reply.body ) ).when( response ).getWriter(); + servlet.service( request, response ); + return reply; + } + + /** Checks the status, the content type and the shape of the body against what the contract declares for the operation. */ + private static void assertMatchesContract( final String path, final Reply reply ) { + final Map< String, Object > responses = map( map( map( map( CONTRACT, "paths" ), path ), "get" ), "responses" ); + final Object declared = responses.get( String.valueOf( reply.status ) ); + Assertions.assertNotNull( declared, "the contract has no response " + reply.status + " for " + path ); + + final Map< String, Object > content = map( resolve( declared ), "content" ); + Assertions.assertTrue( content.containsKey( reply.contentType ), "content type " + reply.contentType + " is not declared" ); + assertMatchesSchema( resolve( map( content, reply.contentType ).get( "schema" ) ), reply.json(), "body" ); + } + + private static void assertMatchesSchema( final Map< String, Object > schema, final JsonElement value, final String where ) { + switch( String.valueOf( schema.get( "type" ) ) ) { + case "array": + Assertions.assertTrue( value.isJsonArray(), where + " must be an array" ); + value.getAsJsonArray().forEach( item -> assertMatchesSchema( resolve( schema.get( "items" ) ), item, where + "[]" ) ); + break; + case "object": + Assertions.assertTrue( value.isJsonObject(), where + " must be an object" ); + final JsonObject object = value.getAsJsonObject(); + for( final Object required : list( schema, "required" ) ) { + Assertions.assertTrue( object.has( required.toString() ), where + " lacks " + required ); + } + final Map< String, Object > properties = map( schema, "properties" ); + for( final String name : object.keySet() ) { + Assertions.assertTrue( properties.containsKey( name ), where + "." + name + " is not in the contract" ); + assertMatchesSchema( resolve( properties.get( name ) ), object.get( name ), where + "." + name ); + } + break; + case "string": + Assertions.assertTrue( value.isJsonPrimitive() && value.getAsJsonPrimitive().isString(), where + " must be a string" ); + break; + case "integer": + Assertions.assertTrue( value.isJsonPrimitive() && value.getAsJsonPrimitive().isNumber() + && value.getAsDouble() == Math.rint( value.getAsDouble() ), where + " must be an integer" ); + break; + default: + Assertions.fail( "the test does not know the type of " + where ); + } + } + + private static Map< String, Object > contract() { + try( InputStream in = ApiV1Servlet.class.getResourceAsStream( "openapi.yaml" ) ) { + return new Yaml().load( in ); + } catch( final java.io.IOException e ) { + throw new IllegalStateException( e ); + } + } + + /** Follows a local reference such as #/components/schemas/Error. */ + private static Map< String, Object > resolve( final Object node ) { + Map< String, Object > current = map( node, null ); + while( current.containsKey( "$ref" ) ) { + Object target = CONTRACT; + for( final String part : current.get( "$ref" ).toString().substring( 2 ).split( "/" ) ) { + target = map( target, null ).get( part ); + } + current = map( target, null ); + } + return current; + } + + @SuppressWarnings( "unchecked" ) + private static Map< String, Object > map( final Object node, final String key ) { + return ( Map< String, Object > )( key == null ? node : ( ( Map< String, Object > )node ).get( key ) ); + } + + @SuppressWarnings( "unchecked" ) + private static List< Object > list( final Map< String, Object > node, final String key ) { + return ( List< Object > )node.get( key ); + } + + /** What the servlet wrote to a mock response. */ + private static final class Reply { + int status; + String contentType; + final StringWriter body = new StringWriter(); + + JsonElement json() { + return GSON.fromJson( body.toString(), JsonElement.class ); + } + } + +} diff --git a/jspwiki-war/src/main/webapp/WEB-INF/web.xml b/jspwiki-war/src/main/webapp/WEB-INF/web.xml index 86bf0d69ae..7b3cf9a849 100644 --- a/jspwiki-war/src/main/webapp/WEB-INF/web.xml +++ b/jspwiki-war/src/main/webapp/WEB-INF/web.xml @@ -184,6 +184,12 @@ 1 + + + ApiV1Servlet + org.apache.wiki.rest.ApiV1Servlet + + ATOM @@ -222,6 +228,11 @@ /admin/ajax/* + + ApiV1Servlet + /api/v1/* + + +**2026-11-20 Arturo Bernal (abernal AT apache DOT org)** + +* _3.0.2-git-2_ + +* [JSPWIKI-1310](https://issues.apache.org/jira/browse/JSPWIKI-1310): `GET /api/v1/search` is the first endpoint of a versioned REST API, described by the OpenAPI file `openapi.yaml` ([PR#589](https://github.com/apache/jspwiki/pull/589)) + **2026-11-19 Arturo Bernal (abernal AT apache DOT org)** * _3.0.2-git-1_ diff --git a/jspwiki-api/src/main/java/org/apache/wiki/api/Release.java b/jspwiki-api/src/main/java/org/apache/wiki/api/Release.java index 26cb6a0efa..ad73c8ffa7 100644 --- a/jspwiki-api/src/main/java/org/apache/wiki/api/Release.java +++ b/jspwiki-api/src/main/java/org/apache/wiki/api/Release.java @@ -69,7 +69,7 @@ public final class Release { *

* If the build identifier is empty, it is not added. */ - public static final String BUILD = "1"; + public static final String BUILD = "2"; /** * This is the generic version string you should use when printing out the version. It is of From 6c49f1e87db2148f3715b154b6f553737de22d49 Mon Sep 17 00:00:00 2001 From: Arturo Bernal Date: Fri, 20 Nov 2026 06:12:49 +0100 Subject: [PATCH 9/9] ChangeLog of JSPWIKI-1310 after the merge of master --- ChangeLog.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/ChangeLog.md b/ChangeLog.md index b241271f28..7bc52be8ef 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -21,6 +21,7 @@ under the License. * _3.0.2-git-2_ * [JSPWIKI-1310](https://issues.apache.org/jira/browse/JSPWIKI-1310): `GET /api/v1/search` is the first endpoint of a versioned REST API, described by the OpenAPI file `openapi.yaml` ([PR#589](https://github.com/apache/jspwiki/pull/589)) +* [JSPWIKI-1310](https://issues.apache.org/jira/browse/JSPWIKI-1310): `GET /api/v1/search/suggestions` and `GET /api/v1/plugins` are added to the REST API; the suggestions leave out the pages the caller may not view ([PR#590](https://github.com/apache/jspwiki/pull/590)) **2026-11-19 Arturo Bernal (abernal AT apache DOT org)** * _3.0.2-git-1_ @@ -144,8 +145,6 @@ under the License. * [JSPWIKI-530](https://issues.apache.org/jira/browse/JSPWIKI-530): new `LanguagePlugin` that shows the block of its body that matches the `Accept-Language` header of the visitor, based on the code that Ulf Dittmer attached to the issue ([PR#596](https://github.com/apache/jspwiki/pull/596)) * Fix for [JSPWIKI-90](https://issues.apache.org/jira/browse/JSPWIKI-90): the "More..." menu of the default template has an entry to be notified of the changes of the page, or to stop being notified. It posts, with the anti-CSRF token, to the new `Subscribe.jsp`, which needs a logged-in user with an e-mail address in the profile. * Fix for [JSPWIKI-90](https://issues.apache.org/jira/browse/JSPWIKI-90): the editors of the default template have a "Notify me of changes" box, so a user can subscribe to a page while writing it, also when it is a new page. `Edit.jsp` subscribes the user after the save, when the profile has an e-mail address. -* [JSPWIKI-1310](https://issues.apache.org/jira/browse/JSPWIKI-1310): `GET /api/v1/search` is the first endpoint of a versioned REST API, described by the OpenAPI file `openapi.yaml` ([PR#589](https://github.com/apache/jspwiki/pull/589)) -* [JSPWIKI-1310](https://issues.apache.org/jira/browse/JSPWIKI-1310): `GET /api/v1/search/suggestions` and `GET /api/v1/plugins` are added to the REST API; the suggestions leave out the pages the caller may not view ([PR#590](https://github.com/apache/jspwiki/pull/590)) **2026-10-29 Arturo Bernal (abernal AT apache DOT org)**