View Javadoc
1   /*
2    * Copyright 2012-2021 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.apache.logging.log4j.LogManager;
26  import org.apache.logging.log4j.Logger;
27  import org.codelibs.core.io.CopyUtil;
28  import org.codelibs.core.io.ReaderUtil;
29  import org.codelibs.core.lang.StringUtil;
30  import org.codelibs.curl.CurlRequest;
31  import org.codelibs.curl.CurlResponse;
32  import org.codelibs.fess.Constants;
33  import org.codelibs.fess.annotation.Secured;
34  import org.codelibs.fess.app.web.base.FessAdminAction;
35  import org.codelibs.fess.helper.CurlHelper;
36  import org.codelibs.fess.util.ComponentUtil;
37  import org.lastaflute.web.Execute;
38  import org.lastaflute.web.response.ActionResponse;
39  import org.lastaflute.web.response.HtmlResponse;
40  import org.lastaflute.web.ruts.process.ActionRuntime;
41  
42  /**
43   * @author shinsuke
44   */
45  public class AdminEsreqAction extends FessAdminAction {
46  
47      public static final String ROLE = "admin-esreq";
48  
49      private static final Logger logger = LogManager.getLogger(AdminEsreqAction.class);
50  
51      @Override
52      protected void setupHtmlData(final ActionRuntime runtime) {
53          super.setupHtmlData(runtime);
54          runtime.registerData("helpLink", systemHelper.getHelpLink(fessConfig.getOnlineHelpNameEsreq()));
55      }
56  
57      @Override
58      protected String getActionRole() {
59          return ROLE;
60      }
61  
62      @Execute
63      @Secured({ ROLE, ROLE + VIEW })
64      public HtmlResponse index() {
65          return asListHtml(this::saveToken);
66      }
67  
68      @Execute
69      @Secured({ ROLE })
70      public ActionResponse upload(final UploadForm form) {
71          validate(form, messages -> {}, () -> asListHtml(null));
72          verifyTokenKeep(() -> asListHtml(this::saveToken));
73  
74          String header = null;
75          final StringBuilder buf = new StringBuilder(1000);
76          try (final BufferedReader reader = new BufferedReader(new InputStreamReader(form.requestFile.getInputStream(), Constants.UTF_8))) {
77              header = ReaderUtil.readLine(reader);
78              if (header == null) {
79                  throwValidationError(messages -> messages.addErrorsInvalidHeaderForRequestFile(GLOBAL, "no header"),
80                          () -> asListHtml(this::saveToken));
81                  return redirect(getClass()); // no-op
82              }
83              String line;
84              while ((line = ReaderUtil.readLine(reader)) != null) {
85                  buf.append(line);
86              }
87          } catch (final Exception e) {
88              throwValidationError(messages -> messages.addErrorsFailedToReadRequestFile(GLOBAL, e.getMessage()),
89                      () -> asListHtml(this::saveToken));
90          }
91  
92          final CurlRequest curlRequest = getCurlRequest(header);
93          if (curlRequest == null) {
94              final String msg = header;
95              throwValidationError(messages -> messages.addErrorsInvalidHeaderForRequestFile(GLOBAL, msg), () -> asListHtml(this::saveToken));
96          } else {
97              try (final CurlResponse response = curlRequest.body(buf.toString()).execute()) {
98                  final File tempFile = ComponentUtil.getSystemHelper().createTempFile("esreq_", ".json");
99                  try (final InputStream in = response.getContentAsStream()) {
100                     CopyUtil.copy(in, tempFile);
101                 } catch (final Exception e1) {
102                     if (tempFile != null && tempFile.exists() && !tempFile.delete()) {
103                         logger.warn("Failed to delete {}", tempFile.getAbsolutePath());
104                     }
105                     throw e1;
106                 }
107                 return asStream("es_" + System.currentTimeMillis() + ".json").contentTypeOctetStream().stream(out -> {
108                     try (final InputStream in = new FileInputStream(tempFile)) {
109                         out.write(in);
110                     } finally {
111                         if (tempFile.exists() && !tempFile.delete()) {
112                             logger.warn("Failed to delete {}", tempFile.getAbsolutePath());
113                         }
114                     }
115                 });
116             } catch (final Exception e) {
117                 logger.warn("Failed to process request file: {}", form.requestFile.getFileName(), e);
118                 throwValidationError(messages -> messages.addErrorsInvalidHeaderForRequestFile(GLOBAL, e.getMessage()),
119                         () -> asListHtml(this::saveToken));
120             }
121         }
122         return redirect(getClass()); // no-op
123     }
124 
125     private CurlRequest getCurlRequest(final String header) {
126         if (StringUtil.isBlank(header)) {
127             return null;
128         }
129 
130         final String[] values = header.split(" ");
131         if (values.length != 2) {
132             return null;
133         }
134 
135         final String path;
136         if (values[1].startsWith("/")) {
137             path = values[1];
138         } else {
139             path = "/" + values[1];
140         }
141 
142         final CurlHelper curlHelper = ComponentUtil.getCurlHelper();
143         switch (values[0].toUpperCase(Locale.ROOT)) {
144         case "GET":
145             return curlHelper.get(path);
146         case "POST":
147             return curlHelper.post(path);
148         case "PUT":
149             return curlHelper.put(path);
150         case "DELETE":
151             return curlHelper.delete(path);
152         default:
153             break;
154         }
155         return null;
156     }
157 
158     private HtmlResponse asListHtml(final Runnable runnable) {
159         if (runnable != null) {
160             runnable.run();
161         }
162         return asHtml(path_AdminEsreq_AdminEsreqJsp).useForm(UploadForm.class);
163     }
164 
165 }