Search in sources :

Example 1 with CurlRequest

use of org.codelibs.curl.CurlRequest 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 ("/_plugin".equals(path) || path.startsWith("/_plugin/")) {
        processPluginRequest(request, response, path.replaceFirst("^/_plugin", StringUtil.EMPTY));
        return;
    }
    final Method httpMethod = Method.valueOf(request.getMethod().toUpperCase(Locale.ROOT));
    final CurlRequest curlRequest = ComponentUtil.getCurlHelper().request(httpMethod, path);
    final String contentType = request.getHeader("Content-Type");
    if (StringUtil.isNotEmpty(contentType)) {
        curlRequest.header("Content-Type", contentType);
    }
    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]);
        }
    });
    try (final CurlResponse curlResponse = curlRequest.onConnect((req, con) -> {
        con.setDoOutput(true);
        if (httpMethod != Method.GET && request.getContentLength() > 2) {
            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()) {
        try (ServletOutputStream out = response.getOutputStream();
            InputStream in = curlResponse.getContentAsStream()) {
            response.setStatus(curlResponse.getHttpStatusCode());
            writeHeaders(response);
            CopyUtil.copy(in, out);
        } catch (final ClientAbortException e) {
            logger.debug("Client aborts this request.", e);
        }
    } catch (final Exception e) {
        if (!(e.getCause() instanceof ClientAbortException)) {
            throw new WebApiException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
        }
        logger.debug("Client aborts this request.", 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) CurlRequest(org.codelibs.curl.CurlRequest) ClientAbortException(org.apache.catalina.connector.ClientAbortException) SessionManager(org.lastaflute.web.servlet.session.SessionManager) WebApiException(org.codelibs.fess.exception.WebApiException) Method(org.codelibs.curl.Curl.Method) 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) Files(java.nio.file.Files) HttpServletResponse(javax.servlet.http.HttpServletResponse) StringUtil(org.codelibs.core.lang.StringUtil) IOException(java.io.IOException) UUID(java.util.UUID) Logger(org.apache.logging.log4j.Logger) ComponentUtil(org.codelibs.fess.util.ComponentUtil) PostConstruct(javax.annotation.PostConstruct) LogManager(org.apache.logging.log4j.LogManager) CurlResponse(org.codelibs.curl.CurlResponse) InputStream(java.io.InputStream) CurlResponse(org.codelibs.curl.CurlResponse) ServletOutputStream(javax.servlet.ServletOutputStream) ServletInputStream(javax.servlet.ServletInputStream) InputStream(java.io.InputStream) ServletOutputStream(javax.servlet.ServletOutputStream) OutputStream(java.io.OutputStream) CurlRequest(org.codelibs.curl.CurlRequest) Method(org.codelibs.curl.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) ServletInputStream(javax.servlet.ServletInputStream) ClientAbortException(org.apache.catalina.connector.ClientAbortException)

Example 2 with CurlRequest

use of org.codelibs.curl.CurlRequest in project fess by codelibs.

the class PluginHelper method createCurlRequest.

protected CurlRequest createCurlRequest(final String url) {
    final CurlRequest request = Curl.get(url);
    final Proxy proxy = ComponentUtil.getFessConfig().getHttpProxy();
    if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) {
        request.proxy(proxy);
    }
    return request;
}
Also used : Proxy(java.net.Proxy) CurlRequest(org.codelibs.curl.CurlRequest)

Example 3 with CurlRequest

use of org.codelibs.curl.CurlRequest in project fess by codelibs.

the class CurlHelper method request.

public CurlRequest request(final Method method, final String path) {
    final CurlRequest request = new CurlRequest(method, ResourceUtil.getFesenHttpUrl() + path);
    final FessConfig fessConfig = ComponentUtil.getFessConfig();
    final String username = fessConfig.getElasticsearchUsername();
    final String password = fessConfig.getElasticsearchPassword();
    if (StringUtil.isNotBlank(username) && StringUtil.isNotBlank(password)) {
        final String value = username + ":" + password;
        final String basicAuth = "Basic " + java.util.Base64.getEncoder().encodeToString(value.getBytes(StandardCharsets.UTF_8));
        request.header("Authorization", basicAuth);
    }
    if (sslSocketFactory != null) {
        request.sslSocketFactory(sslSocketFactory);
    }
    return request;
}
Also used : CurlRequest(org.codelibs.curl.CurlRequest) FessConfig(org.codelibs.fess.mylasta.direction.FessConfig)

Example 4 with CurlRequest

use of org.codelibs.curl.CurlRequest in project fess by codelibs.

the class AdminEsreqAction method upload.

@Execute
@Secured({ ROLE })
public ActionResponse upload(final UploadForm form) {
    validate(form, messages -> {
    }, () -> asListHtml(null));
    verifyTokenKeep(() -> asListHtml(this::saveToken));
    String header = null;
    final StringBuilder buf = new StringBuilder(1000);
    try (final BufferedReader reader = new BufferedReader(new InputStreamReader(form.requestFile.getInputStream(), Constants.UTF_8))) {
        header = ReaderUtil.readLine(reader);
        if (header == null) {
            throwValidationError(messages -> messages.addErrorsInvalidHeaderForRequestFile(GLOBAL, "no header"), () -> asListHtml(this::saveToken));
            // no-op
            return redirect(getClass());
        }
        String line;
        while ((line = ReaderUtil.readLine(reader)) != null) {
            buf.append(line);
        }
    } catch (final Exception e) {
        throwValidationError(messages -> messages.addErrorsFailedToReadRequestFile(GLOBAL, e.getMessage()), () -> asListHtml(this::saveToken));
    }
    final CurlRequest curlRequest = getCurlRequest(header);
    if (curlRequest == null) {
        final String msg = header;
        throwValidationError(messages -> messages.addErrorsInvalidHeaderForRequestFile(GLOBAL, msg), () -> asListHtml(this::saveToken));
    } else {
        try (final CurlResponse response = curlRequest.body(buf.toString()).execute()) {
            final File tempFile = ComponentUtil.getSystemHelper().createTempFile("esreq_", ".json");
            try (final InputStream in = response.getContentAsStream()) {
                CopyUtil.copy(in, tempFile);
            } catch (final Exception e1) {
                if (tempFile != null && tempFile.exists() && !tempFile.delete()) {
                    logger.warn("Failed to delete {}", tempFile.getAbsolutePath());
                }
                throw e1;
            }
            return asStream("es_" + System.currentTimeMillis() + ".json").contentTypeOctetStream().stream(out -> {
                try (final InputStream in = new FileInputStream(tempFile)) {
                    out.write(in);
                } finally {
                    if (tempFile.exists() && !tempFile.delete()) {
                        logger.warn("Failed to delete {}", tempFile.getAbsolutePath());
                    }
                }
            });
        } catch (final Exception e) {
            logger.warn("Failed to process request file: {}", form.requestFile.getFileName(), e);
            throwValidationError(messages -> messages.addErrorsInvalidHeaderForRequestFile(GLOBAL, e.getMessage()), () -> asListHtml(this::saveToken));
        }
    }
    // no-op
    return redirect(getClass());
}
Also used : Constants(org.codelibs.fess.Constants) Secured(org.codelibs.fess.annotation.Secured) StringUtil(org.codelibs.core.lang.StringUtil) CurlRequest(org.codelibs.curl.CurlRequest) FileInputStream(java.io.FileInputStream) InputStreamReader(java.io.InputStreamReader) ActionRuntime(org.lastaflute.web.ruts.process.ActionRuntime) File(java.io.File) ActionResponse(org.lastaflute.web.response.ActionResponse) Logger(org.apache.logging.log4j.Logger) CurlHelper(org.codelibs.fess.helper.CurlHelper) ComponentUtil(org.codelibs.fess.util.ComponentUtil) Locale(java.util.Locale) FessAdminAction(org.codelibs.fess.app.web.base.FessAdminAction) Execute(org.lastaflute.web.Execute) BufferedReader(java.io.BufferedReader) CopyUtil(org.codelibs.core.io.CopyUtil) HtmlResponse(org.lastaflute.web.response.HtmlResponse) LogManager(org.apache.logging.log4j.LogManager) ReaderUtil(org.codelibs.core.io.ReaderUtil) CurlResponse(org.codelibs.curl.CurlResponse) InputStream(java.io.InputStream) InputStreamReader(java.io.InputStreamReader) CurlResponse(org.codelibs.curl.CurlResponse) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) BufferedReader(java.io.BufferedReader) CurlRequest(org.codelibs.curl.CurlRequest) File(java.io.File) FileInputStream(java.io.FileInputStream) Execute(org.lastaflute.web.Execute) Secured(org.codelibs.fess.annotation.Secured)

Aggregations

CurlRequest (org.codelibs.curl.CurlRequest)4 InputStream (java.io.InputStream)2 Locale (java.util.Locale)2 LogManager (org.apache.logging.log4j.LogManager)2 Logger (org.apache.logging.log4j.Logger)2 CopyUtil (org.codelibs.core.io.CopyUtil)2 StringUtil (org.codelibs.core.lang.StringUtil)2 CurlResponse (org.codelibs.curl.CurlResponse)2 Constants (org.codelibs.fess.Constants)2 ComponentUtil (org.codelibs.fess.util.ComponentUtil)2 BufferedReader (java.io.BufferedReader)1 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 IOException (java.io.IOException)1 InputStreamReader (java.io.InputStreamReader)1 OutputStream (java.io.OutputStream)1 Proxy (java.net.Proxy)1 Files (java.nio.file.Files)1 Path (java.nio.file.Path)1 UUID (java.util.UUID)1