001/**
002 * Copyright (C) 2014  Universidade de Aveiro, DETI/IEETA, Bioinformatics Group - http://bioinformatics.ua.pt/
003 *
004 * This file is part of Dicoogle/dicoogle.
005 *
006 * Dicoogle/dicoogle is free software: you can redistribute it and/or modify
007 * it under the terms of the GNU General Public License as published by
008 * the Free Software Foundation, either version 3 of the License, or
009 * (at your option) any later version.
010 *
011 * Dicoogle/dicoogle is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
014 * GNU General Public License for more details.
015 *
016 * You should have received a copy of the GNU General Public License
017 * along with Dicoogle.  If not, see <http://www.gnu.org/licenses/>.
018 */
019
020package pt.ua.dicoogle.server.web.servlets.management;
021
022import java.io.IOException;
023import java.lang.reflect.InvocationTargetException;
024import java.lang.reflect.Method;
025import java.lang.reflect.Modifier;
026import java.net.URI;
027import java.net.URISyntaxException;
028import java.util.ArrayList;
029import java.util.List;
030
031import javax.servlet.ServletException;
032import javax.servlet.http.HttpServlet;
033import javax.servlet.http.HttpServletRequest;
034import javax.servlet.http.HttpServletResponse;
035
036import net.sf.json.JSONObject;
037import org.slf4j.Logger;
038import org.slf4j.LoggerFactory;
039import pt.ua.dicoogle.plugins.PluginController;
040import pt.ua.dicoogle.sdk.datastructs.IndexReport;
041import pt.ua.dicoogle.sdk.datastructs.Report;
042import pt.ua.dicoogle.sdk.task.Task;
043
044/**
045 *
046 * @author Frederico Silva <fredericosilva@ua.pt>
047 */
048public class ForceIndexing extends HttpServlet {
049    
050    private static final Logger logger = LoggerFactory.getLogger(ForceIndexing.class);
051
052  /**
053   * 
054   */
055  private static final long serialVersionUID = 1L;
056
057  @Override
058  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
059      IOException {
060
061    // Getting Parameters.
062    String[] uris = req.getParameterValues("uri");
063    String[] pluginsName = req.getParameterValues("plugin");
064
065    if (uris == null) {
066      resp.sendError(400, "No uri provided");
067      return;
068    }
069
070    final PluginController pc = PluginController.getInstance();
071
072    int expectedReports = uris.length * ((pluginsName == null) ?
073            pc.getIndexingPlugins(true).size() :
074            pluginsName.length);
075    
076    //Firing Tasks.
077    List<Task<Report>> reports = new ArrayList<>(expectedReports);
078    for (String uri : uris) {
079        try {
080            URI u = new URI(uri.replaceAll(" ", "%20"));
081            // log.info("Sent Index Request: {}, {}",pluginName, u.toString());
082            if (pluginsName == null) {
083              reports.addAll(pc.index(u));
084            } else {
085              for (String pluginName : pluginsName) {
086                reports.addAll(pc.index(pluginName, u));
087              }
088            }
089        } catch (URISyntaxException ex) {
090            logger.debug("Client provided bad URI");
091            resp.sendError(400);
092            return;
093        }
094    }
095
096    // waiting is bad, clearing all this and giving an ok
097    resp.setStatus(200);
098    
099    /*
100    //Waiting for results, construct the output.
101    List<Report> done = new ArrayList<>(reports.size());
102    JSONArray ret = new JSONArray();
103    for (Task<Report> t : reports) {
104      try {
105        Report report = t.get();
106        done.add(report);
107        JSONObject obj;
108        if (report instanceof IndexReport) {
109            IndexReport indexReport = (IndexReport) report;
110            obj = convertReportToJSON(indexReport);
111        } else {
112            // no information is available
113            obj = new JSONObject();
114            obj.put("complete", true);
115            obj.put("errors", 0);
116        }
117        ret.add(obj);
118      } catch (InterruptedException | ExecutionException ex) {
119        // log.error("UNKNOW ERROR", ex);
120      }
121    }
122    // log.info("Finished forced indexing procedure: {}", reports.size());
123
124    resp.setContentType("application/json");
125    resp.getWriter().write(ret.toString());
126    resp.getWriter().flush();
127    */
128  }
129  
130  @Deprecated
131  private static JSONObject convertReportToJSON(IndexReport r){
132    JSONObject obj = new JSONObject();
133    obj.put("indexed", r.getNIndexed());
134    obj.put("errors", r.getNErrors());
135    obj.put("elapsedTime", r.getElapsedTime());
136    
137    JSONObject extraObjects = new JSONObject();
138    
139    Method[] methods = r.getClass().getDeclaredMethods();
140    for(Method m : methods){
141      if( Modifier.isPublic(m.getModifiers()) && m.getName().startsWith("get") && m.getParameterTypes().length == 0){
142        Object ret = null;
143        try {
144          ret = m.invoke(r, null);
145        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
146        }
147        if(ret != null)
148          extraObjects.put(m.getName().substring(3), ret);
149      }
150    }    
151    
152    obj.put("extra", extraObjects);
153    return obj;
154  }
155}