private void reformat() { String text = getToolTipText(); if (text != null && !text.matches("(?i)^<html\\b.*")) { int width = getToolTipWidth(); if (width > 0) { text = "<html>" + TextUtil.escapeHTMLChars(TextUtil.format(text, width, false)) + "</html>"; super.setToolTipText(text); } } }
/** * Helper method for constructors. Converts the specified string into {@link WebResponseData} with * other defaults specified. * * @param contentString the string to be converted to a <tt>WebResponseData</tt> * @return a simple <tt>WebResponseData</tt> with defaults specified */ private static WebResponseData getWebResponseData( final String contentString, final String charset) { final byte[] content = TextUtil.stringToByteArray(contentString, charset); final List<NameValuePair> compiledHeaders = new ArrayList<NameValuePair>(); compiledHeaders.add(new NameValuePair("Content-Type", "text/html")); return new WebResponseData(content, HttpStatus.SC_OK, "OK", compiledHeaders); }
public void headingAdded(WikiContext context, Heading hd) { log.debug("HD: " + hd.m_level + ", " + hd.m_titleText + ", " + hd.m_titleAnchor); switch (hd.m_level) { case Heading.HEADING_SMALL: m_buf.append("<li class=\"toclevel-3\">"); m_level3Index++; break; case Heading.HEADING_MEDIUM: m_buf.append("<li class=\"toclevel-2\">"); m_level2Index++; break; case Heading.HEADING_LARGE: m_buf.append("<li class=\"toclevel-1\">"); m_level1Index++; break; default: throw new InternalWikiException("Unknown depth in toc! (Please submit a bug report.)"); } if (m_level1Index < m_starting) { // in case we never had a large heading ... m_level1Index++; } if ((m_lastLevel == Heading.HEADING_SMALL) && (hd.m_level != Heading.HEADING_SMALL)) { m_level3Index = 0; } if (((m_lastLevel == Heading.HEADING_SMALL) || (m_lastLevel == Heading.HEADING_MEDIUM)) && (hd.m_level == Heading.HEADING_LARGE)) { m_level3Index = 0; m_level2Index = 0; } String titleSection = hd.m_titleSection.replace('%', '_'); String pageName = context.getEngine().encodeName(context.getPage().getName()).replace('%', '_'); String url = context.getURL(WikiContext.VIEW, context.getPage().getName()); String sectref = "#section-" + pageName + "-" + titleSection; m_buf.append("<a class=\"wikipage\" href=\"" + url + sectref + "\">"); if (m_usingNumberedList) { switch (hd.m_level) { case Heading.HEADING_SMALL: m_buf.append(m_prefix + m_level1Index + "." + m_level2Index + "." + m_level3Index + " "); break; case Heading.HEADING_MEDIUM: m_buf.append(m_prefix + m_level1Index + "." + m_level2Index + " "); break; case Heading.HEADING_LARGE: m_buf.append(m_prefix + m_level1Index + " "); break; default: throw new InternalWikiException("Unknown depth in toc! (Please submit a bug report.)"); } } m_buf.append(TextUtil.replaceEntities(hd.m_titleText) + "</a></li>\n"); m_lastLevel = hd.m_level; }
/** * Sets the response that will be returned when a URL is requested that does not have a specific * content set for it. * * @param content the content to return * @param statusCode the status code to return * @param statusMessage the status message to return * @param contentType the content type to return */ public void setDefaultResponse( final String content, final int statusCode, final String statusMessage, final String contentType) { setDefaultResponse(TextUtil.stringToByteArray(content), statusCode, statusMessage, contentType); }
@Override public void draw() { glPushMatrix(); if (position != null) { glTranslated(position.getX(), position.getY(), 0); } // TODO Auto-generated method stub DrawUtil.setColor(color); if (image != null) { image.draw(); } TextUtil.getInstance().setAlignment(textAlignment); TextUtil.getInstance().setTextSize(fontSize); TextUtil.getInstance().write(label, new Coord()); glPopMatrix(); }
protected void onFormat(Editable s) { String text = removeFormatting(s.toString()); // Get the selection handle, since we're setting text and that'll overwrite it MutableInteger selectionHandle = new MutableInteger(getSelectionStart()); // Adjust the handle by removing any comas or spacing to the left String cs = s.subSequence(0, selectionHandle.intValue()).toString(); selectionHandle.subtract(TextUtil.countOccurrences(cs, mSolver.getBaseModule().getSeparator())); // Update the text with formatted (comas, etc) text setText(Html.fromHtml(formatText(text, selectionHandle))); setSelection(selectionHandle.intValue()); }
/** * Sets the response that will be returned when the specified URL is requested. * * @param content the content to return * @param statusCode the status code to return * @param statusMessage the status message to return * @param contentType the content type to return * @param responseHeaders the response headers to return */ public void setDefaultResponse( final String content, final int statusCode, final String statusMessage, final String contentType, final List<? extends NameValuePair> responseHeaders) { final List<NameValuePair> compiledHeaders = new ArrayList<NameValuePair>(responseHeaders); if (contentType != null) { compiledHeaders.add(new NameValuePair("Content-Type", contentType)); } defaultResponse_ = buildWebResponseData( TextUtil.stringToByteArray(content), statusCode, statusMessage, compiledHeaders); }
/** * Sets the response that will be returned when the specified URL is requested. * * @param url the URL that will return the given response * @param content the content to return * @param statusCode the status code to return * @param statusMessage the status message to return * @param contentType the content type to return * @param responseHeaders the response headers to return */ public void setResponse( final URL url, final String content, final int statusCode, final String statusMessage, final String contentType, final List<? extends NameValuePair> responseHeaders) { setResponse( url, TextUtil.stringToByteArray(content), statusCode, statusMessage, contentType, responseHeaders); }
private void updateTyping() { needNewUpdateTyping = false; if (description.getPeerType() == PeerType.PEER_USER || description.getPeerType() == PeerType.PEER_USER_ENCRYPTED) { if (userTypes) { typingLayout = new StaticLayout( getResources().getString(R.string.lang_common_typing), bodyHighlightPaint, layout.layoutMainWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); } else { typingLayout = null; } } else { if (typingUids != null && typingUids.length != 0) { String[] names = new String[typingUids.length]; for (int i = 0; i < names.length; i++) { names[i] = application.getEngine().getUserRuntime(typingUids[i]).getFirstName(); } String typing = TextUtil.formatTyping(names); Spannable spannable = application .getEmojiProcessor() .processEmojiCutMutable(typing, EmojiProcessor.CONFIGURATION_DIALOGS); CharSequence sequence = TextUtils.ellipsize( spannable, bodyHighlightPaint, layout.layoutMainWidth, TextUtils.TruncateAt.END); typingLayout = new StaticLayout( sequence, bodyHighlightPaint, layout.layoutMainWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); } else { typingLayout = null; } } }
private static String unmangleName(String filename) { return TextUtil.urlDecodeUTF8(filename); }
private static String mangleName(String wikiname) { String res = TextUtil.urlEncodeUTF8(wikiname); return res; }
public void createSenIndex(JSONArray jsonArray, String indexPath, String stopwordsFile) throws Exception { if (jsonArray == null) { System.out.println("error: jsonArray is null!\n"); return; } Analyzer analyzer = null; if (stopwordsFile == null) { analyzer = new SimpleAnalyzer(); } else { analyzer = new StopAnalyzer(Paths.get(stopwordsFile)); } IndexWriterConfig iwc = new IndexWriterConfig(analyzer); iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE); IndexWriter indexWriter = new IndexWriter(FSDirectory.open(Paths.get(indexPath)), iwc); indexWriter.deleteAll(); TextUtil textUtil = new TextUtil(); long startTime = new Date().getTime(); System.out.println("jsonArray size: " + jsonArray.size()); long num_sentence = 0; for (JSONObject jsonObj : (List<JSONObject>) jsonArray) { long id = (long) jsonObj.get(idKey); String review = (String) jsonObj.get(reviewKey); if (review == null || review.isEmpty()) { continue; } if (review.matches(".*[^\\x00-\\x7F].*")) { continue; } String[] tokens = textUtil.tokenize(review); if (tokens.length <= TERM_MIN_THRESHOLD) { continue; } String[] sentences = textUtil.sentenceDetect(review); // System.out.println(body.toLowerCase() + "\n"); num_sentence = 0; for (int i = 0; i < sentences.length; i++) { if (sentences[i] == null || sentences[i].isEmpty()) { continue; } // System.out.println(sentences[i]); Document doc = new Document(); Field idField = new LongField(idKey, id, Field.Store.YES); Field numField = new LongField("num", num_sentence, Field.Store.NO); Field contentField = new TextField( reviewKey, sentences[i].replaceAll("[_'.,]", " ").replaceAll("[0-9]", ""), Field.Store.YES); doc.add(idField); doc.add(numField); doc.add(contentField); indexWriter.addDocument(doc); num_sentence++; } } indexWriter.commit(); indexWriter.close(); long endTime = new Date().getTime(); System.out.println("\n\ncreate index time: " + (endTime - startTime) + "ms"); System.out.println("\n sentence num: " + num_sentence + "\n"); }
/** * Look up a name and return its value as a String, with default. * * @param name the name to look up * @param dflt the default value if the name is not found. */ public String getProperty(String name, String dflt) { ActiveNodeList value = getValueNodes(name); return (value == null) ? dflt : TextUtil.getCharData(value); }
public void setKey(Text key) { this.key = TextUtil.getBytes(key); }
public RowId(Text key, long createdTime, long modifiedTime, byte state) { init(TextUtil.getBytes(key), createdTime, modifiedTime, state); }
// FIXME: The compiled pattern strings should really be cached somehow. public void initialize(WikiContext context, Map params) throws PluginException { m_dateFormat = Preferences.getDateFormat(context, TimeFormat.DATETIME); m_engine = context.getEngine(); m_maxwidth = TextUtil.parseIntParameter((String) params.get(PARAM_MAXWIDTH), Integer.MAX_VALUE); if (m_maxwidth < 0) m_maxwidth = 0; String s = (String) params.get(PARAM_SEPARATOR); if (s != null) { m_separator = s; // pre-2.1.145 there was a separator at the end of the list // if they set the parameters, we use the new format of // before Item1 after separator before Item2 after separator before Item3 after m_after = ""; } s = (String) params.get(PARAM_BEFORE); if (s != null) { m_before = s; } s = (String) params.get(PARAM_AFTER); if (s != null) { m_after = s; } s = (String) params.get(PARAM_EXCLUDE); if (s != null) { try { PatternCompiler pc = new GlobCompiler(); String[] ptrns = StringUtils.split(s, ","); m_exclude = new Pattern[ptrns.length]; for (int i = 0; i < ptrns.length; i++) { m_exclude[i] = pc.compile(ptrns[i]); } } catch (MalformedPatternException e) { throw new PluginException("Exclude-parameter has a malformed pattern: " + e.getMessage()); } } // TODO: Cut-n-paste, refactor s = (String) params.get(PARAM_INCLUDE); if (s != null) { try { PatternCompiler pc = new GlobCompiler(); String[] ptrns = StringUtils.split(s, ","); m_include = new Pattern[ptrns.length]; for (int i = 0; i < ptrns.length; i++) { m_include[i] = pc.compile(ptrns[i]); } } catch (MalformedPatternException e) { throw new PluginException("Include-parameter has a malformed pattern: " + e.getMessage()); } } // log.debug( "Requested maximum width is "+m_maxwidth ); s = (String) params.get(PARAM_SHOW); if (s != null) { if (s.equalsIgnoreCase("count")) { m_show = "count"; } } s = (String) params.get(PARAM_LASTMODIFIED); if (s != null) { if (s.equalsIgnoreCase("true")) { if (m_show.equals("count")) { m_lastModified = true; } else { throw new PluginException( "showLastModified=true is only valid if show=count is also specified"); } } } initSorter(context, params); }
public String execute(WikiContext context, Map params) throws PluginException { WikiEngine engine = context.getEngine(); WikiPage page = context.getPage(); if (context.getVariable(VAR_ALREADY_PROCESSING) != null) return "Table of Contents"; StringBuffer sb = new StringBuffer(); sb.append("<div class=\"toc\">\n"); sb.append("<div class=\"collapsebox\">\n"); String title = (String) params.get(PARAM_TITLE); if (title != null) { sb.append("<h4>" + TextUtil.replaceEntities(title) + "</h4>\n"); } else { sb.append("<h4>Table of Contents</h4>\n"); } // should we use an ordered list? m_usingNumberedList = false; if (params.containsKey(PARAM_NUMBERED)) { String numbered = (String) params.get(PARAM_NUMBERED); if (numbered.equalsIgnoreCase("true")) { m_usingNumberedList = true; } else if (numbered.equalsIgnoreCase("yes")) { m_usingNumberedList = true; } } // if we are using a numbered list, get the rest of the parameters (if any) ... if (m_usingNumberedList) { int start = 0; String startStr = (String) params.get(PARAM_START); if ((startStr != null) && (startStr.matches("^\\d+$"))) { start = Integer.parseInt(startStr); } if (start < 0) start = 0; m_starting = start; m_level1Index = start - 1; if (m_level1Index < 0) m_level1Index = 0; m_level2Index = 0; m_level3Index = 0; m_prefix = (String) params.get(PARAM_PREFIX); if (m_prefix == null) m_prefix = ""; m_lastLevel = Heading.HEADING_LARGE; } try { String wikiText = engine.getPureText(page); context.setVariable(VAR_ALREADY_PROCESSING, "x"); JSPWikiMarkupParser parser = new JSPWikiMarkupParser(context, new StringReader(wikiText)); parser.addHeadingListener(this); parser.parse(); sb.append("<ul>\n" + m_buf.toString() + "</ul>\n"); } catch (IOException e) { log.error("Could not construct table of contents", e); throw new PluginException("Unable to construct table of contents (see logs)"); } sb.append("</div>\n</div>\n"); return sb.toString(); }
private String replaceReferrerString( WikiContext context, String sourceText, String from, String to) { StringBuilder sb = new StringBuilder(sourceText.length() + 32); // // This monstrosity just looks for a JSPWiki link pattern. But it is pretty // cool for a regexp, isn't it? If you can understand this in a single reading, // you have way too much time in your hands. // Pattern linkPattern = Pattern.compile("([\\[\\~]?)\\[([^\\|\\]]*)(\\|)?([^\\|\\]]*)(\\|)?([^\\|\\]]*)\\]"); Matcher matcher = linkPattern.matcher(sourceText); int start = 0; // System.out.println("===="); // System.out.println("SRC="+sourceText.trim()); while (matcher.find(start)) { char charBefore = (char) -1; if (matcher.start() > 0) charBefore = sourceText.charAt(matcher.start() - 1); if (matcher.group(1).length() > 0 || charBefore == '~' || charBefore == '[') { // // Found an escape character, so I am escaping. // sb.append(sourceText.substring(start, matcher.end())); start = matcher.end(); continue; } String text = matcher.group(2); String link = matcher.group(4); String attr = matcher.group(6); /* System.out.println("MATCH="+matcher.group(0)); System.out.println(" text="+text); System.out.println(" link="+link); System.out.println(" attr="+attr); */ if (link.length() == 0) { text = replaceSingleLink(context, text, from, to); } else { link = replaceSingleLink(context, link, from, to); // // A very simple substitution, but should work for quite a few cases. // text = TextUtil.replaceString(text, from, to); } // // Construct the new string // sb.append(sourceText.substring(start, matcher.start())); sb.append("[" + text); if (link.length() > 0) sb.append("|" + link); if (attr.length() > 0) sb.append("|" + attr); sb.append("]"); start = matcher.end(); } sb.append(sourceText.substring(start)); return sb.toString(); }
/** {@inheritDoc} */ public String execute(WikiContext context, Map params) throws PluginException { // // First, determine which kind of name we use to store in // the WikiContext. // String countername = (String) params.get(PARAM_NAME); if (countername == null) { countername = DEFAULT_NAME; } else { countername = DEFAULT_NAME + "-" + countername; } // // Fetch the old value // Integer val = (Integer) context.getVariable(countername); if (val == null) { val = 0; } // // Check if we need to reset this // String start = (String) params.get(PARAM_START); if (start != null) { val = Integer.parseInt(start); } else { // // Determine how much to increment // Object incrementObj = params.get(PARAM_INCREMENT); int increment = DEFAULT_INCREMENT; if (incrementObj != null) { increment = (new Integer((String) incrementObj)).intValue(); } val = val + increment; } context.setVariable(countername, val); // // check if we want to hide the result (just count, don't show result on the page // Object showObj = params.get(PARAM_SHOW_RESULT); boolean show = DEFAULT_SHOW_RESULT; if (showObj != null) { show = TextUtil.isPositive((String) showObj); } if (show) { return val.toString(); } return ""; }
/** * Renames a page. * * @param context The current context. * @param renameFrom The name from which to rename. * @param renameTo The new name. * @param changeReferrers If true, also changes all the referrers. * @return The final new name (in case it had to be modified) * @throws WikiException If the page cannot be renamed. */ public String renamePage( WikiContext context, String renameFrom, String renameTo, boolean changeReferrers) throws WikiException { // // Sanity checks first // if (renameFrom == null || renameFrom.length() == 0) { throw new WikiException("From name may not be null or empty"); } if (renameTo == null || renameTo.length() == 0) { throw new WikiException("To name may not be null or empty"); } // // Clean up the "to" -name so that it does not contain anything illegal // renameTo = MarkupParser.cleanLink(renameTo.trim()); if (renameTo.equals(renameFrom)) { throw new WikiException("You cannot rename the page to itself"); } // // Preconditions: "from" page must exist, and "to" page must not yet exist. // WikiEngine engine = context.getEngine(); WikiPage fromPage = engine.getPage(renameFrom); if (fromPage == null) { throw new WikiException("No such page " + renameFrom); } WikiPage toPage = engine.getPage(renameTo); if (toPage != null) { throw new WikiException("Page already exists " + renameTo); } // // Options // m_camelCase = TextUtil.getBooleanProperty( engine.getWikiProperties(), JSPWikiMarkupParser.PROP_CAMELCASELINKS, m_camelCase); Set<String> referrers = getReferencesToChange(fromPage, engine); // // Do the actual rename by changing from the frompage to the topage, including // all of the attachments // engine.getPageManager().getProvider().movePage(renameFrom, renameTo); if (engine.getAttachmentManager().attachmentsEnabled()) { engine .getAttachmentManager() .getCurrentProvider() .moveAttachmentsForPage(renameFrom, renameTo); } // // Add a comment to the page notifying what changed. This adds a new revision // to the repo with no actual change. // toPage = engine.getPage(renameTo); if (toPage == null) throw new InternalWikiException( "Rename seems to have failed for some strange reason - please check logs!"); toPage.setAttribute(WikiPage.CHANGENOTE, fromPage.getName() + " ==> " + toPage.getName()); toPage.setAuthor(context.getCurrentUser().getName()); engine.getPageManager().putPageText(toPage, engine.getPureText(toPage)); // // Update the references // engine.getReferenceManager().pageRemoved(fromPage); engine.updateReferences(toPage); // // Update referrers // if (changeReferrers) { updateReferrers(context, fromPage, toPage, referrers); } // // re-index the page // engine.getSearchManager().reindexPage(toPage); Collection<Attachment> attachments = engine.getAttachmentManager().listAttachments(toPage); for (Attachment att : attachments) { engine.getSearchManager().reindexPage(att); } // // Done, return the new name. // return renameTo; }