source: other-projects/the-macronizer/trunk/src/java/web/servlets/DirectInput.java@ 35722

Last change on this file since 35722 was 35722, checked in by cstephen, 2 years ago

Remove unnecessary comment

File size: 9.0 KB
Line 
1package web.servlets;
2
3import java.io.BufferedReader;
4import java.io.BufferedWriter;
5import java.io.File;
6import java.io.FileInputStream;
7import java.io.FileOutputStream;
8import java.io.IOException;
9import java.io.InputStreamReader;
10import java.io.OutputStreamWriter;
11import java.io.UnsupportedEncodingException;
12
13import javax.servlet.RequestDispatcher;
14import javax.servlet.ServletConfig;
15import javax.servlet.ServletException;
16import javax.servlet.http.HttpServlet;
17import javax.servlet.http.HttpServletRequest;
18import javax.servlet.http.HttpServletResponse;
19
20import com.google.gson.Gson;
21import com.google.gson.stream.JsonWriter;
22
23import monogram.plugin.PluginConfiguration;
24import monogram.plugin.PluginManager;
25
26import org.apache.log4j.*;
27
28import util.FileUtil;
29import util.IOUtil;
30
31/**
32 * Represents a servlet for macronising direct text input.
33 * @author OEM
34 * @version 2.0
35 */
36public class DirectInput extends HttpServlet
37{
38 private static final String UTF8_ENCODING = "utf-8";
39
40 //Create an instance of the logger object defined for this class in log4j.properties
41 private static final Logger logger = Logger.getLogger(web.servlets.DirectInput.class.getName());
42
43 private final Gson gsonInstance = new Gson();
44
45 private File tmpdir;
46 private PluginManager pluginManager;
47
48 @Override
49 public void init(ServletConfig config) throws ServletException
50 {
51 super.init(config);
52
53 tmpdir = new File((String) config.getServletContext().getAttribute("tmpdir"));
54 pluginManager = new PluginManager(tmpdir);
55 }
56
57 /**
58 * Handles the HTTP <code>GET</code> method.
59 * @param request The servlet request.
60 * @param response The servlet response.
61 * @throws IllegalStateException if a reponse has already been committed.
62 * @throws IOException if an I/O error occurs.
63 */
64 @Override
65 protected void doGet(HttpServletRequest request, HttpServletResponse response)
66 throws IllegalStateException, IOException
67 {
68 response.sendError(405); // 405 Method Not Allowed
69 }
70
71 /**
72 * Handles the HTTP <code>POST</code> method.
73 * @param request The servlet request.
74 * @param response The servlet response.
75 * @throws IllegalStateException if a response has already been committed.
76 * @throws IOException if an I/O error occurs.
77 * @throws ServletException if a servlet-specific error occurs.
78 * @throws UnsupportedEncodingException if the selected encoding is not supported.
79 */
80 @Override
81 protected void doPost(HttpServletRequest request, HttpServletResponse response)
82 throws IllegalStateException, IOException, ServletException, UnsupportedEncodingException
83 {
84 request.setCharacterEncoding(UTF8_ENCODING);
85
86 final String fragment = request.getParameter("fragment");
87 final Boolean showAdvancedOptions = Boolean.parseBoolean(request.getParameter("options"));
88 final Boolean shouldPreserveMacrons = Boolean.parseBoolean(request.getParameter("preserveExistingMacrons"));
89 final OutputType outputType = OutputType.parse(request.getParameter("o"));
90
91 // Note that the lang parameter might be null if the request hasn't been made from an internal JSP page
92 final String forwardPath = request.getParameter("lang") != null
93 ? "/jsp/" + request.getParameter("lang")
94 : "/jsp/mi";
95
96 try
97 {
98 final String restoredFragment = restoreMacrons
99 (
100 fragment,
101 shouldPreserveMacrons,
102 true
103 );
104
105 if (outputType == OutputType.Json)
106 {
107 response.setContentType("application/json; charset=UTF-8");
108 JsonWriter writer = gsonInstance.newJsonWriter(response.getWriter());
109 writer.beginArray();
110
111 for (String element : restoredFragment.split("\\ "))
112 {
113 writer.beginObject();
114
115 if (element.contains("<mark>"))
116 {
117 element = element.replace("<mark>", "").replace("</mark>", "");
118 writer.name("macronised");
119 writer.value(true);
120 }
121
122 writer.name("w");
123 writer.value(element);
124
125 writer.endObject();
126 }
127
128 writer.endArray();
129 writer.flush();
130 }
131 else
132 {
133 request.setAttribute("fragment2", restoredFragment);
134 request.setAttribute("old", fragment);
135 request.setAttribute("options", showAdvancedOptions.toString());
136 request.setAttribute("preserveMacrons", shouldPreserveMacrons.toString());
137
138 forward(forwardPath + "/main.jsp", request, response);
139 }
140
141 logger.debug("Macron restoration succeeded. Input: " + fragment + " | Output: " + restoredFragment);
142 }
143 catch (Exception ex)
144 {
145 ex.printStackTrace();
146 logger.error("Failed to restore macrons", ex);
147
148 switch (outputType) {
149 case Json:
150 // 500 Internal Server Error
151 response.sendError(500, "An unexpected error has occurred. Please try again or contact the web administrator if the problem persists.");
152 break;
153 default:
154 request.setAttribute("errorMessage", "UNEXPECTED_ERROR");
155 forward(forwardPath + "/error.jsp", request, response);
156 break;
157 }
158 }
159 }
160
161 /**
162 * Restores macrons on an input fragment.
163 * @param input The input fragment to restore.
164 * @param preserveMacrons Indicates whether existing macrons on the input should be preserved.
165 * @return The macronised fragment.
166 * @throws IOException
167 * @throws UnsupportedOperationException
168 * @throws Exception
169 */
170 private String restoreMacrons(String input, boolean preserveMacrons, boolean markupChangedWords)
171 throws IOException, UnsupportedOperationException, Exception
172 {
173 //Write the input to a temporary file.
174 File inputFile = File.createTempFile(FileUtil.TMP_FILE_PREFIX, ".txt", tmpdir);
175 write(inputFile, UTF8_ENCODING, input);
176
177 //Create a fileview
178 PluginConfiguration configuration = new PluginConfiguration();
179 configuration.setFile(inputFile);
180 configuration.setCharsetEncoding(UTF8_ENCODING);
181 configuration.setFileType(".txt");
182 configuration.setPreserveExistingMacrons(preserveMacrons);
183 configuration.setMarkupChangedWords(markupChangedWords);
184
185 //Restore the file.
186 File restoredFile = null;
187
188 try
189 {
190 restoredFile = pluginManager.run(configuration);
191 return read(restoredFile, UTF8_ENCODING).trim();
192 }
193 finally
194 {
195 inputFile.delete();
196
197 if (restoredFile != null)
198 {
199 restoredFile.delete();
200 }
201 }
202 }
203
204 /**
205 * Forwards a request from a servlet to another resource on the server.
206 * @param path The path to forward to.
207 * @param request The servlet request.
208 * @param response The servlet response.
209 * @throws ServletException
210 * @throws IOException
211 */
212 private void forward(String path, HttpServletRequest request, HttpServletResponse response)
213 throws ServletException, IOException
214 {
215 final RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(path);
216 dispatcher.forward(request, response);
217 }
218
219 /**
220 * Writes the fragment to the file.
221 * @param file The file to write to.
222 * @param fragment The String to write to the file.
223 * @throws IOException
224 */
225 private void write(File file, String charsetEncoding, String fragment)
226 throws IOException
227 {
228 BufferedWriter out = null;
229 try
230 {
231 out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charsetEncoding));
232 out.write(fragment);
233 }
234 finally
235 {
236 IOUtil.closeWriter(out);
237 }
238 }
239
240 /**
241 * Reads the contents of the file.
242 * @param file The file to read.
243 * @param charsetEncoding The character set encoding of the file.
244 * @return The contents of the file.
245 * @throws IOException
246 */
247 private String read(File file, String charsetEncoding)
248 throws IOException
249 {
250 final StringBuilder buffer = new StringBuilder();
251 BufferedReader reader = null;
252
253 try
254 {
255 reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charsetEncoding));
256 final char[] chars = new char[1024];
257 int numRead = 0;
258
259 while ((numRead = reader.read(chars)) > -1)
260 {
261 buffer.append(String.valueOf(chars, 0, numRead));
262 }
263 }
264 finally
265 {
266 IOUtil.closeReader(reader);
267 }
268
269 return buffer.toString();
270 }
271}
Note: See TracBrowser for help on using the repository browser.