use of org.codelibs.fess.exception.WebApiException in project fess by codelibs.
the class JsonApiManager method processFavoriteRequest.
protected void processFavoriteRequest(final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain) {
if (!ComponentUtil.getFessConfig().isUserFavorite()) {
writeJsonResponse(9, null, "Unsupported operation.");
return;
}
final FessConfig fessConfig = ComponentUtil.getFessConfig();
final UserInfoHelper userInfoHelper = ComponentUtil.getUserInfoHelper();
final SearchService searchService = ComponentUtil.getComponent(SearchService.class);
final FavoriteLogService favoriteLogService = ComponentUtil.getComponent(FavoriteLogService.class);
final SystemHelper systemHelper = ComponentUtil.getSystemHelper();
try {
final String docId = request.getParameter("docId");
final String queryId = request.getParameter("queryId");
final String[] docIds = userInfoHelper.getResultDocIds(URLDecoder.decode(queryId, Constants.UTF_8));
if (docIds == null) {
throw new WebApiException(6, "No searched urls.");
}
searchService.getDocumentByDocId(docId, new String[] { fessConfig.getIndexFieldUrl() }, OptionalThing.empty()).ifPresent(doc -> {
final String favoriteUrl = DocumentUtil.getValue(doc, fessConfig.getIndexFieldUrl(), String.class);
final String userCode = userInfoHelper.getUserCode();
if (StringUtil.isBlank(userCode)) {
throw new WebApiException(2, "No user session.");
} else if (StringUtil.isBlank(favoriteUrl)) {
throw new WebApiException(2, "URL is null.");
}
boolean found = false;
for (final String id : docIds) {
if (docId.equals(id)) {
found = true;
break;
}
}
if (!found) {
throw new WebApiException(5, "Not found: " + favoriteUrl);
}
if (!favoriteLogService.addUrl(userCode, (userInfo, favoriteLog) -> {
favoriteLog.setUserInfoId(userInfo.getId());
favoriteLog.setUrl(favoriteUrl);
favoriteLog.setDocId(docId);
favoriteLog.setQueryId(queryId);
favoriteLog.setCreatedAt(systemHelper.getCurrentTimeAsLocalDateTime());
})) {
throw new WebApiException(4, "Failed to add url: " + favoriteUrl);
}
final String id = DocumentUtil.getValue(doc, fessConfig.getIndexFieldId(), String.class);
searchService.update(id, builder -> {
final Script script = new Script("ctx._source." + fessConfig.getIndexFieldFavoriteCount() + "+=1");
builder.setScript(script);
final Map<String, Object> upsertMap = new HashMap<>();
upsertMap.put(fessConfig.getIndexFieldFavoriteCount(), 1);
builder.setUpsert(upsertMap);
builder.setRefreshPolicy(Constants.TRUE);
});
writeJsonResponse(0, "\"result\":\"ok\"", (String) null);
}).orElse(() -> {
throw new WebApiException(6, "Not found: " + docId);
});
} catch (final Exception e) {
int status;
if (e instanceof WebApiException) {
status = ((WebApiException) e).getStatusCode();
} else {
status = 1;
}
writeJsonResponse(status, null, e);
if (logger.isDebugEnabled()) {
logger.debug("Failed to process a favorite request.", e);
}
}
}
use of org.codelibs.fess.exception.WebApiException in project fess by codelibs.
the class EsApiManager method processRequest.
protected void processRequest(final HttpServletRequest request, final HttpServletResponse response, final String path) {
if (StringUtil.isNotBlank(path)) {
final String lowerPath = path.toLowerCase(Locale.ROOT);
if (lowerPath.endsWith(".html")) {
response.setContentType("text/html;charset=utf-8");
} else if (lowerPath.endsWith(".txt")) {
response.setContentType("text/plain");
} else if (lowerPath.endsWith(".css")) {
response.setContentType("text/css");
}
}
if (path.startsWith("/_plugin/") || path.equals("/_plugin")) {
processPluginRequest(request, response, path.replaceFirst("^/_plugin", StringUtil.EMPTY));
return;
}
final Method httpMethod = Method.valueOf(request.getMethod().toUpperCase(Locale.ROOT));
final CurlRequest curlRequest = new CurlRequest(httpMethod, ResourceUtil.getElasticsearchHttpUrl() + path);
request.getParameterMap().entrySet().stream().forEach(entry -> {
if (entry.getValue().length > 1) {
curlRequest.param(entry.getKey(), String.join(",", entry.getValue()));
} else if (entry.getValue().length == 1) {
curlRequest.param(entry.getKey(), entry.getValue()[0]);
}
});
curlRequest.onConnect((req, con) -> {
con.setDoOutput(true);
if (httpMethod != Method.GET) {
try (ServletInputStream in = request.getInputStream();
OutputStream out = con.getOutputStream()) {
CopyUtil.copy(in, out);
} catch (final IOException e) {
throw new WebApiException(HttpServletResponse.SC_BAD_REQUEST, e);
}
}
}).execute(con -> {
try (ServletOutputStream out = response.getOutputStream()) {
try (InputStream in = con.getInputStream()) {
response.setStatus(con.getResponseCode());
CopyUtil.copy(in, out);
} catch (final Exception e) {
response.setStatus(con.getResponseCode());
try (InputStream err = con.getErrorStream()) {
CopyUtil.copy(err, out);
}
}
} catch (final ClientAbortException e) {
logger.debug("Client aborts this request.", e);
} catch (final Exception e) {
if (e.getCause() instanceof ClientAbortException) {
logger.debug("Client aborts this request.", e);
} else {
throw new WebApiException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
}
}
});
}
use of org.codelibs.fess.exception.WebApiException in project fess by codelibs.
the class EsApiManager method processPluginRequest.
private void processPluginRequest(final HttpServletRequest request, final HttpServletResponse response, final String path) {
Path filePath = ResourceUtil.getSitePath(path.replaceAll("\\.\\.+", StringUtil.EMPTY).replaceAll("/+", "/").split("/"));
if (Files.isDirectory(filePath)) {
filePath = filePath.resolve("index.html");
}
if (Files.exists(filePath)) {
try (InputStream in = Files.newInputStream(filePath);
ServletOutputStream out = response.getOutputStream()) {
response.setStatus(HttpServletResponse.SC_OK);
CopyUtil.copy(in, out);
} catch (final ClientAbortException e) {
logger.debug("Client aborts this request.", e);
} catch (final IOException e) {
logger.error("Failed to read " + path + " from " + filePath);
throw new WebApiException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
}
} else {
try {
response.sendError(HttpServletResponse.SC_NOT_FOUND, path + " is not found.");
} catch (final ClientAbortException e) {
logger.debug("Client aborts this request.", e);
} catch (final IOException e) {
logger.error("Failed to read " + path + " from " + filePath);
throw new WebApiException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
}
}
}
use of org.codelibs.fess.exception.WebApiException in project fess by codelibs.
the class JsonApiManager method processPopularWordRequest.
protected void processPopularWordRequest(final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain) {
if (!ComponentUtil.getFessConfig().isWebApiPopularWord()) {
writeJsonResponse(9, null, "Unsupported operation.");
return;
}
final String seed = request.getParameter("seed");
final String[] tags = request.getParameterValues("labels");
final String[] fields = request.getParameterValues("fields");
// TODO
final String[] excludes = StringUtil.EMPTY_STRINGS;
final PopularWordHelper popularWordHelper = ComponentUtil.getPopularWordHelper();
int status = 0;
Exception err = null;
// TODO replace response stream
final StringBuilder buf = new StringBuilder(255);
try {
final List<String> popularWordList = popularWordHelper.getWordList(SearchRequestType.JSON, seed, tags, null, fields, excludes);
buf.append("\"result\":[");
boolean first1 = true;
for (final String word : popularWordList) {
if (!first1) {
buf.append(',');
} else {
first1 = false;
}
buf.append(escapeJson(word));
}
buf.append(']');
} catch (final Exception e) {
if (e instanceof WebApiException) {
status = ((WebApiException) e).getStatusCode();
} else {
status = 1;
}
err = e;
if (logger.isDebugEnabled()) {
logger.debug("Failed to process a popularWord request.", e);
}
}
writeJsonResponse(status, buf.toString(), err);
}
use of org.codelibs.fess.exception.WebApiException in project fess by codelibs.
the class JsonApiManager method processFavoritesRequest.
protected void processFavoritesRequest(final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain) {
if (!ComponentUtil.getFessConfig().isUserFavorite()) {
writeJsonResponse(9, null, "Unsupported operation.");
return;
}
final UserInfoHelper userInfoHelper = ComponentUtil.getUserInfoHelper();
final FessConfig fessConfig = ComponentUtil.getFessConfig();
final SearchService searchService = ComponentUtil.getComponent(SearchService.class);
final FavoriteLogService favoriteLogService = ComponentUtil.getComponent(FavoriteLogService.class);
int status = 0;
String body = null;
Exception err = null;
try {
final String queryId = request.getParameter("queryId");
final String userCode = userInfoHelper.getUserCode();
if (StringUtil.isBlank(userCode)) {
throw new WebApiException(2, "No user session.");
} else if (StringUtil.isBlank(queryId)) {
throw new WebApiException(3, "Query ID is null.");
}
final String[] docIds = userInfoHelper.getResultDocIds(queryId);
final List<Map<String, Object>> docList = searchService.getDocumentListByDocIds(docIds, new String[] { fessConfig.getIndexFieldUrl(), fessConfig.getIndexFieldDocId(), fessConfig.getIndexFieldFavoriteCount() }, OptionalThing.empty(), SearchRequestType.JSON);
List<String> urlList = new ArrayList<>(docList.size());
for (final Map<String, Object> doc : docList) {
final String urlObj = DocumentUtil.getValue(doc, fessConfig.getIndexFieldUrl(), String.class);
if (urlObj != null) {
urlList.add(urlObj);
}
}
urlList = favoriteLogService.getUrlList(userCode, urlList);
final List<String> docIdList = new ArrayList<>(urlList.size());
for (final Map<String, Object> doc : docList) {
final String urlObj = DocumentUtil.getValue(doc, fessConfig.getIndexFieldUrl(), String.class);
if (urlObj != null && urlList.contains(urlObj)) {
final String docIdObj = DocumentUtil.getValue(doc, fessConfig.getIndexFieldDocId(), String.class);
if (docIdObj != null) {
docIdList.add(docIdObj);
}
}
}
// TODO replace response stream
final StringBuilder buf = new StringBuilder(255);
buf.append("\"num\":").append(docIdList.size());
if (!docIdList.isEmpty()) {
buf.append(", \"doc_ids\":[");
for (int i = 0; i < docIdList.size(); i++) {
if (i > 0) {
buf.append(',');
}
buf.append(escapeJson(docIdList.get(i)));
}
buf.append(']');
}
body = buf.toString();
} catch (final Exception e) {
if (e instanceof WebApiException) {
status = ((WebApiException) e).getStatusCode();
} else {
status = 1;
}
err = e;
if (logger.isDebugEnabled()) {
logger.debug("Failed to process a favorites request.", e);
}
}
writeJsonResponse(status, body, err);
}
Aggregations