package com.github.rnewson.couchdb.lucene;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.lucene.index.IndexWriter;

import com.github.rnewson.couchdb.lucene.LuceneGateway.WriterCallback;

/**
 * Administrative functions.
 * 
 * <ul>
 * <li>_expunge
 * <li>_optimize
 * <li>_pause
 * <li>_resume
 * </ul>
 * 
 * @author rnewson
 * 
 */
public final class AdminServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    private final State state;

    AdminServlet(final State state) {
        this.state = state;
    }

    @Override
    protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
        final ViewSignature sig = state.locator.lookup(req);
        if (sig == null) {
            resp.sendError(400, "Invalid path.");
            return;
        }

        if ("/_expunge".equals(req.getPathInfo())) {
            state.lucene.withWriter(sig, new WriterCallback<Void>() {
                public Void callback(final IndexWriter writer) throws IOException {
                    writer.expungeDeletes(false);
                    return null;
                }
            });
            resp.setStatus(202);
            return;
        }

        if ("/_optimize".equals(req.getPathInfo())) {
            state.lucene.withWriter(sig, new WriterCallback<Void>() {
                public Void callback(final IndexWriter writer) throws IOException {
                    writer.optimize(false);
                    return null;
                }
            });
            resp.setStatus(202);
            return;
        }

        resp.sendError(400);
    }

}

@@ -1018,32 +1018,89 @@
 urn;%0A        %7D%0A%0A
+        final String command = req.getParameter(%22cmd%22);%0A%0A
         if (%22/_e
@@ -1096,18 +1096,16 @@
    if (%22
-/_
 expunge%22
@@ -1112,33 +1112,23 @@
 .equals(
-req.getPathInfo()
+command
 )) %7B%0A   
@@ -1476,10 +1476,8 @@
 f (%22
-/_
 opti
@@ -1493,25 +1493,15 @@
 als(
-req.getPathInfo()
+command
 )) %7B
@@ -1822,32 +1822,32 @@
 urn;%0A        %7D%0A%0A
-
         resp.sen
@@ -1856,16 +1856,31 @@
 rror(400
+, %22Bad request%22
 );%0A    %7D

fix admin servlet.