PageRenderTime 127ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/tinymce4-parent/tinymce4/src/main/java/wicket/contrib/tinymce4/settings/JazzySpellChecker.java

https://github.com/chrisco484/core
Java | 282 lines | 194 code | 30 blank | 58 comment | 12 complexity | e3588ac3fe2bca5691da6cf048c48067 MD5 | raw file
  1. /*
  2. * $Id: org.eclipse.jdt.ui.prefs 5004 2006-03-17 20:47:08 -0800 (Fri, 17 Mar
  3. * 2006) eelco12 $ $Revision: 5004 $ $Date: 2006-03-17 20:47:08 -0800 (Fri, 17
  4. * Mar 2006) $
  5. *
  6. * ==============================================================================
  7. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  8. * use this file except in compliance with the License. You may obtain a copy of
  9. * the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  15. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  16. * License for the specific language governing permissions and limitations under
  17. * the License.
  18. */
  19. package wicket.contrib.tinymce4.settings;
  20. import com.swabunga.spell.engine.SpellDictionary;
  21. import com.swabunga.spell.engine.SpellDictionaryHashMap;
  22. import com.swabunga.spell.event.SpellCheckEvent;
  23. import com.swabunga.spell.event.SpellCheckListener;
  24. import com.swabunga.spell.event.SpellChecker;
  25. import com.swabunga.spell.event.StringWordTokenizer;
  26. import java.io.BufferedReader;
  27. import java.io.IOException;
  28. import java.io.InputStream;
  29. import java.io.InputStreamReader;
  30. import java.util.HashSet;
  31. import java.util.Iterator;
  32. import java.util.List;
  33. import java.util.Set;
  34. import javax.servlet.ServletInputStream;
  35. import javax.servlet.http.HttpServletRequest;
  36. import org.apache.wicket.ajax.json.JSONArray;
  37. import org.apache.wicket.ajax.json.JSONException;
  38. import org.apache.wicket.ajax.json.JSONObject;
  39. import org.apache.wicket.ajax.json.JSONTokener;
  40. import org.apache.wicket.protocol.http.servlet.ServletWebRequest;
  41. import org.apache.wicket.request.cycle.RequestCycle;
  42. import org.apache.wicket.request.http.WebResponse;
  43. import org.apache.wicket.request.resource.AbstractResource;
  44. import org.apache.wicket.util.resource.StringBufferResourceStream;
  45. import org.apache.wicket.util.time.Time;
  46. import org.slf4j.Logger;
  47. import org.slf4j.LoggerFactory;
  48. /**
  49. * Wicket web resource that acts as backend spell checker for tinymce component.
  50. *
  51. * @author ivaynberg
  52. * @author Iulian Costan (iulian.costan@gmail.com)
  53. * @author Boris Goldowsky
  54. */
  55. class JazzySpellChecker extends AbstractResource
  56. {
  57. protected static final String dictFile = "wicket/contrib/tinymce/jazzy/english.0";
  58. private SpellDictionary dict;
  59. private final StringBufferResourceStream resourceStream;
  60. protected static final String contentType = "application/json";
  61. private static final Logger LOG = LoggerFactory.getLogger(JazzySpellChecker.class);
  62. private static final long serialVersionUID = 1L;
  63. /**
  64. * Construct spell checker resource.
  65. */
  66. public JazzySpellChecker()
  67. {
  68. // todo load dict file from jazzy.jar archive.
  69. InputStream inputStream = getClass().getClassLoader().getResourceAsStream(dictFile);
  70. InputStreamReader reader = new InputStreamReader(inputStream);
  71. try
  72. {
  73. dict = new SpellDictionaryHashMap(reader);
  74. }
  75. catch (IOException e)
  76. {
  77. throw new RuntimeException(e);
  78. }
  79. finally
  80. {
  81. try
  82. {
  83. reader.close();
  84. }
  85. catch (IOException e)
  86. {
  87. throw new RuntimeException(e);
  88. }
  89. }
  90. resourceStream = new StringBufferResourceStream(contentType);
  91. }
  92. // /**
  93. // * Read the Request and do the processing needed to construct a response.
  94. // * Why here? configureResponse is one of the few Resource methods that is
  95. // * called only once per Request. Running the spellcheck anew each time
  96. // * getResourceStream is called, for example, would be wasteful.
  97. // *
  98. // * @see org.apache.wicket.Resource#configureResponse(Response response)
  99. // */
  100. @Override
  101. protected ResourceResponse newResourceResponse(Attributes attributes)
  102. {
  103. buildResourceStream();
  104. if (attributes.getResponse() instanceof WebResponse)
  105. ((WebResponse)attributes.getResponse()).setHeader("Cache-Control",
  106. "no-cache, must-revalidate");
  107. ResourceResponse resourceResponse = new ResourceResponse();
  108. resourceResponse.setWriteCallback(new WriteCallback()
  109. {
  110. @Override
  111. public void writeData(Attributes attributes)
  112. {
  113. attributes.getResponse().write(resourceStream.asString());
  114. }
  115. });
  116. return resourceResponse;
  117. }
  118. //
  119. // /**
  120. // * @see org.apache.wicket.Resource#getResourceStream()
  121. // */
  122. // public IResourceStream getResourceStream()
  123. // {
  124. // return resourceStream;
  125. // }
  126. /**
  127. * Read the Request and construct an appropriate ResourceStream to respond with.
  128. */
  129. public void buildResourceStream()
  130. {
  131. JSONObject json;
  132. String cmd = null, id = null;
  133. JSONArray paramArray = null;
  134. HttpServletRequest req = ((ServletWebRequest)RequestCycle.get().getRequest()).getContainerRequest();
  135. BufferedReader reader = null;
  136. try
  137. {
  138. ServletInputStream sis = req.getInputStream();
  139. reader = new BufferedReader(new InputStreamReader(sis, "UTF-8"));
  140. // Used for debugging:
  141. // reader.mark(10);
  142. // if (reader.read() == -1) {
  143. // LOG.error("No request seen");
  144. // }
  145. // reader.reset();
  146. json = new JSONObject(new JSONTokener(reader));
  147. // LOG.debug("JSON Object: {}", json);
  148. id = json.getString("id");
  149. cmd = json.getString("method");
  150. paramArray = json.getJSONArray("params");
  151. }
  152. catch (IOException e)
  153. {
  154. jsonError("I/O exception while parsing");
  155. }
  156. catch (JSONException e)
  157. {
  158. jsonError("Could not parse command");
  159. }
  160. finally
  161. {
  162. try
  163. {
  164. if (reader != null)
  165. reader.close();
  166. }
  167. catch (IOException e)
  168. {
  169. e.printStackTrace();
  170. }
  171. }
  172. if (paramArray == null)
  173. {
  174. handleEmptyCheckList(cmd, id);
  175. }
  176. else if ("checkWords".equals(cmd))
  177. {
  178. doSpell(cmd, id, paramArray);
  179. }
  180. else if ("getSuggestions".equals(cmd))
  181. {
  182. doSuggest(cmd, id, paramArray);
  183. }
  184. else
  185. {
  186. jsonError("Unknown command");
  187. }
  188. // LOG.debug("Processed command {}; output will be {}", cmd,
  189. // resourceStream.asString());
  190. }
  191. private void handleEmptyCheckList(final String cmd, final String id)
  192. {
  193. respond(null, cmd, id);
  194. }
  195. @SuppressWarnings("unchecked")
  196. private void doSuggest(final String cmd, final String id, final JSONArray paramArray)
  197. {
  198. final SpellChecker checker = new SpellChecker(dict);
  199. String word = paramArray.optString(1);
  200. List<String> suggestions = checker.getSuggestions(word, 2);
  201. respond(suggestions.iterator(), cmd, id);
  202. }
  203. private void doSpell(final String cmd, final String id, final JSONArray paramArray)
  204. {
  205. final SpellChecker checker = new SpellChecker(dict);
  206. final Set<String> errors = new HashSet<>();
  207. checker.addSpellCheckListener(new SpellCheckListener()
  208. {
  209. @Override
  210. public void spellingError(SpellCheckEvent event)
  211. {
  212. errors.add(event.getInvalidWord());
  213. }
  214. });
  215. JSONArray words = paramArray.optJSONArray(1);
  216. checker.checkSpelling(new StringWordTokenizer(words.toString()));
  217. respond(errors.iterator(), cmd, id);
  218. }
  219. private void respond(Iterator<String> words, String cmd, String id)
  220. {
  221. JSONArray array = new JSONArray();
  222. if (words != null)
  223. {
  224. while (words.hasNext())
  225. array.put(words.next());
  226. }
  227. JSONObject response = new JSONObject();
  228. try
  229. {
  230. response.put("id", id);
  231. response.put("error", (String)null);
  232. response.put("result", array);
  233. setResponse(response.toString());
  234. }
  235. catch (JSONException e)
  236. {
  237. jsonError("Failed to construct response");
  238. }
  239. }
  240. private void setResponse(String response)
  241. {
  242. resourceStream.clear();
  243. resourceStream.append(response);
  244. resourceStream.setLastModified(Time.now());
  245. }
  246. // Simple method of returning a user-visible error message to TinyMCE
  247. private void jsonError(String message)
  248. {
  249. setResponse("{\"error\":\"" + message + "\"}");
  250. LOG.debug("Error message return from RPC call: {}", message);
  251. }
  252. }