View Javadoc
1   /*
2    * Copyright 2012-2017 CodeLibs Project and the Others.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
15   */
16  package org.codelibs.fess.app.web.admin.esreq;
17  
18  import java.io.BufferedReader;
19  import java.io.File;
20  import java.io.FileInputStream;
21  import java.io.InputStream;
22  import java.io.InputStreamReader;
23  import java.util.Locale;
24  
25  import org.codelibs.core.io.CopyUtil;
26  import org.codelibs.core.io.ReaderUtil;
27  import org.codelibs.core.lang.StringUtil;
28  import org.codelibs.elasticsearch.runner.net.Curl;
29  import org.codelibs.elasticsearch.runner.net.CurlRequest;
30  import org.codelibs.elasticsearch.runner.net.CurlResponse;
31  import org.codelibs.fess.Constants;
32  import org.codelibs.fess.app.web.base.FessAdminAction;
33  import org.codelibs.fess.util.ResourceUtil;
34  import org.lastaflute.web.Execute;
35  import org.lastaflute.web.response.ActionResponse;
36  import org.lastaflute.web.response.HtmlResponse;
37  import org.lastaflute.web.ruts.process.ActionRuntime;
38  import org.slf4j.Logger;
39  import org.slf4j.LoggerFactory;
40  
41  /**
42   * @author shinsuke
43   */
44  public class AdminEsreqAction extends FessAdminAction {
45  
46      private static final Logger logger = LoggerFactory.getLogger(AdminEsreqAction.class);
47  
48      @Override
49      protected void setupHtmlData(final ActionRuntime runtime) {
50          super.setupHtmlData(runtime);
51          runtime.registerData("helpLink", systemHelper.getHelpLink(fessConfig.getOnlineHelpNameEsreq()));
52      }
53  
54      @Execute
55      public HtmlResponse index() {
56          return asListHtml(() -> saveToken());
57      }
58  
59      @Execute
60      public ActionResponse upload(final UploadForm form) {
61          validate(form, messages -> {}, () -> asListHtml(null));
62          verifyToken(() -> asListHtml(() -> saveToken()));
63  
64          String header = null;
65          final StringBuilder buf = new StringBuilder(1000);
66          try (final BufferedReader reader = new BufferedReader(new InputStreamReader(form.requestFile.getInputStream(), Constants.UTF_8))) {
67              header = ReaderUtil.readLine(reader);
68              String line;
69              while ((line = ReaderUtil.readLine(reader)) != null) {
70                  buf.append(line);
71              }
72          } catch (final Exception e) {
73              throwValidationError(messages -> messages.addErrorsFailedToReadRequestFile(GLOBAL, e.getMessage()), () -> {
74                  return asListHtml(() -> saveToken());
75              });
76          }
77  
78          final CurlRequest curlRequest = getCurlRequest(header);
79          if (curlRequest == null) {
80              final String msg = header;
81              throwValidationError(messages -> messages.addErrorsInvalidHeaderForRequestFile(GLOBAL, msg), () -> {
82                  return asListHtml(() -> saveToken());
83              });
84          } else {
85              try (final CurlResponse response = curlRequest.header("Content-Type", "application/json").body(buf.toString()).execute()) {
86                  final File tempFile = File.createTempFile("esreq_", ".json");
87                  try (final InputStream in = response.getContentAsStream()) {
88                      CopyUtil.copy(in, tempFile);
89                  } catch (final Exception e1) {
90                      if (tempFile != null && tempFile.exists() && !tempFile.delete()) {
91                          logger.warn("Failed to delete " + tempFile.getAbsolutePath());
92                      }
93                      throw e1;
94                  }
95                  return asStream("es_" + System.currentTimeMillis() + ".json").contentTypeOctetStream().stream(out -> {
96                      try (final InputStream in = new FileInputStream(tempFile)) {
97                          out.write(in);
98                      } finally {
99                          if (tempFile.exists() && !tempFile.delete()) {
100                             logger.warn("Failed to delete " + tempFile.getAbsolutePath());
101                         }
102                     }
103                 });
104             } catch (final Exception e) {
105                 logger.warn("Failed to process request file: " + form.requestFile.getFileName(), e);
106                 throwValidationError(messages -> messages.addErrorsInvalidHeaderForRequestFile(GLOBAL, e.getMessage()), () -> {
107                     return asListHtml(() -> saveToken());
108                 });
109             }
110         }
111         return redirect(getClass()); // no-op
112     }
113 
114     private CurlRequest getCurlRequest(final String header) {
115         if (StringUtil.isBlank(header)) {
116             return null;
117         }
118 
119         final String[] values = header.split(" ");
120         if (values.length != 2) {
121             return null;
122         }
123 
124         final String url;
125         if (values[1].startsWith("/")) {
126             url = ResourceUtil.getElasticsearchHttpUrl() + values[1];
127         } else {
128             url = ResourceUtil.getElasticsearchHttpUrl() + "/" + values[1];
129         }
130 
131         switch (values[0].toUpperCase(Locale.ROOT)) {
132         case "GET":
133             return Curl.get(url);
134         case "POST":
135             return Curl.post(url);
136         case "PUT":
137             return Curl.put(url);
138         case "DELETE":
139             return Curl.delete(url);
140         default:
141             break;
142         }
143         return null;
144     }
145 
146     private HtmlResponse asListHtml(final Runnable runnable) {
147         if (runnable != null) {
148             runnable.run();
149         }
150         return asHtml(path_AdminEsreq_AdminEsreqJsp).useForm(UploadForm.class);
151     }
152 
153 }