Search in sources :

Example 1 with WebApiException

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);
        }
    }
}
Also used : XContentFactory(org.elasticsearch.common.xcontent.XContentFactory) FilterChain(javax.servlet.FilterChain) Constants(org.codelibs.fess.Constants) DocumentUtil(org.codelibs.fess.util.DocumentUtil) UserInfoHelper(org.codelibs.fess.helper.UserInfoHelper) URLDecoder(java.net.URLDecoder) FavoriteLogService(org.codelibs.fess.app.service.FavoriteLogService) ServletException(javax.servlet.ServletException) OptionalThing(org.dbflute.optional.OptionalThing) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) WebApiException(org.codelibs.fess.exception.WebApiException) ArrayList(java.util.ArrayList) GeoInfo(org.codelibs.fess.entity.GeoInfo) HttpServletRequest(javax.servlet.http.HttpServletRequest) SearchRequestType(org.codelibs.fess.entity.SearchRequestParams.SearchRequestType) FessConfig(org.codelibs.fess.mylasta.direction.FessConfig) PingResponse(org.codelibs.fess.entity.PingResponse) SearchRequestParams(org.codelibs.fess.entity.SearchRequestParams) Locale(java.util.Locale) PopularWordHelper(org.codelibs.fess.helper.PopularWordHelper) Map(java.util.Map) FacetInfo(org.codelibs.fess.entity.FacetInfo) SearchRenderData(org.codelibs.fess.entity.SearchRenderData) Field(org.codelibs.fess.util.FacetResponse.Field) Script(org.elasticsearch.script.Script) Logger(org.slf4j.Logger) FessEsClient(org.codelibs.fess.es.client.FessEsClient) HttpServletResponse(javax.servlet.http.HttpServletResponse) StringUtil(org.codelibs.core.lang.StringUtil) ToXContent(org.elasticsearch.common.xcontent.ToXContent) IOException(java.io.IOException) FacetResponse(org.codelibs.fess.util.FacetResponse) SearchService(org.codelibs.fess.app.service.SearchService) List(java.util.List) ComponentUtil(org.codelibs.fess.util.ComponentUtil) SystemHelper(org.codelibs.fess.helper.SystemHelper) LabelTypeHelper(org.codelibs.fess.helper.LabelTypeHelper) BaseJsonApiManager(org.codelibs.fess.api.BaseJsonApiManager) Script(org.elasticsearch.script.Script) FavoriteLogService(org.codelibs.fess.app.service.FavoriteLogService) FessConfig(org.codelibs.fess.mylasta.direction.FessConfig) WebApiException(org.codelibs.fess.exception.WebApiException) ServletException(javax.servlet.ServletException) WebApiException(org.codelibs.fess.exception.WebApiException) IOException(java.io.IOException) SystemHelper(org.codelibs.fess.helper.SystemHelper) UserInfoHelper(org.codelibs.fess.helper.UserInfoHelper) SearchService(org.codelibs.fess.app.service.SearchService) HashMap(java.util.HashMap) Map(java.util.Map)

Example 2 with WebApiException

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);
            }
        }
    });
}
Also used : FilterChain(javax.servlet.FilterChain) Constants(org.codelibs.fess.Constants) ServletException(javax.servlet.ServletException) FessSystemException(org.codelibs.fess.exception.FessSystemException) ServletInputStream(javax.servlet.ServletInputStream) BaseApiManager(org.codelibs.fess.api.BaseApiManager) LoggerFactory(org.slf4j.LoggerFactory) ClientAbortException(org.apache.catalina.connector.ClientAbortException) SessionManager(org.lastaflute.web.servlet.session.SessionManager) WebApiException(org.codelibs.fess.exception.WebApiException) FessUserBean(org.codelibs.fess.mylasta.action.FessUserBean) ResourceUtil(org.codelibs.fess.util.ResourceUtil) HttpServletRequest(javax.servlet.http.HttpServletRequest) RequestManager(org.lastaflute.web.servlet.request.RequestManager) ServletOutputStream(javax.servlet.ServletOutputStream) Locale(java.util.Locale) CopyUtil(org.codelibs.core.io.CopyUtil) Path(java.nio.file.Path) OutputStream(java.io.OutputStream) Logger(org.slf4j.Logger) Files(java.nio.file.Files) HttpServletResponse(javax.servlet.http.HttpServletResponse) StringUtil(org.codelibs.core.lang.StringUtil) IOException(java.io.IOException) UUID(java.util.UUID) ComponentUtil(org.codelibs.fess.util.ComponentUtil) CurlRequest(org.codelibs.elasticsearch.runner.net.CurlRequest) InputStream(java.io.InputStream) Method(org.codelibs.elasticsearch.runner.net.Curl.Method) ServletInputStream(javax.servlet.ServletInputStream) ServletOutputStream(javax.servlet.ServletOutputStream) ServletInputStream(javax.servlet.ServletInputStream) InputStream(java.io.InputStream) ServletOutputStream(javax.servlet.ServletOutputStream) OutputStream(java.io.OutputStream) CurlRequest(org.codelibs.elasticsearch.runner.net.CurlRequest) ClientAbortException(org.apache.catalina.connector.ClientAbortException) Method(org.codelibs.elasticsearch.runner.net.Curl.Method) IOException(java.io.IOException) WebApiException(org.codelibs.fess.exception.WebApiException) ServletException(javax.servlet.ServletException) FessSystemException(org.codelibs.fess.exception.FessSystemException) ClientAbortException(org.apache.catalina.connector.ClientAbortException) WebApiException(org.codelibs.fess.exception.WebApiException) IOException(java.io.IOException)

Example 3 with WebApiException

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);
        }
    }
}
Also used : Path(java.nio.file.Path) ServletOutputStream(javax.servlet.ServletOutputStream) ServletInputStream(javax.servlet.ServletInputStream) InputStream(java.io.InputStream) ClientAbortException(org.apache.catalina.connector.ClientAbortException) IOException(java.io.IOException) WebApiException(org.codelibs.fess.exception.WebApiException)

Example 4 with WebApiException

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);
}
Also used : PopularWordHelper(org.codelibs.fess.helper.PopularWordHelper) WebApiException(org.codelibs.fess.exception.WebApiException) ServletException(javax.servlet.ServletException) WebApiException(org.codelibs.fess.exception.WebApiException) IOException(java.io.IOException)

Example 5 with WebApiException

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);
}
Also used : FavoriteLogService(org.codelibs.fess.app.service.FavoriteLogService) ArrayList(java.util.ArrayList) FessConfig(org.codelibs.fess.mylasta.direction.FessConfig) WebApiException(org.codelibs.fess.exception.WebApiException) ServletException(javax.servlet.ServletException) WebApiException(org.codelibs.fess.exception.WebApiException) IOException(java.io.IOException) UserInfoHelper(org.codelibs.fess.helper.UserInfoHelper) SearchService(org.codelibs.fess.app.service.SearchService) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

IOException (java.io.IOException)5 WebApiException (org.codelibs.fess.exception.WebApiException)5 ServletException (javax.servlet.ServletException)4 InputStream (java.io.InputStream)2 Path (java.nio.file.Path)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 Locale (java.util.Locale)2 Map (java.util.Map)2 FilterChain (javax.servlet.FilterChain)2 ServletInputStream (javax.servlet.ServletInputStream)2 ServletOutputStream (javax.servlet.ServletOutputStream)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 ClientAbortException (org.apache.catalina.connector.ClientAbortException)2 StringUtil (org.codelibs.core.lang.StringUtil)2 Constants (org.codelibs.fess.Constants)2 FavoriteLogService (org.codelibs.fess.app.service.FavoriteLogService)2 SearchService (org.codelibs.fess.app.service.SearchService)2 PopularWordHelper (org.codelibs.fess.helper.PopularWordHelper)2