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.helper;
17  
18  import java.io.File;
19  import java.io.FileInputStream;
20  import java.io.InputStream;
21  
22  import javax.annotation.PostConstruct;
23  
24  import org.codelibs.core.lang.StringUtil;
25  import org.codelibs.fess.Constants;
26  import org.codelibs.fess.util.ComponentUtil;
27  import org.lastaflute.web.response.StreamResponse;
28  import org.lastaflute.web.util.LaServletContextUtil;
29  import org.slf4j.Logger;
30  import org.slf4j.LoggerFactory;
31  
32  /**
33   * Helper class for Open Search Description Document.
34   *
35   * @author shinsuke
36   *
37   */
38  public class OpenSearchHelper {
39      private static final Logger logger = LoggerFactory.getLogger(OpenSearchHelper.class);
40  
41      public String osddPath;
42  
43      public String encoding = Constants.UTF_8;
44  
45      public String contentType = "text/xml"; // "application/opensearchdescription+xml";
46  
47      private File osddFile;
48  
49      @PostConstruct
50      public void init() {
51          if (StringUtil.isNotBlank(osddPath)) {
52              final String path = LaServletContextUtil.getServletContext().getRealPath(osddPath);
53              osddFile = new File(path);
54              if (!osddFile.isFile()) {
55                  osddFile = null;
56                  logger.warn(path + " was not found.");
57              }
58          } else {
59              logger.info("OSDD file is not found.");
60          }
61      }
62  
63      public boolean hasOpenSearchFile() {
64          return osddFile != null;
65      }
66  
67      public StreamResponse asStream() {
68          if (osddFile == null) {
69              throw ComponentUtil.getResponseManager().new404("Unsupported OpenSearch response.");
70          }
71  
72          return new StreamResponse(osddFile.getName()).contentType(contentType + "; charset=" + encoding).stream(out -> {
73              try (InputStream ins = new FileInputStream(osddFile)) {
74                  out.write(ins);
75              }
76          });
77      }
78  }