diff --git a/ChangeLog.md b/ChangeLog.md index 7f9a870113..6bde3cd93d 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -16,6 +16,17 @@ KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> +**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)) +* [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)) +* [JSPWIKI-1310](https://issues.apache.org/jira/browse/JSPWIKI-1310): `GET /api/v1/pages/{name}`, `GET /api/v1/pages/{name}/history` and `GET /api/v1/pages/{name}/attachments` are added to the REST API, to read a page, its versions and its attachments if the caller may view the page +* [JSPWIKI-1310](https://issues.apache.org/jira/browse/JSPWIKI-1310): `GET /api/v1/pages`, `GET /api/v1/pages/{name}/references` and `GET /api/v1/pages/{name}/html` are added to the REST API, to list the pages in chunks, to read the links of a page and to read a page rendered to HTML +* [JSPWIKI-1310](https://issues.apache.org/jira/browse/JSPWIKI-1310): the REST API is in its own module `jspwiki-rest-api` and writes its JSON with Jackson, which the wiki already uses, and not with Gson +* [JSPWIKI-1310](https://issues.apache.org/jira/browse/JSPWIKI-1310): the operations of `openapi.yaml` are grouped with the tags Search, Plugins and Pages, so that code generators such as openapi-generator make one class per tag, and a description that made the generator for JAX-RS interfaces write code that does not compile is reworded. A client and the JAX-RS interfaces generated with openapi-generator 7.27.0 compile, and the client reads the responses of a running wiki. + **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 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-bom/pom.xml b/jspwiki-bom/pom.xml index 2b27e4d5a7..18cc094686 100644 --- a/jspwiki-bom/pom.xml +++ b/jspwiki-bom/pom.xml @@ -97,6 +97,12 @@ ${jspwiki.version} + + org.apache.jspwiki + jspwiki-rest-api + ${jspwiki.version} + + org.apache.jspwiki jspwiki-portable diff --git a/jspwiki-main/pom.xml b/jspwiki-main/pom.xml index 3ea5c62eaa..fcb039b5b7 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/search/DefaultSearchManager.java b/jspwiki-main/src/main/java/org/apache/wiki/search/DefaultSearchManager.java index 2bc434229b..2c38136275 100644 --- a/jspwiki-main/src/main/java/org/apache/wiki/search/DefaultSearchManager.java +++ b/jspwiki-main/src/main/java/org/apache/wiki/search/DefaultSearchManager.java @@ -29,12 +29,14 @@ Licensed to the Apache Software Foundation (ASF) under one import org.apache.wiki.api.core.ContextEnum; import org.apache.wiki.api.core.Engine; import org.apache.wiki.api.core.Page; +import org.apache.wiki.api.core.Session; import org.apache.wiki.api.exceptions.FilterException; import org.apache.wiki.api.exceptions.NoRequiredPropertyException; import org.apache.wiki.api.filters.BasePageFilter; 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.auth.permissions.PermissionFactory; import org.apache.wiki.event.WikiEvent; import org.apache.wiki.event.WikiEventManager; @@ -59,6 +61,7 @@ Licensed to the Apache Software Foundation (ASF) under one import java.util.Map; import java.util.Properties; import java.util.Set; +import java.util.function.Predicate; import org.apache.wiki.api.plugin.Plugin; import org.apache.wiki.plugin.PluginManager; import static org.apache.wiki.search.SearchManager.PLUGIN_SEARCH; @@ -91,6 +94,52 @@ public DefaultSearchManager( final Engine engine, final Properties properties ) WikiAjaxDispatcherServlet.registerServlet( PLUGIN_SEARCH, new PluginSearch() ); } + /** {@inheritDoc} */ + @Override + public List< String > suggestPages( final String text, final int max, final Session session ) { + final AuthorizationManager mgr = m_engine.getManager( AuthorizationManager.class ); + return suggest( text, max, name -> mgr.checkPermission( session, new PagePermission( m_engine.getApplicationName() + ":" + name, PagePermission.VIEW_ACTION ) ) ); + } + + /** + * Looks for the names of the pages that start with the given text and that the filter accepts. + * + * @param wikiName the page name, optionally followed by a slash and the beginning of an attachment name + * @param maxLength maximum number of suggestions + * @param accepted tells whether a name may be suggested + * @return the suggestions + */ + private List< String > suggest( String wikiName, final int maxLength, final Predicate< String > accepted ) { + final StopWatch sw = new StopWatch(); + sw.start(); + final List< String > list = new ArrayList<>( Math.min( maxLength, 100 ) ); + if( !wikiName.isEmpty() ) { + // split pagename and attachment filename + String filename = ""; + final int pos = wikiName.indexOf("/"); + if( pos >= 0 ) { + filename = wikiName.substring( pos ).toLowerCase(); + wikiName = wikiName.substring( 0, pos ); + } + + final String cleanWikiName = MarkupParser.cleanLink(wikiName).toLowerCase() + filename; + final String oldStyleName = MarkupParser.wikifyLink(wikiName).toLowerCase() + filename; + final Set< String > allPages = m_engine.getManager( ReferenceManager.class ).findCreated(); + + for( final Iterator< String > i = allPages.iterator(); i.hasNext() && list.size() < maxLength; ) { + final String p = i.next(); + final String pp = p.toLowerCase(); + if( ( pp.startsWith( cleanWikiName ) || pp.startsWith( oldStyleName ) ) && accepted.test( p ) ) { + list.add( p ); + } + } + } + + sw.stop(); + LOG.debug( "Suggestion request for {} done in {}", wikiName, sw ); + return list; + } + /** * Provides a JSON AJAX API to the JSPWiki Plugin discovery mechanism, * primarily used for [{}] based auto complete @@ -228,37 +277,8 @@ private boolean mayView( final Context wikiContext, final String pageName ) { * @param wikiContext the context of the viewer, whose view permission decides which page names are suggested * @return the suggestions */ - public List< String > getSuggestions( String wikiName, final int maxLength, final Context wikiContext ) { - final StopWatch sw = new StopWatch(); - sw.start(); - final List< String > list = new ArrayList<>( maxLength ); - if( !wikiName.isEmpty() ) { - // split pagename and attachment filename - String filename = ""; - final int pos = wikiName.indexOf("/"); - if( pos >= 0 ) { - filename = wikiName.substring( pos ).toLowerCase(); - wikiName = wikiName.substring( 0, pos ); - } - - final String cleanWikiName = MarkupParser.cleanLink(wikiName).toLowerCase() + filename; - final String oldStyleName = MarkupParser.wikifyLink(wikiName).toLowerCase() + filename; - final Set< String > allPages = m_engine.getManager( ReferenceManager.class ).findCreated(); - - int counter = 0; - for( final Iterator< String > i = allPages.iterator(); i.hasNext() && counter < maxLength; ) { - final String p = i.next(); - final String pp = p.toLowerCase(); - if( ( pp.startsWith( cleanWikiName) || pp.startsWith( oldStyleName ) ) && mayView( wikiContext, p ) ) { - list.add( p ); - counter++; - } - } - } - - sw.stop(); - LOG.debug( "Suggestion request for {} done in {}", wikiName, sw ); - return list; + public List< String > getSuggestions( final String wikiName, final int maxLength, final Context wikiContext ) { + return suggest( wikiName, maxLength, name -> mayView( wikiContext, name ) ); } /** 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 e6ff9cfdab..3ef5e5bbdf 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 @@ -538,7 +538,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/java/org/apache/wiki/search/SearchManager.java b/jspwiki-main/src/main/java/org/apache/wiki/search/SearchManager.java index cb241c3aa3..398d2a471a 100644 --- a/jspwiki-main/src/main/java/org/apache/wiki/search/SearchManager.java +++ b/jspwiki-main/src/main/java/org/apache/wiki/search/SearchManager.java @@ -20,6 +20,7 @@ Licensed to the Apache Software Foundation (ASF) under one import org.apache.wiki.api.core.Context; import org.apache.wiki.api.core.Page; +import org.apache.wiki.api.core.Session; import org.apache.wiki.api.exceptions.ProviderException; import org.apache.wiki.api.filters.PageFilter; import org.apache.wiki.api.search.SearchResult; @@ -28,6 +29,7 @@ Licensed to the Apache Software Foundation (ASF) under one import java.io.IOException; import java.util.Collection; +import java.util.List; /** @@ -55,6 +57,17 @@ public interface SearchManager extends PageFilter, InternalModule, WikiEventList */ SearchProvider getSearchEngine(); + /** + * Suggests the names of the pages that start with the given text, leaving out the pages the session may not view. + * + * @param text the beginning of a page name, optionally followed by a slash and the beginning of an attachment name. + * @param max the maximum number of names to return. + * @param session the session of the caller. + * @return the names of the pages, in no particular order. + * @since 3.0.1 + */ + List< String > suggestPages( String text, int max, Session session ); + /** * Sends a search to the current search provider. The query is is whatever native format the query engine wants to use. * diff --git a/jspwiki-rest-api/pom.xml b/jspwiki-rest-api/pom.xml new file mode 100644 index 0000000000..a0fd5d7723 --- /dev/null +++ b/jspwiki-rest-api/pom.xml @@ -0,0 +1,116 @@ + + + + + + org.apache.jspwiki + jspwiki-builder + 3.0.2-SNAPSHOT + + + jspwiki-rest-api + 4.0.0 + Apache JSPWiki REST API + Version 1 of the REST API of Apache JSPWiki, described by an OpenAPI file + + + + ${project.groupId} + jspwiki-api + ${project.version} + + + + ${project.groupId} + jspwiki-main + ${project.version} + provided + + + + ${project.groupId} + jspwiki-main + ${project.version} + test-jar + test + + + + tools.jackson.core + jackson-databind + + + + org.apache.commons + commons-lang3 + + + + org.apache.lucene + lucene-queryparser + + + + org.apache.logging.log4j + log4j-api + + + + org.apache.logging.log4j + log4j-core + + + + jakarta.servlet + jakarta.servlet-api + provided + + + + org.junit.jupiter + junit-jupiter-api + test + + + + org.junit.jupiter + junit-jupiter-engine + test + + + + org.mockito + mockito-core + test + + + + org.awaitility + awaitility + test + + + + org.yaml + snakeyaml + test + + + diff --git a/jspwiki-rest-api/src/main/java/org/apache/wiki/rest/ApiV1Servlet.java b/jspwiki-rest-api/src/main/java/org/apache/wiki/rest/ApiV1Servlet.java new file mode 100644 index 0000000000..1d92e38ecc --- /dev/null +++ b/jspwiki-rest-api/src/main/java/org/apache/wiki/rest/ApiV1Servlet.java @@ -0,0 +1,463 @@ +/* + 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.fasterxml.jackson.annotation.JsonInclude; +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.Attachment; +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.Page; +import org.apache.wiki.api.core.Session; +import org.apache.wiki.api.exceptions.ProviderException; +import org.apache.wiki.api.plugin.Plugin; +import org.apache.wiki.api.providers.WikiProvider; +import org.apache.wiki.api.search.SearchResult; +import org.apache.wiki.api.spi.Wiki; +import org.apache.wiki.auth.AuthorizationManager; +import org.apache.wiki.attachment.AttachmentManager; +import org.apache.wiki.auth.permissions.PagePermission; +import org.apache.wiki.auth.permissions.PermissionFactory; +import org.apache.wiki.pages.PageManager; +import org.apache.wiki.plugin.PluginManager; +import org.apache.wiki.references.ReferenceManager; +import org.apache.wiki.render.RenderingManager; +import org.apache.wiki.search.SearchManager; +import tools.jackson.core.JacksonException; +import tools.jackson.databind.json.JsonMapper; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.Date; +import java.util.List; +import java.util.Locale; + +/** + * 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 ); + /** Leaves out the fields without a value, as the page that has no author. */ + private static final JsonMapper JSON = JsonMapper.builder() + .changeDefaultPropertyInclusion( value -> value.withValueInclusion( JsonInclude.Include.NON_NULL ) ) + .build(); + + /** Number of entries returned when the request does not say how many it wants. */ + static final int DEFAULT_MAX = 20; + + private static final String PAGES = "/pages/"; + private static final String HISTORY = "/history"; + private static final String ATTACHMENTS = "/attachments"; + private static final String REFERENCES = "/references"; + private static final String HTML = "/html"; + + 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 { + final String path = req.getPathInfo(); + if( "/search".equals( path ) ) { + search( req, resp ); + } else if( "/search/suggestions".equals( path ) ) { + suggestions( req, resp ); + } else if( "/plugins".equals( path ) ) { + plugins( req, resp ); + } else if( "/pages".equals( path ) ) { + list( req, resp ); + } else if( path != null && path.startsWith( PAGES ) ) { + pages( req, resp, path.substring( PAGES.length() ) ); + } else { + error( resp, HttpServletResponse.SC_NOT_FOUND, "No such resource." ); + } + } + + private void search( final HttpServletRequest req, final HttpServletResponse resp ) throws IOException { + final Session session = authorized( req, resp ); + final String query = session == null ? null : query( req, resp ); + final int max = query == null ? 0 : max( req, resp ); + if( max < 1 ) { + 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." ); + } + } + + private void suggestions( final HttpServletRequest req, final HttpServletResponse resp ) throws IOException { + final Session session = authorized( req, resp ); + final String query = session == null ? null : query( req, resp ); + final int max = query == null ? 0 : max( req, resp ); + if( max > 0 ) { + json( resp, HttpServletResponse.SC_OK, engine.getManager( SearchManager.class ).suggestPages( query, max, session ) ); + } + } + + private void plugins( final HttpServletRequest req, final HttpServletResponse resp ) throws IOException { + if( authorized( req, resp ) == null ) { + return; + } + final Locale locale = req.getLocale() != null ? req.getLocale() : Locale.getDefault(); + final List< Plugin > discovered = new ArrayList<>( engine.getManager( PluginManager.class ).getDiscoveredPlugins() ); + discovered.sort( Comparator.comparing( plugin -> plugin.getDisplayName( locale ) ) ); + final List< PluginEntry > entries = new ArrayList<>(); + for( final Plugin plugin : discovered ) { + entries.add( new PluginEntry( plugin.getDisplayName( locale ), plugin.getSnipExample() ) ); + } + json( resp, HttpServletResponse.SC_OK, entries ); + } + + /** Serves a page, its history or its attachments. The part of the path before the optional suffix is the page name. */ + private void pages( final HttpServletRequest req, final HttpServletResponse resp, final String rest ) throws IOException { + final String suffix = rest.endsWith( HISTORY ) ? HISTORY : rest.endsWith( ATTACHMENTS ) ? ATTACHMENTS + : rest.endsWith( REFERENCES ) ? REFERENCES : rest.endsWith( HTML ) ? HTML : ""; + final String name = rest.substring( 0, rest.length() - suffix.length() ); + if( name.isEmpty() ) { + error( resp, HttpServletResponse.SC_NOT_FOUND, "No such resource." ); + return; + } + if( !plausible( name ) ) { + error( resp, HttpServletResponse.SC_BAD_REQUEST, "The name of the page is not valid." ); + return; + } + final Session session = authorized( req, resp ); + if( session == null ) { + return; + } + // The permission is checked before the existence of the page, so that the answer does not depend on whether a page is there + if( !engine.getManager( AuthorizationManager.class ).checkPermission( session, PermissionFactory.getPagePermission( Wiki.contents().page( engine, name ), PagePermission.VIEW_ACTION ) ) ) { + denied( resp, session ); + return; + } + final int version = suffix.isEmpty() || HTML.equals( suffix ) ? version( req, resp ) : WikiProvider.LATEST_VERSION; + if( version == 0 ) { + return; + } + + try { + final Page page = engine.getManager( PageManager.class ).getPageInfo( name, version ); + if( page == null ) { + error( resp, HttpServletResponse.SC_NOT_FOUND, "The page does not exist." ); + } else if( HISTORY.equals( suffix ) ) { + history( resp, page ); + } else if( ATTACHMENTS.equals( suffix ) ) { + attachments( resp, page ); + } else if( REFERENCES.equals( suffix ) ) { + references( req, resp, page ); + } else if( HTML.equals( suffix ) ) { + final Context context = Wiki.context().create( engine, req, page ); + json( resp, HttpServletResponse.SC_OK, new Rendered( page, engine.getManager( RenderingManager.class ).getHTML( context, page ) ) ); + } else { + final String text = engine.getManager( PageManager.class ).getPageText( name, page.getVersion() ); + json( resp, HttpServletResponse.SC_OK, new PageContent( page, text ) ); + } + } catch( final ProviderException e ) { + LOG.error( "The request for the page {} of the REST API failed", name, e ); + error( resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "The page could not be read." ); + } + } + + /** Lists the names of the pages the caller may view, sorted by name, from the position given by offset. */ + private void list( final HttpServletRequest req, final HttpServletResponse resp ) throws IOException { + final Session session = authorized( req, resp ); + final int max = session == null ? 0 : max( req, resp ); + final int offset = max < 1 ? -1 : offset( req, resp ); + if( offset < 0 ) { + return; + } + try { + final AuthorizationManager mgr = engine.getManager( AuthorizationManager.class ); + final List< String > names = new ArrayList<>(); + for( final Page page : engine.getManager( PageManager.class ).getAllPages() ) { + if( mgr.checkPermission( session, PermissionFactory.getPagePermission( page, PagePermission.VIEW_ACTION ) ) ) { + names.add( page.getName() ); + } + } + names.sort( engine.getManager( PageManager.class ).getPageSorter() ); + json( resp, HttpServletResponse.SC_OK, names.subList( Math.min( offset, names.size() ), ( int )Math.min( offset + ( long )max, names.size() ) ) ); + } catch( final ProviderException e ) { + LOG.error( "The list of pages for the REST API failed", e ); + error( resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "The pages could not be listed." ); + } + } + + /** Answers with the pages that link to the page and the pages it links to, leaving out the ones the caller may not view. */ + private void references( final HttpServletRequest req, final HttpServletResponse resp, final Page page ) throws IOException { + final Session session = Wiki.session().find( engine, req ); + final ReferenceManager references = engine.getManager( ReferenceManager.class ); + json( resp, HttpServletResponse.SC_OK, new References( viewable( session, references.findReferrers( page.getName() ) ), + viewable( session, references.findRefersTo( page.getName() ) ) ) ); + } + + /** Returns the names the session may view, sorted. A name without a page, such as a link to a page not yet written, is kept. */ + private List< String > viewable( final Session session, final Collection< String > names ) { + final List< String > viewable = new ArrayList<>(); + if( names != null ) { + final AuthorizationManager mgr = engine.getManager( AuthorizationManager.class ); + for( final String name : names ) { + if( mgr.checkPermission( session, PermissionFactory.getPagePermission( Wiki.contents().page( engine, name ), PagePermission.VIEW_ACTION ) ) ) { + viewable.add( name ); + } + } + } + viewable.sort( engine.getManager( PageManager.class ).getPageSorter() ); + return viewable; + } + + /** Returns the offset parameter, zero when it is absent, and -1 after answering 400 when it is not an integer of zero or more. */ + private static int offset( final HttpServletRequest req, final HttpServletResponse resp ) throws IOException { + final String value = req.getParameter( "offset" ); + if( value == null ) { + return 0; + } + try { + final int offset = Integer.parseInt( value.trim() ); + if( offset >= 0 ) { + return offset; + } + } catch( final NumberFormatException e ) { + // answered below + } + error( resp, HttpServletResponse.SC_BAD_REQUEST, "The parameter offset must be an integer of zero or more." ); + return -1; + } + + private void history( final HttpServletResponse resp, final Page page ) throws IOException { + final List< Page > versions = engine.getManager( PageManager.class ).getVersionHistory( page.getName() ); + if( versions == null ) { + error( resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "The history of the page could not be read." ); + return; + } + final List< Revision > revisions = new ArrayList<>(); + for( final Page version : versions ) { + revisions.add( new Revision( version ) ); + } + if( revisions.isEmpty() ) { + // A page that was put in the page directory by hand has no history, but it still has its current version + revisions.add( new Revision( page ) ); + } + revisions.sort( Comparator.comparingInt( ( Revision revision ) -> revision.version() ).reversed() ); + json( resp, HttpServletResponse.SC_OK, revisions ); + } + + private void attachments( final HttpServletResponse resp, final Page page ) throws ProviderException, IOException { + final List< AttachmentEntry > entries = new ArrayList<>(); + for( final Attachment attachment : engine.getManager( AttachmentManager.class ).listAttachments( page ) ) { + entries.add( new AttachmentEntry( attachment ) ); + } + json( resp, HttpServletResponse.SC_OK, entries ); + } + + /** + * Tells whether the text can be the name of a page. The providers encode the names they turn into files, so this is only an extra + * barrier before a name that comes from the caller reaches them: no parent directory, no backslash and no control character. + */ + private static boolean plausible( final String name ) { + return !name.contains( ".." ) && name.indexOf( '\\' ) < 0 && name.chars().noneMatch( Character::isISOControl ); + } + + /** Returns the version parameter, the latest version when it is absent, and 0 after answering 400 when it is not a positive integer. */ + private static int version( final HttpServletRequest req, final HttpServletResponse resp ) throws IOException { + final String value = req.getParameter( "version" ); + if( value == null ) { + return WikiProvider.LATEST_VERSION; + } + try { + final int version = Integer.parseInt( value.trim() ); + if( version > 0 ) { + return version; + } + } catch( final NumberFormatException e ) { + // answered below + } + error( resp, HttpServletResponse.SC_BAD_REQUEST, "The parameter version must be an integer greater than zero." ); + return 0; + } + + /** A provider that keeps no old versions numbers its only version -1, which the API reports as 1. */ + private static int number( final int version ) { + return Math.max( 1, version ); + } + + private static String instant( final Date date ) { + return date == null ? null : date.toInstant().toString(); + } + + /** Returns the session of the caller, or null after answering 401 or 403 when the caller may not read. */ + private Session authorized( 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 ) ) { + return session; + } + denied( resp, session ); + return null; + } + + /** Returns the query parameter, or null after answering 400 when it is missing. */ + private static String query( final HttpServletRequest req, final HttpServletResponse resp ) throws IOException { + final String query = req.getParameter( "query" ); + if( StringUtils.isBlank( query ) ) { + error( resp, HttpServletResponse.SC_BAD_REQUEST, "The parameter query is required." ); + return null; + } + return query; + } + + /** Returns the max parameter, the default when it is absent, and 0 after answering 400 when it is not a positive integer. */ + private static int max( final HttpServletRequest req, final HttpServletResponse resp ) throws IOException { + final String value = req.getParameter( "max" ); + if( value == null ) { + return DEFAULT_MAX; + } + try { + final int max = Integer.parseInt( value.trim() ); + if( max > 0 ) { + return max; + } + } catch( final NumberFormatException e ) { + // answered below + } + error( resp, HttpServletResponse.SC_BAD_REQUEST, "The parameter max must be an integer greater than zero." ); + 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() ); + try { + resp.getWriter().write( JSON.writeValueAsString( body ) ); + } catch( final JacksonException e ) { + // the bodies are built here, so this is a bug and not a failure of the caller + throw new IOException( e ); + } + } + + /** An entry of the answer to a search. */ + private record Hit( String page, int score ) { + } + + /** An entry of the list of plugins. */ + private record PluginEntry( String displayName, String snip ) { + } + + /** The content of a page. */ + private record PageContent( String name, int version, String author, String lastModified, String text ) { + + PageContent( final Page page, final String text ) { + this( page.getName(), number( page.getVersion() ), page.getAuthor(), instant( page.getLastModified() ), text ); + } + } + + /** The page rendered to HTML. */ + private record Rendered( String name, int version, String html ) { + + Rendered( final Page page, final String html ) { + this( page.getName(), number( page.getVersion() ), html ); + } + } + + /** The links of a page. */ + private record References( List< String > referredBy, List< String > refersTo ) { + } + + /** An entry of the history of a page. */ + private record Revision( int version, String author, String lastModified, String changeNote ) { + + Revision( final Page page ) { + this( number( page.getVersion() ), page.getAuthor(), instant( page.getLastModified() ), page.getAttribute( Page.CHANGENOTE ) ); + } + } + + /** An entry of the list of attachments of a page. */ + private record AttachmentEntry( String name, int version, long size, String author, String lastModified ) { + + AttachmentEntry( final Attachment attachment ) { + this( attachment.getFileName(), number( attachment.getVersion() ), attachment.getSize(), attachment.getAuthor(), + instant( attachment.getLastModified() ) ); + } + } + + /** The body of every answer that is not a success. */ + private record Failure( int status, String message ) { + } + +} diff --git a/jspwiki-rest-api/src/main/resources/org/apache/wiki/rest/openapi.yaml b/jspwiki-rest-api/src/main/resources/org/apache/wiki/rest/openapi.yaml new file mode 100644 index 0000000000..fddf495bb3 --- /dev/null +++ b/jspwiki-rest-api/src/main/resources/org/apache/wiki/rest/openapi.yaml @@ -0,0 +1,441 @@ +# 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, page name suggestions and the installed plugins. + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: /api/v1 +security: + - sessionCookie: [] +tags: + - name: Search + description: Finding pages by text or by the start of their name. + - name: Plugins + description: The plugins the wiki offers. + - name: Pages + description: Reading pages, their history, attachments and references. +paths: + /search: + get: + operationId: searchPages + tags: [Search] + 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' + /search/suggestions: + get: + operationId: suggestPages + tags: [Search] + summary: Suggest the names of the pages that start with the given text and that the caller may view. + parameters: + - name: query + in: query + required: true + schema: + type: string + minLength: 1 + - $ref: '#/components/parameters/max' + responses: + '200': + description: Page names. Empty when there is no suggestion. + content: + application/json: + schema: + type: array + items: + type: string + '400': + $ref: '#/components/responses/BadRequest' + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + /plugins: + get: + operationId: listPlugins + tags: [Plugins] + summary: List the plugins discovered by the wiki, sorted by display name for the locale of the request. + responses: + '200': + description: The plugins with an example of how to insert each one. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Plugin' + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + /pages: + get: + operationId: listPages + tags: [Pages] + summary: List the names of the pages the caller may view, sorted by name. + parameters: + - $ref: '#/components/parameters/max' + - name: offset + in: query + required: false + description: Number of names to skip, to read the next entries of a long list. + schema: + type: integer + minimum: 0 + default: 0 + responses: + '200': + description: Page names. Empty when there are no more. + content: + application/json: + schema: + type: array + items: + type: string + '400': + $ref: '#/components/responses/BadRequest' + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + '500': + $ref: '#/components/responses/InternalError' + /pages/{name}: + get: + operationId: getPage + tags: [Pages] + summary: Read a page the caller may view, in the latest version or in the one asked for. + parameters: + - $ref: '#/components/parameters/name' + - name: version + in: query + required: false + description: Version of the page. The latest version when absent. + schema: + type: integer + minimum: 1 + responses: + '200': + description: The page with its markup. + content: + application/json: + schema: + $ref: '#/components/schemas/Page' + '400': + $ref: '#/components/responses/BadRequest' + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + '500': + $ref: '#/components/responses/InternalError' + /pages/{name}/history: + get: + operationId: getPageHistory + tags: [Pages] + summary: List the versions of a page the caller may view, the latest first. + parameters: + - $ref: '#/components/parameters/name' + responses: + '200': + description: The versions of the page. A provider that does not keep old versions lists only the current one. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Revision' + '400': + $ref: '#/components/responses/BadRequest' + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + '500': + $ref: '#/components/responses/InternalError' + /pages/{name}/attachments: + get: + operationId: listPageAttachments + tags: [Pages] + summary: List the attachments of a page the caller may view, sorted by name. + parameters: + - $ref: '#/components/parameters/name' + responses: + '200': + description: The attachments of the page. Empty when it has none or when attachments are disabled. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Attachment' + '400': + $ref: '#/components/responses/BadRequest' + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + '500': + $ref: '#/components/responses/InternalError' + /pages/{name}/references: + get: + operationId: getPageReferences + tags: [Pages] + summary: List the pages that link to a page and the pages it links to, leaving out the ones the caller may not view. + parameters: + - $ref: '#/components/parameters/name' + responses: + '200': + description: The links of the page, each list sorted by name. A page that is linked but not written yet is listed. + content: + application/json: + schema: + $ref: '#/components/schemas/References' + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + '500': + $ref: '#/components/responses/InternalError' + /pages/{name}/html: + get: + operationId: getPageHtml + tags: [Pages] + summary: Read a page rendered to HTML, as the wiki shows it to the caller. + parameters: + - $ref: '#/components/parameters/name' + - name: version + in: query + required: false + description: Version of the page. The latest version when absent. + schema: + type: integer + minimum: 1 + responses: + '200': + description: The HTML of the page, without the template around it. + content: + application/json: + schema: + $ref: '#/components/schemas/RenderedPage' + '400': + $ref: '#/components/responses/BadRequest' + '401': + $ref: '#/components/responses/Unauthorized' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + '500': + $ref: '#/components/responses/InternalError' +components: + securitySchemes: + sessionCookie: + type: apiKey + in: cookie + name: JSESSIONID + parameters: + name: + name: name + in: path + required: true + description: Name of the page. A name with two dots in a row, a backslash or a control character is not valid. + schema: + type: string + minLength: 1 + 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. + Page: + type: object + required: [name, version, text] + properties: + name: + type: string + version: + type: integer + author: + type: string + lastModified: + type: string + format: date-time + text: + type: string + description: Wiki markup of the page, without any conversion. + RenderedPage: + type: object + required: [name, version, html] + properties: + name: + type: string + version: + type: integer + html: + type: string + References: + type: object + required: [referredBy, refersTo] + properties: + referredBy: + type: array + items: + type: string + refersTo: + type: array + items: + type: string + Revision: + type: object + required: [version] + properties: + version: + type: integer + author: + type: string + lastModified: + type: string + format: date-time + changeNote: + type: string + Attachment: + type: object + required: [name, version, size] + properties: + name: + type: string + description: File name of the attachment. + version: + type: integer + size: + type: integer + description: Size in bytes. + author: + type: string + lastModified: + type: string + format: date-time + Plugin: + type: object + required: [displayName, snip] + properties: + displayName: + type: string + snip: + type: string + description: Example of the markup that inserts the plugin. + 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' + NotFound: + description: The page does not exist. + 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-rest-api/src/test/java/org/apache/wiki/rest/ApiV1ServletTest.java b/jspwiki-rest-api/src/test/java/org/apache/wiki/rest/ApiV1ServletTest.java new file mode 100644 index 0000000000..a549e364d2 --- /dev/null +++ b/jspwiki-rest-api/src/test/java/org/apache/wiki/rest/ApiV1ServletTest.java @@ -0,0 +1,785 @@ +/* + 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 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.Attachment; +import org.apache.wiki.api.core.Session; +import org.apache.wiki.api.spi.Wiki; +import org.apache.wiki.attachment.AttachmentManager; +import org.apache.wiki.auth.AuthenticationManager; +import org.apache.wiki.auth.AuthorizationManager; +import org.apache.wiki.auth.Users; +import org.apache.wiki.pages.PageManager; +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 tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +import java.io.ByteArrayInputStream; +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.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; + +class ApiV1ServletTest { + + private static final JsonMapper JSON = JsonMapper.builder().build(); + 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" ).ignoreExceptions().until( () -> { + reply[ 0 ] = search( null, "query", "mankind" ); + return reply[ 0 ].json().size() == 2; + } ); + + assertMatchesContract( "/search", reply[ 0 ] ); + Assertions.assertEquals( 200, reply[ 0 ].status ); + final JsonNode first = reply[ 0 ].json().get( 0 ); + Assertions.assertTrue( first.get( "page" ).asString().startsWith( "ApiSearch" ) ); + } + + @Test + void searchWithoutMatchesAnswersWithAnEmptyList() throws Exception { + startEngine( null ); + + final Reply[] answer = new Reply[ 1 ]; + Awaitility.await( "the index is built" ).until( () -> { + answer[ 0 ] = search( null, "query", "nothingwillmatchthis" ); + return answer[ 0 ].status != 503; + } ); + final Reply reply = answer[ 0 ]; + + assertMatchesContract( "/search", reply ); + Assertions.assertEquals( 200, reply.status ); + Assertions.assertEquals( 0, reply.json().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" ).ignoreExceptions().until( () -> search( null, "query", "common" ).json().size() == 2 ); + + final Reply reply = search( null, "query", "common", "max", "1" ); + + assertMatchesContract( "/search", reply ); + Assertions.assertEquals( 1, reply.json().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[] answer = new Reply[ 1 ]; + Awaitility.await( "the index is built" ).until( () -> { + answer[ 0 ] = search( null, "query", "\"unbalanced" ); + return answer[ 0 ].status != 503; + } ); + final Reply reply = answer[ 0 ]; + + 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 suggestionsAnswerWithTheContract() throws Exception { + startEngine( null ); + engine.saveText( "ApiSugOne", "one" ); + engine.saveText( "ApiSugTwo", "two" ); + engine.saveText( "ApiOther", "other" ); + + final Reply reply = call( requestTo( "/search/suggestions", "query", "ApiSug" ) ); + + assertMatchesContract( "/search/suggestions", reply ); + Assertions.assertEquals( 200, reply.status ); + Assertions.assertEquals( Set.of( "ApiSugOne", "ApiSugTwo" ), names( reply ) ); + } + + @Test + void suggestionsReturnAtMostMaxEntries() throws Exception { + startEngine( null ); + engine.saveText( "ApiSugOne", "one" ); + engine.saveText( "ApiSugTwo", "two" ); + + final Reply reply = call( requestTo( "/search/suggestions", "query", "ApiSug", "max", "1" ) ); + + assertMatchesContract( "/search/suggestions", reply ); + Assertions.assertEquals( 1, reply.json().size() ); + } + + @Test + void suggestionsLeaveOutThePagesTheCallerMayNotView() throws Exception { + startEngine( null ); + engine.saveText( "ApiSugOpen", "open" ); + engine.saveText( "ApiSugSecret", "[{ALLOW view Admin}] secret" ); + + final Reply reply = call( requestTo( "/search/suggestions", "query", "ApiSug" ) ); + + assertMatchesContract( "/search/suggestions", reply ); + Assertions.assertEquals( Set.of( "ApiSugOpen" ), names( reply ) ); + } + + @Test + void suggestionsWithoutQueryAreABadRequest() throws Exception { + startEngine( null ); + + final Reply reply = call( requestTo( "/search/suggestions" ) ); + + assertMatchesContract( "/search/suggestions", reply ); + Assertions.assertEquals( 400, reply.status ); + } + + @Test + void suggestionsByAnAnonymousCallerWithoutPermissionAre401( @TempDir final Path dir ) throws Exception { + startEngine( policy( dir, "Authenticated" ) ); + + final Reply reply = call( requestTo( "/search/suggestions", "query", "Api" ) ); + + assertMatchesContract( "/search/suggestions", reply ); + Assertions.assertEquals( 401, reply.status ); + } + + @Test + void pluginsAnswerWithTheContractSortedByDisplayName() throws Exception { + startEngine( null ); + + final Reply reply = call( requestTo( "/plugins" ) ); + + assertMatchesContract( "/plugins", reply ); + Assertions.assertEquals( 200, reply.status ); + final List< String > displayNames = new ArrayList<>(); + reply.json().forEach( entry -> displayNames.add( entry.get( "displayName" ).asString() ) ); + Assertions.assertFalse( displayNames.isEmpty(), "the wiki has plugins" ); + final List< String > sorted = new ArrayList<>( displayNames ); + sorted.sort( null ); + Assertions.assertEquals( sorted, displayNames ); + } + + @Test + void pluginsByALoggedInCallerWithoutPermissionAre403( @TempDir final Path dir ) throws Exception { + startEngine( policy( dir, "Admin" ) ); + final HttpServletRequest request = requestTo( "/plugins" ); + final Session session = Wiki.session().find( engine, request ); + engine.getManager( AuthenticationManager.class ).login( session, request, Users.JANNE, Users.JANNE_PASS ); + + final Reply reply = call( request ); + + assertMatchesContract( "/plugins", reply ); + Assertions.assertEquals( 403, 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().get( "status" ).asInt() ); + } + + @Test + void pageAnswersWithTheContract() throws Exception { + startEngine( null ); + engine.saveText( "ApiReadPage", "Some *markup* here." ); + + final Reply reply = call( requestTo( "/pages/ApiReadPage" ) ); + + assertMatchesContract( "/pages/{name}", reply ); + Assertions.assertEquals( 200, reply.status ); + final JsonNode page = reply.json(); + Assertions.assertEquals( "ApiReadPage", page.get( "name" ).asString() ); + Assertions.assertEquals( 1, page.get( "version" ).asInt() ); + Assertions.assertTrue( page.get( "text" ).asString().contains( "Some *markup* here." ) ); + } + + @Test + void pageInAnOlderVersionAnswersWithThatText() throws Exception { + startEngine( null, "0", "VersioningFileProvider" ); + engine.saveText( "ApiReadVersions", "first text" ); + engine.saveText( "ApiReadVersions", "second text" ); + + final Reply latest = call( requestTo( "/pages/ApiReadVersions" ) ); + final Reply first = call( requestTo( "/pages/ApiReadVersions", "version", "1" ) ); + + assertMatchesContract( "/pages/{name}", first ); + Assertions.assertEquals( 2, latest.json().get( "version" ).asInt() ); + Assertions.assertTrue( latest.json().get( "text" ).asString().contains( "second text" ) ); + Assertions.assertEquals( 1, first.json().get( "version" ).asInt() ); + Assertions.assertTrue( first.json().get( "text" ).asString().contains( "first text" ) ); + } + + @Test + void pageThatDoesNotExistIs404() throws Exception { + startEngine( null ); + + final Reply reply = call( requestTo( "/pages/ApiNoSuchPage" ) ); + + assertMatchesContract( "/pages/{name}", reply ); + Assertions.assertEquals( 404, reply.status ); + } + + @Test + void pageWithAVersionThatIsNotAPositiveIntegerIsABadRequest() throws Exception { + startEngine( null ); + engine.saveText( "ApiReadBadVersion", "text" ); + + for( final String version : new String[] { "0", "-1", "last", "" } ) { + final Reply reply = call( requestTo( "/pages/ApiReadBadVersion", "version", version ) ); + + assertMatchesContract( "/pages/{name}", reply ); + Assertions.assertEquals( 400, reply.status, "version=" + version ); + } + } + + @Test + void pageTheCallerMayNotViewIs401ForAnAnonymousCallerAnd403ForALoggedInOne() throws Exception { + startEngine( null ); + engine.saveText( "ApiReadSecret", "[{ALLOW view Admin}] secret" ); + + final Reply anonymous = call( requestTo( "/pages/ApiReadSecret" ) ); + final HttpServletRequest request = requestTo( "/pages/ApiReadSecret" ); + final Session session = Wiki.session().find( engine, request ); + engine.getManager( AuthenticationManager.class ).login( session, request, Users.JANNE, Users.JANNE_PASS ); + final Reply loggedIn = call( request ); + + assertMatchesContract( "/pages/{name}", anonymous ); + assertMatchesContract( "/pages/{name}", loggedIn ); + Assertions.assertEquals( 401, anonymous.status ); + Assertions.assertEquals( 403, loggedIn.status ); + Assertions.assertFalse( anonymous.body.toString().contains( "secret" ) ); + Assertions.assertFalse( loggedIn.body.toString().contains( "secret" ) ); + } + + @Test + void historyAnswersWithTheVersionsLatestFirst() throws Exception { + startEngine( null, "0", "VersioningFileProvider" ); + engine.saveText( "ApiReadHistory", "one" ); + engine.saveText( "ApiReadHistory", "two" ); + engine.saveText( "ApiReadHistory", "three" ); + + final Reply reply = call( requestTo( "/pages/ApiReadHistory/history" ) ); + + assertMatchesContract( "/pages/{name}/history", reply ); + Assertions.assertEquals( 200, reply.status ); + final List< Integer > versions = new ArrayList<>(); + reply.json().forEach( entry -> versions.add( entry.get( "version" ).asInt() ) ); + Assertions.assertEquals( List.of( 3, 2, 1 ), versions ); + } + + @Test + void historyOfAPageWithoutOldVersionsListsTheCurrentOne() throws Exception { + startEngine( null, "0", "VersioningFileProvider" ); + Files.write( Path.of( engine.getWikiProperties().getProperty( "jspwiki.fileSystemProvider.pageDir" ), "ApiReadByHand.txt" ), + "put here by hand".getBytes( StandardCharsets.UTF_8 ) ); + + final Reply reply = call( requestTo( "/pages/ApiReadByHand/history" ) ); + + assertMatchesContract( "/pages/{name}/history", reply ); + Assertions.assertEquals( 200, reply.status ); + Assertions.assertEquals( 1, reply.json().size() ); + Assertions.assertEquals( 1, reply.json().get( 0 ).get( "version" ).asInt() ); + } + + @Test + void historyOfAPageThatDoesNotExistIs404() throws Exception { + startEngine( null ); + + final Reply reply = call( requestTo( "/pages/ApiNoSuchPage/history" ) ); + + assertMatchesContract( "/pages/{name}/history", reply ); + Assertions.assertEquals( 404, reply.status ); + } + + @Test + void historyOfAPageTheCallerMayNotViewIs401() throws Exception { + startEngine( null ); + engine.saveText( "ApiReadSecretHistory", "[{ALLOW view Admin}] secret" ); + + final Reply reply = call( requestTo( "/pages/ApiReadSecretHistory/history" ) ); + + assertMatchesContract( "/pages/{name}/history", reply ); + Assertions.assertEquals( 401, reply.status ); + } + + @Test + void attachmentsAnswerWithTheContract() throws Exception { + startEngine( null ); + engine.saveText( "ApiReadAttachments", "text" ); + final Attachment attachment = Wiki.contents().attachment( engine, "ApiReadAttachments", "b.txt" ); + engine.getManager( AttachmentManager.class ).storeAttachment( attachment, new ByteArrayInputStream( "hello".getBytes( StandardCharsets.UTF_8 ) ) ); + final Attachment other = Wiki.contents().attachment( engine, "ApiReadAttachments", "a.txt" ); + engine.getManager( AttachmentManager.class ).storeAttachment( other, new ByteArrayInputStream( "hi".getBytes( StandardCharsets.UTF_8 ) ) ); + + final Reply reply = call( requestTo( "/pages/ApiReadAttachments/attachments" ) ); + + assertMatchesContract( "/pages/{name}/attachments", reply ); + Assertions.assertEquals( 200, reply.status ); + final JsonNode entries = reply.json(); + Assertions.assertEquals( 2, entries.size() ); + Assertions.assertEquals( "a.txt", entries.get( 0 ).get( "name" ).asString() ); + Assertions.assertEquals( 2, entries.get( 0 ).get( "size" ).asInt() ); + Assertions.assertEquals( "b.txt", entries.get( 1 ).get( "name" ).asString() ); + } + + @Test + void attachmentsOfAPageWithoutAttachmentsAreAnEmptyList() throws Exception { + startEngine( null ); + engine.saveText( "ApiReadNoAttachments", "text" ); + + final Reply reply = call( requestTo( "/pages/ApiReadNoAttachments/attachments" ) ); + + assertMatchesContract( "/pages/{name}/attachments", reply ); + Assertions.assertEquals( 200, reply.status ); + Assertions.assertEquals( 0, reply.json().size() ); + } + + @Test + void attachmentsOfAPageTheCallerMayNotViewAre401() throws Exception { + startEngine( null ); + engine.saveText( "ApiReadSecretAttachments", "[{ALLOW view Admin}] secret" ); + + final Reply reply = call( requestTo( "/pages/ApiReadSecretAttachments/attachments" ) ); + + assertMatchesContract( "/pages/{name}/attachments", reply ); + Assertions.assertEquals( 401, reply.status ); + } + + @Test + void attachmentsOfAPageThatDoesNotExistAre404() throws Exception { + startEngine( null ); + + final Reply reply = call( requestTo( "/pages/ApiNoSuchPage/attachments" ) ); + + assertMatchesContract( "/pages/{name}/attachments", reply ); + Assertions.assertEquals( 404, reply.status ); + } + + @Test + void pagesListTheNamesSortedAndLeaveOutTheOnesTheCallerMayNotView() throws Exception { + startEngine( null ); + engine.saveText( "ApiListB", "b" ); + engine.saveText( "ApiListA", "a" ); + engine.saveText( "ApiListSecret", "[{ALLOW view Admin}] secret" ); + + final Reply reply = call( requestTo( "/pages", "max", "1000" ) ); + + assertMatchesContract( "/pages", reply ); + Assertions.assertEquals( 200, reply.status ); + final List< String > names = new ArrayList<>(); + reply.json().forEach( name -> names.add( name.asString() ) ); + Assertions.assertTrue( names.indexOf( "ApiListA" ) >= 0 && names.indexOf( "ApiListA" ) < names.indexOf( "ApiListB" ) ); + Assertions.assertFalse( names.contains( "ApiListSecret" ) ); + } + + @Test + void pagesListInChunksWithMaxAndOffset() throws Exception { + startEngine( null ); + engine.saveText( "ApiChunkA", "a" ); + engine.saveText( "ApiChunkB", "b" ); + engine.saveText( "ApiChunkC", "c" ); + final List< String > all = new ArrayList<>(); + call( requestTo( "/pages", "max", "1000" ) ).json().forEach( name -> all.add( name.asString() ) ); + + final Reply second = call( requestTo( "/pages", "max", "2", "offset", "1" ) ); + + assertMatchesContract( "/pages", second ); + final List< String > chunk = new ArrayList<>(); + second.json().forEach( name -> chunk.add( name.asString() ) ); + Assertions.assertEquals( all.subList( 1, 3 ), chunk ); + final Reply beyond = call( requestTo( "/pages", "offset", "100000" ) ); + Assertions.assertEquals( 0, beyond.json().size() ); + } + + @Test + void pagesWithAnOffsetThatIsNotAnIntegerOfZeroOrMoreIsABadRequest() throws Exception { + startEngine( null ); + + for( final String offset : new String[] { "-1", "x", "" } ) { + final Reply reply = call( requestTo( "/pages", "offset", offset ) ); + + assertMatchesContract( "/pages", reply ); + Assertions.assertEquals( 400, reply.status, "offset=" + offset ); + } + } + + @Test + void pagesListByAnAnonymousCallerWithoutPermissionIs401( @TempDir final Path dir ) throws Exception { + startEngine( policy( dir, "Authenticated" ) ); + + final Reply reply = call( requestTo( "/pages" ) ); + + assertMatchesContract( "/pages", reply ); + Assertions.assertEquals( 401, reply.status ); + } + + @Test + void referencesListTheLinksInBothDirectionsWithoutTheSecretOnes() throws Exception { + startEngine( null ); + engine.saveText( "ApiRefTarget", "the target" ); + engine.saveText( "ApiRefSource", "links to [ApiRefTarget] and to [ApiRefNotWritten]" ); + engine.saveText( "ApiRefSecret", "[{ALLOW view Admin}] links to [ApiRefTarget]" ); + + final Reply target = call( requestTo( "/pages/ApiRefTarget/references" ) ); + final Reply source = call( requestTo( "/pages/ApiRefSource/references" ) ); + + assertMatchesContract( "/pages/{name}/references", target ); + assertMatchesContract( "/pages/{name}/references", source ); + final List< String > referredBy = new ArrayList<>(); + target.json().get( "referredBy" ).forEach( name -> referredBy.add( name.asString() ) ); + Assertions.assertEquals( List.of( "ApiRefSource" ), referredBy ); + final List< String > refersTo = new ArrayList<>(); + source.json().get( "refersTo" ).forEach( name -> refersTo.add( name.asString() ) ); + Assertions.assertEquals( List.of( "ApiRefNotWritten", "ApiRefTarget" ), refersTo ); + } + + @Test + void referencesOfAPageThatDoesNotExistAre404AndOfASecretPageAre401() throws Exception { + startEngine( null ); + engine.saveText( "ApiRefHidden", "[{ALLOW view Admin}] hidden" ); + + final Reply missing = call( requestTo( "/pages/ApiRefNone/references" ) ); + final Reply hidden = call( requestTo( "/pages/ApiRefHidden/references" ) ); + + assertMatchesContract( "/pages/{name}/references", missing ); + assertMatchesContract( "/pages/{name}/references", hidden ); + Assertions.assertEquals( 404, missing.status ); + Assertions.assertEquals( 401, hidden.status ); + } + + @Test + void htmlAnswersWithThePageRendered() throws Exception { + startEngine( null ); + engine.saveText( "ApiHtmlPage", "Some __bold__ text." ); + + final Reply reply = call( requestTo( "/pages/ApiHtmlPage/html" ) ); + + assertMatchesContract( "/pages/{name}/html", reply ); + Assertions.assertEquals( 200, reply.status ); + final JsonNode page = reply.json(); + Assertions.assertEquals( "ApiHtmlPage", page.get( "name" ).asString() ); + Assertions.assertTrue( page.get( "html" ).asString().contains( "bold" ), page.get( "html" ).asString() ); + } + + @Test + void htmlOfAPageThatDoesNotExistIs404AndOfASecretPageIs401() throws Exception { + startEngine( null ); + engine.saveText( "ApiHtmlHidden", "[{ALLOW view Admin}] hidden" ); + + final Reply missing = call( requestTo( "/pages/ApiHtmlNone/html" ) ); + final Reply hidden = call( requestTo( "/pages/ApiHtmlHidden/html" ) ); + + assertMatchesContract( "/pages/{name}/html", missing ); + assertMatchesContract( "/pages/{name}/html", hidden ); + Assertions.assertEquals( 404, missing.status ); + Assertions.assertEquals( 401, hidden.status ); + Assertions.assertFalse( hidden.body.toString().contains( "hidden" ) ); + } + + @Test + void aNameThatCouldLeaveTheDirectoryOfThePagesIsABadRequest() throws Exception { + startEngine( null ); + + for( final String name : new String[] { "..", "a..b", "a\\b", "a\u0000b", "a\nb" } ) { + for( final String suffix : new String[] { "", "/history", "/attachments" } ) { + final Reply reply = call( requestTo( "/pages/" + name + suffix ) ); + + assertMatchesContract( "/pages/{name}" + suffix, reply ); + Assertions.assertEquals( 400, reply.status, name + suffix ); + } + } + } + + @Test + void pagesWithoutANameIs404() throws Exception { + startEngine( null ); + + final Reply reply = call( requestTo( "/pages/" ) ); + + Assertions.assertEquals( 404, reply.status ); + } + + @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 ) { + startEngine( policy, initialIndexDelay, null ); + } + + private void startEngine( final String policy, final String initialIndexDelay, final String pageProvider ) { + 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( pageProvider != null ) { + props.setProperty( PageManager.PROP_PAGEPROVIDER, pageProvider ); + } + 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 ) { + return requestTo( "/search", parameters ); + } + + private HttpServletRequest requestTo( final String pathInfo, final String... parameters ) { + final HttpServletRequest request = HttpMockFactory.createHttpRequest( "/JSPWiki", "/api/v1" + pathInfo ); + Mockito.doReturn( "GET" ).when( request ).getMethod(); + Mockito.doReturn( pathInfo ).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 JsonNode value, final String where ) { + switch( String.valueOf( schema.get( "type" ) ) ) { + case "array": + Assertions.assertTrue( value.isArray(), where + " must be an array" ); + value.forEach( item -> assertMatchesSchema( resolve( schema.get( "items" ) ), item, where + "[]" ) ); + break; + case "object": + Assertions.assertTrue( value.isObject(), where + " must be an object" ); + final JsonNode object = value; + 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.propertyNames() ) { + 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.isString(), where + " must be a string" ); + break; + case "integer": + Assertions.assertTrue( value.isNumber() + && value.asDouble() == Math.rint( value.asDouble() ), 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 ); + } + + private static Set< String > names( final Reply reply ) { + final Set< String > names = new HashSet<>(); + reply.json().forEach( name -> names.add( name.asString() ) ); + return names; + } + + /** What the servlet wrote to a mock response. */ + private static final class Reply { + int status; + String contentType; + final StringWriter body = new StringWriter(); + + JsonNode json() { + return JSON.readTree( body.toString() ); + } + } + +} diff --git a/jspwiki-rest-api/src/test/resources/groupdatabase.xml b/jspwiki-rest-api/src/test/resources/groupdatabase.xml new file mode 100644 index 0000000000..0166d16ff8 --- /dev/null +++ b/jspwiki-rest-api/src/test/resources/groupdatabase.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/jspwiki-rest-api/src/test/resources/userdatabase.xml b/jspwiki-rest-api/src/test/resources/userdatabase.xml new file mode 100644 index 0000000000..5d095f88d1 --- /dev/null +++ b/jspwiki-rest-api/src/test/resources/userdatabase.xml @@ -0,0 +1,32 @@ + + + + + + rO0ABXNyABFqYXZhLnV0aWwuSGFzaE1hcAUH2sHDFmDRAwACRgAKbG9hZEZhY3RvckkACXRocmVzaG9sZHhwP0AAAAAAAAx3CAAAABAAAAACdAAKYXR0cmlidXRlMXQAEXNvbWUgcmFuZG9tIHZhbHVldAAKYXR0cmlidXRlMnQADWFub3RoZXIgdmFsdWV4 + + + + + + + + + diff --git a/jspwiki-war/pom.xml b/jspwiki-war/pom.xml index 2c0ec67cf8..ab65a3e02a 100644 --- a/jspwiki-war/pom.xml +++ b/jspwiki-war/pom.xml @@ -49,6 +49,12 @@ ${project.version} + + ${project.groupId} + jspwiki-rest-api + ${project.version} + + ${project.groupId} jspwiki-210-adapters diff --git a/jspwiki-war/src/main/webapp/WEB-INF/web.xml b/jspwiki-war/src/main/webapp/WEB-INF/web.xml index afce534d0d..454761b373 100644 --- a/jspwiki-war/src/main/webapp/WEB-INF/web.xml +++ b/jspwiki-war/src/main/webapp/WEB-INF/web.xml @@ -213,6 +213,12 @@ 1 + + + ApiV1Servlet + org.apache.wiki.rest.ApiV1Servlet + + ATOM @@ -251,6 +257,11 @@ /admin/ajax/* + + ApiV1Servlet + /api/v1/* + +