@Override protected Transferable createTransferable(JComponent c) { JTextPane aTextPane = (JTextPane) c; HTMLEditorKit kit = ((HTMLEditorKit) aTextPane.getEditorKit()); StyledDocument sdoc = aTextPane.getStyledDocument(); int sel_start = aTextPane.getSelectionStart(); int sel_end = aTextPane.getSelectionEnd(); int i = sel_start; StringBuilder output = new StringBuilder(); while (i < sel_end) { Element e = sdoc.getCharacterElement(i); Object nameAttr = e.getAttributes().getAttribute(StyleConstants.NameAttribute); int start = e.getStartOffset(), end = e.getEndOffset(); if (nameAttr == HTML.Tag.BR) { output.append("\n"); } else if (nameAttr == HTML.Tag.CONTENT) { if (start < sel_start) { start = sel_start; } if (end > sel_end) { end = sel_end; } try { String str = sdoc.getText(start, end - start); output.append(str); } catch (BadLocationException ble) { Debug.error(me + "Copy-paste problem!\n%s", ble.getMessage()); } } i = end; } return new StringSelection(output.toString()); }
// TODO: make this a method of SikuliDocument, no need to pass document as argument private void changeIndentation(DefaultStyledDocument doc, int linenum, int columns) throws BadLocationException { PreferencesUser pref = PreferencesUser.getInstance(); boolean expandTab = pref.getExpandTab(); int tabWidth = pref.getTabWidth(); if (linenum < 0) { throw new BadLocationException("Negative line", -1); } Element map = doc.getDefaultRootElement(); if (linenum >= map.getElementCount()) { throw new BadLocationException("No such line", doc.getLength() + 1); } if (columns == 0) { return; } Element lineElem = map.getElement(linenum); int lineStart = lineElem.getStartOffset(); int lineLength = lineElem.getEndOffset() - lineStart; String line = doc.getText(lineStart, lineLength); // determine current indentation and number of whitespace characters int wsChars; int indentation = 0; for (wsChars = 0; wsChars < line.length(); wsChars++) { char c = line.charAt(wsChars); if (c == ' ') { indentation++; } else if (c == '\t') { indentation += tabWidth; } else { break; } } int newIndentation = indentation + columns; if (newIndentation <= 0) { doc.remove(lineStart, wsChars); return; } // build whitespace string for new indentation StringBuilder newWs = new StringBuilder(newIndentation / tabWidth + tabWidth - 1); int ind = 0; if (!expandTab) { for (; ind + tabWidth <= newIndentation; ind += tabWidth) { newWs.append('\t'); } } for (; ind < newIndentation; ind++) { newWs.append(' '); } doc.replace(lineStart, wsChars, newWs.toString(), null); }
private String escapePrintfChars(String str) { if (str == null) return ""; StringBuilder sb = new StringBuilder(); for (int ci = 0; ci < str.length(); ci++) { char ch = str.charAt(ci); if (ch == '%') { sb.append('%'); } sb.append(ch); } return sb.toString(); }
/** * Return a copy of the string with all reserved regexp chars escaped by backslash. * * @param str the string to add escapes to * @return String return a string with escapes or "" if str is null */ private String escapeReservedChars(String str) { if (str == null) return ""; StringBuilder sb = new StringBuilder(); for (int ci = 0; ci < str.length(); ci++) { char ch = str.charAt(ci); if (RESERVED_STRING.indexOf(ch) >= 0) { sb.append('\\'); } sb.append(ch); } return escapePrintfChars(sb.toString()); }
public String valueToString(Object value) throws ParseException { if (!(value instanceof byte[])) throw new ParseException("Not a byte[]", 0); byte[] a = (byte[]) value; if (a.length != 4) throw new ParseException("Length != 4", 0); StringBuilder builder = new StringBuilder(); for (int i = 0; i < 4; i++) { int b = a[i]; if (b < 0) b += 256; builder.append(String.valueOf(b)); if (i < 3) builder.append('.'); } return builder.toString(); }
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException { StringBuilder builder = new StringBuilder(string); for (int i = builder.length() - 1; i >= 0; i--) { int cp = builder.codePointAt(i); if (!Character.isDigit(cp) && cp != '-') { builder.deleteCharAt(i); if (Character.isSupplementaryCodePoint(cp)) { i--; builder.deleteCharAt(i); } } } super.insertString(fb, offset, builder.toString(), attr); }
/** * Creates a String representation of the given object. * * @param certificate to print * @return the String representation */ private String toString(Object certificate) { final StringBuilder sb = new StringBuilder(); sb.append("<html><body>\n"); if (certificate instanceof X509Certificate) { renderX509(sb, (X509Certificate) certificate); } else { sb.append("<pre>\n"); sb.append(certificate.toString()); sb.append("</pre>\n"); } sb.append("</body></html>"); return sb.toString(); }
/** * Writes the <code>shape</code>, <code>coords</code>, <code>href</code>, * <code>nohref</code> Attribute for the specified figure and shape. * * @return Returns true, if the polygon is inside of the image bounds. */ private boolean writePolyAttributes(IXMLElement elem, SVGFigure f, Shape shape) { AffineTransform t = TRANSFORM.getClone(f); if (t == null) { t = drawingTransform; } else { t.preConcatenate(drawingTransform); } StringBuilder buf = new StringBuilder(); float[] coords = new float[6]; GeneralPath path = new GeneralPath(); for (PathIterator i = shape.getPathIterator(t, 1.5f); ! i.isDone(); i.next()) { switch (i.currentSegment(coords)) { case PathIterator.SEG_MOVETO : if (buf.length() != 0) { throw new IllegalArgumentException("Illegal shape "+shape); } if (buf.length() != 0) { buf.append(','); } buf.append((int) coords[0]); buf.append(','); buf.append((int) coords[1]); path.moveTo(coords[0], coords[1]); break; case PathIterator.SEG_LINETO : if (buf.length() != 0) { buf.append(','); } buf.append((int) coords[0]); buf.append(','); buf.append((int) coords[1]); path.lineTo(coords[0], coords[1]); break; case PathIterator.SEG_CLOSE : path.closePath(); break; default : throw new InternalError("Illegal segment type "+i.currentSegment(coords)); } } elem.setAttribute("shape", "poly"); elem.setAttribute("coords", buf.toString()); writeHrefAttribute(elem, f); return path.intersects(new Rectangle2D.Float(bounds.x, bounds.y, bounds.width, bounds.height)); }
public void showItem() { if (!this.editorPanel.getViewer().isLanguageFunctionAvailable()) { return; } this.highlight = this.editorPanel .getEditor() .addHighlight(this.position, this.position + this.word.length(), null, true); final FindSynonymsActionHandler _this = this; QTextEditor editor = this.editorPanel.getEditor(); Rectangle r = null; try { r = editor.modelToView(this.position); } catch (Exception e) { // BadLocationException! Environment.logError("Location: " + this.position + " is not valid", e); UIUtils.showErrorMessage(this.editorPanel, "Unable to display synonyms."); return; } int y = r.y; // Show a panel of all the items. final QPopup p = this.popup; p.setOpaque(false); Synonyms syns = null; try { syns = this.projectViewer.getSynonymProvider().getSynonyms(this.word); } catch (Exception e) { UIUtils.showErrorMessage(this.editorPanel, "Unable to display synonyms."); Environment.logError("Unable to lookup synonyms for: " + word, e); return; } if ((syns.words.size() == 0) && (this.word.toLowerCase().endsWith("ed"))) { // Trim off the ed and try again. try { syns = this.projectViewer.getSynonyms(this.word.substring(0, this.word.length() - 2)); } catch (Exception e) { UIUtils.showErrorMessage(this.editorPanel, "Unable to display synonyms."); Environment.logError("Unable to lookup synonyms for: " + word, e); return; } } if ((syns.words.size() == 0) && (this.word.toLowerCase().endsWith("s"))) { // Trim off the ed and try again. try { syns = this.projectViewer.getSynonyms(this.word.substring(0, this.word.length() - 1)); } catch (Exception e) { UIUtils.showErrorMessage(this.editorPanel, "Unable to display synonyms."); Environment.logError("Unable to lookup synonyms for: " + word, e); return; } } StringBuilder sb = new StringBuilder(); if (syns.words.size() > 0) { sb.append("6px"); for (int i = 0; i < syns.words.size(); i++) { if (sb.length() > 0) { sb.append(", "); } sb.append("p, 3px, [p,90px], 5px"); } /* if (syns.words.size () > 0) { sb.append (",5px"); } */ } else { sb.append("6px, p, 6px"); } FormLayout summOnly = new FormLayout("3px, fill:380px:grow, 3px", sb.toString()); PanelBuilder pb = new PanelBuilder(summOnly); CellConstraints cc = new CellConstraints(); int ind = 2; Map<String, String> names = new HashMap(); names.put(Synonyms.ADJECTIVE + "", "Adjectives"); names.put(Synonyms.NOUN + "", "Nouns"); names.put(Synonyms.VERB + "", "Verbs"); names.put(Synonyms.ADVERB + "", "Adverbs"); names.put(Synonyms.OTHER + "", "Other"); if (syns.words.size() == 0) { JLabel l = new JLabel("No synonyms found."); l.setFont(l.getFont().deriveFont(Font.ITALIC)); pb.add(l, cc.xy(2, 2)); } // Determine what type of word we are looking for. for (Synonyms.Part i : syns.words) { JLabel l = new JLabel(names.get(i.type + "")); l.setFont(l.getFont().deriveFont(Font.ITALIC)); l.setFont(l.getFont().deriveFont((float) UIUtils.getEditorFontSize(10))); l.setBorder( new CompoundBorder( new MatteBorder(0, 0, 1, 0, Environment.getBorderColor()), new EmptyBorder(0, 0, 3, 0))); pb.add(l, cc.xy(2, ind)); ind += 2; HTMLEditorKit kit = new HTMLEditorKit(); HTMLDocument doc = (HTMLDocument) kit.createDefaultDocument(); JTextPane t = new JTextPane(doc); t.setEditorKit(kit); t.setEditable(false); t.setOpaque(false); StringBuilder buf = new StringBuilder( "<style>a { text-decoration: none; } a:hover { text-decoration: underline; }</style><span style='color: #000000; font-size: " + ((int) UIUtils.getEditorFontSize(10) /*t.getFont ().getSize () + 2*/) + "pt; font-family: " + t.getFont().getFontName() + ";'>"); for (int x = 0; x < i.words.size(); x++) { String w = (String) i.words.get(x); buf.append("<a class='x' href='http://" + w + "'>" + w + "</a>"); if (x < (i.words.size() - 1)) { buf.append(", "); } } buf.append("</span>"); t.setText(buf.toString()); t.addHyperlinkListener( new HyperlinkAdapter() { public void hyperlinkUpdate(HyperlinkEvent ev) { if (ev.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { QTextEditor ed = _this.editorPanel.getEditor(); ed.replaceText( _this.position, _this.position + _this.word.length(), ev.getURL().getHost()); ed.removeHighlight(_this.highlight); _this.popup.setVisible(false); _this.projectViewer.fireProjectEvent( ProjectEvent.SYNONYM, ProjectEvent.REPLACE, ev.getURL().getHost()); } } }); // Annoying that we have to do this but it prevents the text from being too small. t.setSize(new Dimension(380, Short.MAX_VALUE)); JScrollPane sp = new JScrollPane(t); t.setCaretPosition(0); sp.setOpaque(false); sp.getVerticalScrollBar().setValue(0); /* sp.setPreferredSize (t.getPreferredSize ()); sp.setMaximumSize (new Dimension (380, 75)); */ sp.getViewport().setOpaque(false); sp.setOpaque(false); sp.setBorder(null); sp.getViewport().setBackground(Color.WHITE); sp.setAlignmentX(Component.LEFT_ALIGNMENT); pb.add(sp, cc.xy(2, ind)); ind += 2; } JPanel pan = pb.getPanel(); pan.setOpaque(true); pan.setBackground(Color.WHITE); this.popup.setContent(pan); // r.y -= this.editorPanel.getScrollPane ().getVerticalScrollBar ().getValue (); Point po = SwingUtilities.convertPoint(editor, r.x, r.y, this.editorPanel); r.x = po.x; r.y = po.y; // Subtract the insets of the editorPanel. Insets ins = this.editorPanel.getInsets(); r.x -= ins.left; r.y -= ins.top; this.editorPanel.showPopupAt(this.popup, r, "above", true); }
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException { StringBuilder builder = new StringBuilder(string); // 过滤用户输入的所有字符 filterInt(builder); super.insertString(fb, offset, builder.toString(), attr); }
/** * This methods provides a readable classname. If the supplied name parameter denotes an array * this method returns either the classname of the component type for arrays of java reference * types or the name of the primitive type for arrays of java primitive types followed by n-times * "[]" where 'n' denotes the arity of the array. Otherwise, if the supplied name doesn't denote * an array it returns the same classname. */ public static String getReadableClassName(String name) { String className = getArrayClassName(name); if (className == null) return name; int index = name.lastIndexOf("["); StringBuilder brackets = new StringBuilder(className); for (int i = 0; i <= index; i++) { brackets.append("[]"); } return brackets.toString(); }
public void replace(FilterBypass fb, int offset, int length, String string, AttributeSet attr) throws BadLocationException { if (string != null) { StringBuilder builder = new StringBuilder(string); // 过滤用户替换的所有字符 filterInt(builder); string = builder.toString(); } super.replace(fb, offset, length, string, attr); }
/** * Converts the byte array to hex string. * * @param raw the data. * @return the hex string. */ private String getHex(byte[] raw) { if (raw == null) return null; StringBuilder hex = new StringBuilder(2 * raw.length); Formatter f = new Formatter(hex); try { for (byte b : raw) f.format("%02x", b); } finally { f.close(); } return hex.toString(); }
private String htmlize(String msg) { StringBuilder sb = new StringBuilder(); Pattern patMsgCat = Pattern.compile("\\[(.+?)\\].*"); msg = msg.replace("&", "&").replace("<", "<").replace(">", ">"); for (String line : msg.split(lineSep)) { Matcher m = patMsgCat.matcher(line); String cls = "normal"; if (m.matches()) { cls = m.group(1); } line = "<span class='" + cls + "'>" + line + "</span>"; sb.append(line).append("<br>"); } return sb.toString(); }
@Override public void insertString( FilterBypass filterBypass, int offset, String text, AttributeSet attributeSet) throws BadLocationException { text = trimHexadecimal(text); Document document = filterBypass.getDocument(); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(document.getText(0, document.getLength())); stringBuilder.insert(offset, text); if (isValidInput(stringBuilder.toString(), 0)) { super.insertString(filterBypass, offset, text, attributeSet); } else { Toolkit.getDefaultToolkit().beep(); } }
private String addWhiteSpace(Document doc, int offset) throws BadLocationException { StringBuilder whiteSpace = new StringBuilder("\n"); Element rootElement = doc.getDefaultRootElement(); int line = rootElement.getElementIndex(offset); int i = rootElement.getElement(line).getStartOffset(); while (true) { String temp = doc.getText(i, 1); if (temp.equals(" ") || temp.equals("\t")) { whiteSpace.append(temp); i++; } else break; } return whiteSpace.toString(); }
public String valueToString(Object value) throws ParseException { if (!(value instanceof byte[])) { throw new ParseException("该IP地址的值只能是字节数组", 0); } byte[] a = (byte[]) value; if (a.length != 4) { throw new ParseException("IP地址必须是四个整数", 0); } StringBuilder builder = new StringBuilder(); for (int i = 0; i < 4; i++) { int b = a[i]; if (b < 0) b += 256; builder.append(String.valueOf(b)); if (i < 3) builder.append('.'); } return builder.toString(); }
/** * Calculates the hash of the certificate known as the "thumbprint" and returns it as a string * representation. * * @param cert The certificate to hash. * @param algorithm The hash algorithm to use. * @return The SHA-1 hash of the certificate. * @throws CertificateException */ private static String getThumbprint(X509Certificate cert, String algorithm) throws CertificateException { MessageDigest digest; try { digest = MessageDigest.getInstance(algorithm); } catch (NoSuchAlgorithmException e) { throw new CertificateException(e); } byte[] encodedCert = cert.getEncoded(); StringBuilder sb = new StringBuilder(encodedCert.length * 2); Formatter f = new Formatter(sb); try { for (byte b : digest.digest(encodedCert)) f.format("%02x", b); } finally { f.close(); } return sb.toString(); }
@Override public void replace( DocumentFilter.FilterBypass fp, int offset, int length, String string, AttributeSet aset) throws BadLocationException { Document doc = fp.getDocument(); String oldText = doc.getText(0, doc.getLength()); StringBuilder sb = new StringBuilder(oldText); sb.replace(offset, offset + length, oldText); int len = string.length(); boolean isValidInteger = true; for (int i = 0; i < len; i++) { if (!Character.isDigit(string.charAt(i))) { isValidInteger = false; break; } } if (isValidInteger && verifyText(sb.toString())) { super.replace(fp, offset, length, string, aset); } else Toolkit.getDefaultToolkit().beep(); }
/** * Creates this account on the server. * * @return the created account */ public NewAccount createAccount() { // Check if the two passwords match. String pass1 = new String(passField.getPassword()); String pass2 = new String(retypePassField.getPassword()); if (!pass1.equals(pass2)) { showErrorMessage( IppiAccRegWizzActivator.getResources() .getI18NString("plugin.sipaccregwizz.NOT_SAME_PASSWORD")); return null; } NewAccount newAccount = null; try { StringBuilder registerLinkBuilder = new StringBuilder(registerLink); registerLinkBuilder .append(URLEncoder.encode("email", "UTF-8")) .append("=") .append(URLEncoder.encode(emailField.getText(), "UTF-8")) .append("&") .append(URLEncoder.encode("password", "UTF-8")) .append("=") .append(URLEncoder.encode(new String(passField.getPassword()), "UTF-8")) .append("&") .append(URLEncoder.encode("display_name", "UTF-8")) .append("=") .append(URLEncoder.encode(displayNameField.getText(), "UTF-8")) .append("&") .append(URLEncoder.encode("username", "UTF-8")) .append("=") .append(URLEncoder.encode(usernameField.getText(), "UTF-8")) .append("&") .append(URLEncoder.encode("user_agent", "UTF-8")) .append("=") .append(URLEncoder.encode("sip-communicator.org", "UTF-8")); URL url = new URL(registerLinkBuilder.toString()); URLConnection conn = url.openConnection(); // If this is not an http connection we have nothing to do here. if (!(conn instanceof HttpURLConnection)) { return null; } HttpURLConnection httpConn = (HttpURLConnection) conn; int responseCode = httpConn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // Read all the text returned by the server BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String str; StringBuffer stringBuffer = new StringBuffer(); while ((str = in.readLine()) != null) { stringBuffer.append(str); } if (logger.isInfoEnabled()) logger.info("JSON response to create account request: " + stringBuffer.toString()); newAccount = parseHttpResponse(stringBuffer.toString()); } } catch (MalformedURLException e1) { if (logger.isInfoEnabled()) logger.info("Failed to create URL with string: " + registerLink, e1); } catch (IOException e1) { if (logger.isInfoEnabled()) logger.info("Failed to open connection.", e1); } return newAccount; }
void insertButton_actionPerformed(ActionEvent e) { Object selected = paramComboBox.getSelectedItem(); ConfigParamDescr descr; String key; int type = 0; String format = ""; if (selected instanceof ConfigParamDescr) { descr = (ConfigParamDescr) selected; key = descr.getKey(); type = descr.getType(); switch (type) { case ConfigParamDescr.TYPE_STRING: case ConfigParamDescr.TYPE_URL: case ConfigParamDescr.TYPE_BOOLEAN: format = "%s"; break; case ConfigParamDescr.TYPE_INT: case ConfigParamDescr.TYPE_LONG: case ConfigParamDescr.TYPE_POS_INT: NumericPaddingDialog dialog = new NumericPaddingDialog(); Point pos = this.getLocationOnScreen(); dialog.setLocation(pos.x, pos.y); dialog.pack(); dialog.setVisible(true); StringBuilder fbuf = new StringBuilder("%"); int width = dialog.getPaddingSize(); boolean is_zero = dialog.useZero(); if (width > 0) { fbuf.append("."); if (is_zero) { fbuf.append(0); } fbuf.append(width); } if (type == ConfigParamDescr.TYPE_LONG) { fbuf.append("ld"); } else { fbuf.append("d"); } format = fbuf.toString(); break; case ConfigParamDescr.TYPE_YEAR: if (key.startsWith(DefinableArchivalUnit.PREFIX_AU_SHORT_YEAR)) { format = "%02d"; } else { format = "%d"; } break; case ConfigParamDescr.TYPE_RANGE: case ConfigParamDescr.TYPE_NUM_RANGE: case ConfigParamDescr.TYPE_SET: format = "%s"; break; } if (selectedPane == 0) { insertParameter(descr, format, editorPane.getSelectionStart()); } else if (selectedPane == 1) { // add the combobox data value to the edit box int pos = formatTextArea.getCaretPosition(); formatTextArea.insert(format, pos); pos = parameterTextArea.getCaretPosition(); parameterTextArea.insert(", " + key, pos); } } else { key = selected.toString(); format = escapePrintfChars( (String) JOptionPane.showInputDialog( this, "Enter the string you wish to input", "String Literal Input", JOptionPane.OK_CANCEL_OPTION)); if (StringUtil.isNullString(format)) { return; } if (selectedPane == 0) { insertText(format, PLAIN_ATTR, editorPane.getSelectionStart()); } else if (selectedPane == 1) { // add the combobox data value to the edit box formatTextArea.insert(format, formatTextArea.getCaretPosition()); } } }