/*******************************************************************************
* Copyright (c) 2013, Perforce Software
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package com.perforce.search.controller;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.perforce.p4java.extension.exception.ServerAccessException;
import com.perforce.p4java.extension.exception.ServerConnectionException;
import com.perforce.p4java.extension.exception.ServerErrorException;
import com.perforce.p4java.extension.operation.FilesCommand;
import com.perforce.p4java.extension.path.PathStringFormat;
import com.perforce.p4java.extension.path.PerforcePathFactory;
import com.perforce.p4java.extension.server.PerforcePrincipalCredential;
import com.perforce.p4java.extension.server.Server;
import com.perforce.search.configuration.Configuration;
import com.perforce.search.exception.ErrorModelException;
import com.perforce.search.manager.SchemaKey;
import com.perforce.search.manager.SearchIndexManager;
import com.perforce.search.model.FilesModel;
import com.perforce.search.model.SearchModel;
import com.perforce.search.model.SearchModel.ResultFormat;
import com.perforce.search.model.SearchModel.SearchType;
import com.perforce.search.model.impl.ErrorModel;
import com.perforce.search.model.impl.ErrorModels;
import com.perforce.search.model.impl.FilesModelImpl;
import com.perforce.search.model.impl.SearchModelImpl;
import com.perforce.search.server.ServerConnectionPoolFacade;
@Controller
@RequestMapping("/api")
public class SearchController {
private static final Logger log = Logger.getLogger(SearchController.class);
// private Configuration config;
private SearchIndexManager searchIndexManager = null;
private ServerConnectionPoolFacade pool;
public SearchController(final Configuration config,
final SearchIndexManager searchIndexManager,
final ServerConnectionPoolFacade pool) {
// this.config = config;
this.searchIndexManager = searchIndexManager;
this.pool = pool;
}
private static ModelAndView errorModel(final ErrorModel error) {
return ResponseBuilder.buildResponse(error);
}
private static void addCORSHeader(final HttpServletRequest request,
final HttpServletResponse response) {
if (request.getHeader("Origin") != null) {
response.addHeader("Access-Control-Allow-Origin",
request.getHeader("Origin"));
}
}
/**
* Search via GET request, not recommended
*
* @param request
* @param response
* @param query
* - raw query string
* @param path
* - limit search to this path
* @param userId
* - userID to filter by
* @param ticket
* - password or p4 issued ticket (p4 login -h -p)
* @param pathparts
* - limit results to files that had these words in their path
*
* @return
*/
@RequestMapping(value = "/search", method = RequestMethod.GET)
public ModelAndView search(
final HttpServletRequest request,
final HttpServletResponse response,
@RequestParam(value = "query", required = true) final String query,
@RequestParam(value = "path", required = false) final String pathOrig,
@RequestParam(value = "user", required = true) final String userId,
@RequestParam(value = "ticket", required = false) final String ticket,
@RequestParam(value = "searchType", required = false) final String searchTypeOrig,
@RequestParam(value = "format", required = false) final String formatOrig) {
Server server = null;
try {
// allow CORS requests
addCORSHeader(request, response);
server = pool.acquireTicketed(PerforcePrincipalCredential
.createUser(userId, ticket));
List<String> paths = new ArrayList<String>();
String path = pathOrig;
if (path == null || path.length() == 0) {
path = "//...";
}
String searchType = searchTypeOrig;
if (searchType == null || searchType.length() == 0) {
searchType = SearchType.SIMPLE.toString();
}
String format = formatOrig;
if (format == null || format.length() == 0) {
format = ResultFormat.SIMPLE.toString();
}
paths.add(path);
SearchModelImpl searchModel = new SearchModelImpl();
searchModel.setQuery(query);
searchModel.setPaths(paths);
searchModel.setUserId(userId);
searchModel.setTicket(ticket);
searchModel.setSearchType(SearchType.valueOf(searchType));
searchModel.setResultFormat(ResultFormat.valueOf(format));
searchModel.addHeadRevisionField();
return search(searchModel, server);
} catch (ServerConnectionException e) {
log.error("Error running search", e);
return errorModel(ErrorModels.Error_ConnectionException);
} catch (ServerAccessException e) {
log.error("Error running search", e);
return errorModel(ErrorModels.Error_AccessException);
} catch (ServerErrorException e) {
log.error("Error running search", e);
return errorModel(ErrorModels.Error_ServerErrorException);
} finally {
pool.release(server);
}
}
/**
* Search via POST request of the searchModel
*
* @param request
* @param response
* @param searchModel
* @return
*/
@RequestMapping(value = "/search", method = RequestMethod.POST)
public ModelAndView search(final HttpServletRequest request,
final HttpServletResponse response,
@RequestBody final SearchModel searchModel) {
Server server = null;
try {
// allow CORS requests
addCORSHeader(request, response);
SearchModelImpl.validate(searchModel);
SearchModelImpl modelImpl = new SearchModelImpl(searchModel);
modelImpl.addHeadRevisionField();
server = pool.acquireTicketed(PerforcePrincipalCredential
.createUser(modelImpl.getUserId(), modelImpl.getTicket()));
// paths should be at least one (e.g. //...)
return search(modelImpl, server);
} catch (ServerConnectionException e) {
log.error("Error running search", e);
return errorModel(ErrorModels.Error_ConnectionException);
} catch (ServerAccessException e) {
log.error("Error running search", e);
return errorModel(ErrorModels.Error_AccessException);
} catch (ServerErrorException e) {
log.error("Error running search", e);
return errorModel(ErrorModels.Error_ServerErrorException);
} catch (ErrorModelException e) {
log.error("Error running search", e);
return errorModel(e.getError());
} catch (Exception e) {
log.error("Error running search", e);
return errorModel(ErrorModels.Error_Generic);
} finally {
pool.release(server);
}
}
/**
* Search via POST request, but the authentication was already handled by
* spring
*
* @param request
* @param response
* @param searchModel
* @return
*/
@RequestMapping(value = "/auth-search", method = RequestMethod.POST)
public ModelAndView authorizedSearch(final HttpServletRequest request,
final HttpServletResponse response,
@RequestBody final SearchModel searchModel) {
Server server = null;
try {
// allow CORS requests
addCORSHeader(request, response);
Authentication auth = SecurityContextHolder.getContext()
.getAuthentication();
SearchModelImpl fullmodel = new SearchModelImpl(searchModel);
fullmodel.setUserId(auth.getName());
fullmodel.setTicket((String) auth.getCredentials());
SearchModelImpl.validate(fullmodel);
fullmodel.addHeadRevisionField();
server = pool.acquireTicketed(PerforcePrincipalCredential
.createUser(fullmodel.getUserId(), fullmodel.getTicket()));
// paths should be at least one (e.g. //...)
return search(fullmodel, server);
} catch (ServerConnectionException e) {
log.error("Error running search", e);
return errorModel(ErrorModels.Error_ConnectionException);
} catch (ServerAccessException e) {
log.error("Error running search", e);
return errorModel(ErrorModels.Error_AccessException);
} catch (ServerErrorException e) {
log.error("Error running search", e);
return errorModel(ErrorModels.Error_ServerErrorException);
} catch (ErrorModelException e) {
log.error("Error running search", e);
return errorModel(e.getError());
} catch (Exception e) {
log.error("Error running search", e);
return errorModel(ErrorModels.Error_Generic);
} finally {
pool.release(server);
}
}
/**
* Commons will send a HEAD request on startup, just respond with "OK"
*
* @param request
* @param resp
* @return
*/
@RequestMapping(value = "/search", method = RequestMethod.HEAD)
public ModelAndView searchCommonsHead(final HttpServletRequest request,
final HttpServletResponse response) {
// allow CORS requests
addCORSHeader(request, response);
return errorModel(ErrorModels.Error_OK);
}
private ModelAndView search(final SearchModel searchModel,
final Server server) throws ServerConnectionException,
ServerAccessException, ServerErrorException {
// run the index search
// TODO: add fl keys to limit to what we need
QueryResponse response = searchIndexManager.searchForFiles(
searchModel.getQueryProcessed(), searchModel.getRowCount(),
searchModel.getStartRow());
SolrDocumentList list = response.getResults();
// convert the paths to PerforcePaths
final List<String> escapedPaths = new ArrayList<String>();
// when every revision is indexed, the ID ends with #NN, so don't escape
// that by using PerforcePathFactory (?)
for (SolrDocument d : list) {
escapedPaths.add(PerforcePathFactory.getPath(
(String) d.getFieldValue(SchemaKey.ID)).asString(
EnumSet.of(PathStringFormat.ESCAPE)));
}
// run p4 -u uid -P ticket files {result files} to get only the
// files available for the user
Map<String, Object>[] filesMap = FilesCommand.listFilesToMap(
escapedPaths, server);
List<FilesModel> filesList = new ArrayList<FilesModel>();
for (Map<String, Object> map : filesMap) {
// code0 is an error condition
if (map.containsKey(FilesCommand.tagErrorCode)) {
continue;
}
if (!map.containsKey(FilesCommand.tagDepotFile)) {
continue;
}
if (FilesCommand.tagAppleType.equals((String) map
.get(FilesCommand.tagType))) {
continue;
}
// return depotFile/rev/change/action/type/time
filesList.add(new FilesModelImpl(map));
}
if (searchModel.getResultFormat() == SearchModel.ResultFormat.SIMPLE) {
return ResponseBuilder.buildResponse(filesList);
} else {
// TODO:
// return:
// status : {code:..., message: }
// data : {
// files: [ ... ],
// found: NNNN,
// raw_results: { Solr JSON },
// rows: { start: NNNN, count: NNNN }
// }
// TODO: return more data, make the SIMPLE case a subset: data: {
// files: [ ... ] }
// long found = response.getResults().getNumFound();
// long start = response.getResults().getStart();
// long count = list.size();
return ResponseBuilder.buildResponse(filesList);
}
}
/**
* Simple API call to retrieve indexed search fields
*
*/
@RequestMapping(value = "/search-fields", method = RequestMethod.GET)
public ModelAndView getSearchFields(final HttpServletRequest request,
final HttpServletResponse response) {
// allow CORS requests
addCORSHeader(request, response);
return ResponseBuilder.buildResponse(searchIndexManager
.getSearchFields());
}
}