IndexFromXWiki.java

  1. package org.jbehave.core.io.rest.xwiki;

  2. import static java.text.MessageFormat.format;

  3. import java.util.Collection;
  4. import java.util.HashMap;
  5. import java.util.Map;

  6. import com.google.gson.Gson;
  7. import com.google.gson.JsonParser;
  8. import com.google.gson.reflect.TypeToken;

  9. import org.jbehave.core.io.rest.IndexWithBreadcrumbs;
  10. import org.jbehave.core.io.rest.RESTClient;
  11. import org.jbehave.core.io.rest.RESTClient.Type;
  12. import org.jbehave.core.io.rest.Resource;
  13. import org.jbehave.core.io.rest.ResourceNameResolver;

  14. /**
  15.  * Indexes resources from XWiki using the REST API
  16.  */
  17. public class IndexFromXWiki extends IndexWithBreadcrumbs {

  18.     private static final String INDEX_URI = "{0}?media=json";
  19.     private static final String PAGE_URI = "{0}/{1}";

  20.     public IndexFromXWiki() {
  21.         this(null, null);
  22.     }

  23.     public IndexFromXWiki(String username, String password) {
  24.         this(username, password, new ToLowerCase());
  25.     }

  26.     public IndexFromXWiki(String username, String password, ResourceNameResolver nameResolver) {
  27.         super(new RESTClient(Type.JSON, username, password), nameResolver);
  28.     }

  29.     @Override
  30.     protected Map<String, Resource> createIndexFromEntity(String rootURI, String entity) {
  31.         Collection<Page> pages = parse(entity);
  32.         Map<String, Resource> index = new HashMap<>();
  33.         for (Page page : pages) {
  34.             String parentName = (page.parent != null ? resolveName(page.parent) : null);
  35.             String uri = format(PAGE_URI, rootURI, page.name);
  36.             Resource resource = new Resource(uri, resolveName(page.name), parentName);
  37.             index.put(resource.getName(), resource);
  38.         }
  39.         return index;
  40.     }

  41.     @Override
  42.     protected String uri(String rootPath) {
  43.         return format(INDEX_URI, rootPath);
  44.     }

  45.     private Collection<Page> parse(String entity) {
  46.         Gson gson = new Gson();
  47.         return gson.fromJson(
  48.                 jsonMember(entity, "pageSummaries"),
  49.                 new TypeToken<Collection<Page>>() {
  50.                 }.getType());
  51.     }

  52.     private String jsonMember(String entity, String memberName) {
  53.         return new JsonParser().parse(entity).getAsJsonObject().get(memberName)
  54.                 .toString();
  55.     }

  56.     private static class Page {
  57.         private String name;
  58.         private String parent;
  59.     }

  60. }