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

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

Cleanup DI

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