use of org.codelibs.fess.suggest.entity.SuggestItem in project fess by codelibs.
the class SuggestApiManager method process.
@Override
public void process(final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain) throws IOException, ServletException {
int status = 0;
String errMsg = StringUtil.EMPTY;
// TODO replace response stream
final StringBuilder buf = new StringBuilder(255);
final RoleQueryHelper roleQueryHelper = ComponentUtil.getRoleQueryHelper();
final SearchService searchService = ComponentUtil.getComponent(SearchService.class);
try {
final RequestParameter parameter = RequestParameter.parse(request);
final String[] langs = searchService.getLanguages(request, parameter);
final SuggestHelper suggestHelper = ComponentUtil.getSuggestHelper();
final SuggestRequestBuilder builder = suggestHelper.suggester().suggest();
builder.setQuery(parameter.getQuery());
stream(parameter.getSuggestFields()).of(stream -> stream.forEach(builder::addField));
roleQueryHelper.build(SearchRequestType.SUGGEST).stream().forEach(builder::addRole);
builder.setSize(parameter.getNum());
stream(langs).of(stream -> stream.forEach(builder::addLang));
builder.addKind(SuggestItem.Kind.USER.toString());
if (ComponentUtil.getFessConfig().isSuggestSearchLog()) {
builder.addKind(SuggestItem.Kind.QUERY.toString());
}
if (ComponentUtil.getFessConfig().isSuggestDocuments()) {
builder.addKind(SuggestItem.Kind.DOCUMENT.toString());
}
final SuggestResponse suggestResponse = builder.execute().getResponse();
buf.append("\"result\":{");
buf.append("\"took\":\"").append(suggestResponse.getTookMs()).append('\"');
buf.append(",\"total\":\"").append(suggestResponse.getTotal()).append('\"');
buf.append(",\"num\":\"").append(suggestResponse.getNum()).append('\"');
if (!suggestResponse.getItems().isEmpty()) {
buf.append(",\"hits\":[");
boolean first = true;
for (final SuggestItem item : suggestResponse.getItems()) {
if (!first) {
buf.append(',');
}
first = false;
buf.append("{\"text\":\"").append(StringEscapeUtils.escapeJson(item.getText())).append('\"');
buf.append(",\"tags\":[");
for (int i = 0; i < item.getTags().length; i++) {
if (i > 0) {
buf.append(',');
}
buf.append('\"').append(StringEscapeUtils.escapeJson(item.getTags()[i])).append('\"');
}
buf.append(']');
buf.append('}');
}
buf.append(']');
}
buf.append('}');
} catch (final Exception e) {
status = 1;
errMsg = e.getMessage();
if (errMsg == null) {
errMsg = e.getClass().getName();
}
if (logger.isDebugEnabled()) {
logger.debug("Failed to process a suggest request.", e);
}
if (e instanceof InvalidAccessTokenException) {
final InvalidAccessTokenException iate = (InvalidAccessTokenException) e;
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", "Bearer error=\"" + iate.getType() + "\"");
}
}
writeJsonResponse(status, buf.toString(), errMsg);
}
Aggregations