@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()); }
@NotNull public static String getLibraryName(@NotNull Library library) { final String result = library.getName(); if (result != null) { return result; } String[] endingsToStrip = {"/", "!", ".jar"}; StringBuilder buffer = new StringBuilder(); for (OrderRootType type : OrderRootType.getAllTypes()) { for (String url : library.getUrls(type)) { buffer.setLength(0); buffer.append(url); for (String ending : endingsToStrip) { if (buffer.lastIndexOf(ending) == buffer.length() - ending.length()) { buffer.setLength(buffer.length() - ending.length()); } } final int i = buffer.lastIndexOf(PATH_SEPARATOR); if (i < 0 || i >= buffer.length() - 1) { continue; } String candidate = buffer.substring(i + 1); if (!StringUtil.isEmpty(candidate)) { return candidate; } } } assert false; return "unknown-lib"; }
private boolean getNextEntryURL(String allText, int entryNumber, Map<String, JLabel> entries) { String toFind = "<div class=\"numbering\">"; int index = allText.indexOf(toFind, piv); int endIndex = allText.indexOf("<br clear=\"all\" />", index); piv = endIndex; if (index >= 0) { String text = allText.substring(index, endIndex); // Always try RIS import first Matcher fullCitation = ACMPortalFetcher.FULL_CITATION_PATTERN.matcher(text); String item; if (fullCitation.find()) { String link = getEntryBibTeXURL(fullCitation.group(1)); if (endIndex > 0) { StringBuilder sb = new StringBuilder(); // Find authors: String authMarker = "<div class=\"authors\">"; int authStart = text.indexOf(authMarker); if (authStart >= 0) { int authEnd = text.indexOf("</div>", authStart + authMarker.length()); if (authEnd >= 0) { sb.append("<p>").append(text.substring(authStart, authEnd)).append("</p>"); } } // Find title: Matcher titM = ACMPortalFetcher.TITLE_PATTERN.matcher(text); if (titM.find()) { sb.append("<p>").append(titM.group(1)).append("</p>"); } String sourceMarker = "<div class=\"source\">"; int sourceStart = text.indexOf(sourceMarker); if (sourceStart >= 0) { int sourceEnd = text.indexOf("</div>", sourceStart + sourceMarker.length()); if (sourceEnd >= 0) { String sourceText = text.substring(sourceStart, sourceEnd); // Find source: Matcher source = ACMPortalFetcher.SOURCE_PATTERN.matcher(sourceText); if (source.find()) { sb.append("<p>").append(source.group(1)).append("</p>"); } } } item = sb.toString(); } else { item = link; } JLabel preview = new JLabel("<html>" + item + "</html>"); preview.setPreferredSize(new Dimension(750, 100)); entries.put(link, preview); return true; } LOGGER.warn("Citation unmatched " + Integer.toString(entryNumber)); return false; } return false; }
private static void formatStyle( final StringBuilder builder, final SimpleTextAttributes attributes) { final Color fgColor = attributes.getFgColor(); final Color bgColor = attributes.getBgColor(); final int style = attributes.getStyle(); final int pos = builder.length(); if (fgColor != null) { builder .append("color:#") .append(Integer.toString(fgColor.getRGB() & 0xFFFFFF, 16)) .append(';'); } if (bgColor != null) { builder .append("background-color:#") .append(Integer.toString(bgColor.getRGB() & 0xFFFFFF, 16)) .append(';'); } if ((style & SimpleTextAttributes.STYLE_BOLD) != 0) { builder.append("font-weight:bold;"); } if ((style & SimpleTextAttributes.STYLE_ITALIC) != 0) { builder.append("font-style:italic;"); } if ((style & SimpleTextAttributes.STYLE_UNDERLINE) != 0) { builder.append("text-decoration:underline;"); } else if ((style & SimpleTextAttributes.STYLE_STRIKEOUT) != 0) { builder.append("text-decoration:line-through;"); } if (builder.length() > pos) { builder.insert(pos, " style=\""); builder.append('"'); } }
private void replaceCollectionGetAccess( PsiElement element, String contentVariableName, PsiVariable listVariable, String indexName, PsiElement childToSkip, StringBuilder out) { if (isListGetLookup(element, indexName, listVariable)) { out.append(contentVariableName); } else { final PsiElement[] children = element.getChildren(); if (children.length == 0) { final String text = element.getText(); if (PsiKeyword.INSTANCEOF.equals(text) && out.charAt(out.length() - 1) != ' ') { out.append(' '); } out.append(text); } else { boolean skippingWhiteSpace = false; for (final PsiElement child : children) { if (child.equals(childToSkip)) { skippingWhiteSpace = true; } else if (child instanceof PsiWhiteSpace && skippingWhiteSpace) { // don't do anything } else { skippingWhiteSpace = false; replaceCollectionGetAccess( child, contentVariableName, listVariable, indexName, childToSkip, out); } } } } }
@Nullable private LookupFile getClosestParent(final String typed) { if (typed == null) return null; LookupFile lastFound = myFinder.find(typed); if (lastFound == null) return null; if (lastFound.exists()) { if (typed.charAt(typed.length() - 1) != File.separatorChar) return lastFound.getParent(); return lastFound; } final String[] splits = myFinder.normalize(typed).split(myFileSpitRegExp); StringBuilder fullPath = new StringBuilder(); for (int i = 0; i < splits.length; i++) { String each = splits[i]; fullPath.append(each); if (i < splits.length - 1) { fullPath.append(myFinder.getSeparator()); } final LookupFile file = myFinder.find(fullPath.toString()); if (file == null || !file.exists()) return lastFound; lastFound = file; } return lastFound; }
private void replaceIteratorNext( PsiElement element, String contentVariableName, String iteratorName, PsiElement childToSkip, StringBuilder out, PsiType contentType) { if (isIteratorNext(element, iteratorName, contentType)) { out.append(contentVariableName); } else { final PsiElement[] children = element.getChildren(); if (children.length == 0) { final String text = element.getText(); if (PsiKeyword.INSTANCEOF.equals(text) && out.charAt(out.length() - 1) != ' ') { out.append(' '); } out.append(text); } else { boolean skippingWhiteSpace = false; for (final PsiElement child : children) { if (child.equals(childToSkip)) { skippingWhiteSpace = true; } else if (child instanceof PsiWhiteSpace && skippingWhiteSpace) { // don't do anything } else { skippingWhiteSpace = false; replaceIteratorNext( child, contentVariableName, iteratorName, childToSkip, out, contentType); } } } } }
@NotNull protected JLabel formatToLabel(@NotNull JLabel label) { label.setIcon(myIcon); if (!myFragments.isEmpty()) { final StringBuilder text = new StringBuilder(); text.append("<html><body style=\"white-space:nowrap\">"); for (int i = 0; i < myFragments.size(); i++) { final String fragment = myFragments.get(i); final SimpleTextAttributes attributes = myAttributes.get(i); final Object tag = getFragmentTag(i); if (tag instanceof BrowserLauncherTag) { formatLink(text, fragment, attributes, ((BrowserLauncherTag) tag).myUrl); } else { formatText(text, fragment, attributes); } } text.append("</body></html>"); label.setText(text.toString()); } return label; }
public void toString0(StringBuilder sb, String indentString) { sb.append(indentString); sb.append(" value: "); sb.append(value); sb.append("\n"); toString1(sb, indentString); }
@NotNull public static String rightJustify(@NotNull String text, int width, char fillChar) { final StringBuilder builder = new StringBuilder(text); for (int i = text.length(); i < width; i++) { builder.insert(0, fillChar); } return builder.toString(); }
// 过滤整数字符,把所有非0~9的字符全部删除 private void filterInt(StringBuilder builder) { for (int i = builder.length() - 1; i >= 0; i--) { int cp = builder.codePointAt(i); if (cp > '9' || cp < '0') { builder.deleteCharAt(i); } } }
void log(@NonNls String msg, Document document, boolean synchronously, @NonNls Object... args) { if (debug()) { @NonNls String s = (SwingUtilities.isEventDispatchThread() ? "- " : "-") + msg + (synchronously ? " (sync)" : "") + (document == null ? "" : "; Document: " + System.identityHashCode(document) + "; stage: " + getCommitStage(document)) + "; my indic=" + myProgressIndicator + " ||"; for (Object arg : args) { s += "; " + arg; } System.out.println(s); synchronized (log) { log.append(s).append("\n"); if (log.length() > 1000000) { log.delete(0, 1000000); } } } }
public int searchWord(@NotNull Editor editor, int count, boolean whole, int dir) { TextRange range = SearchHelper.findWordUnderCursor(editor); if (range == null) { return -1; } StringBuilder pattern = new StringBuilder(); if (whole) { pattern.append("\\<"); } pattern.append(EditorHelper.getText(editor, range.getStartOffset(), range.getEndOffset())); if (whole) { pattern.append("\\>"); } MotionGroup.moveCaret(editor, range.getStartOffset()); lastSearch = pattern.toString(); setLastPattern(editor, lastSearch); lastOffset = ""; lastDir = dir; searchHighlight(true); return findItOffset(editor, editor.getCaretModel().getOffset(), count, lastDir, true); }
private void logTrace(StringBuilder builder, Throwable e) { Throwable parent = e; String indent = " "; while (parent != null) { if (parent == e) { builder.append(indent).append("Trace:").append("\n"); } else { builder .append(indent) .append("Caused By: (") .append(parent.getClass().getSimpleName()) .append(")") .append("\n"); builder .append(indent) .append(" ") .append("[") .append(parent.getMessage()) .append("]") .append("\n"); } for (StackTraceElement ele : e.getStackTrace()) { builder.append(indent).append(" ").append(ele.toString()).append("\n"); } indent += " "; parent = parent.getCause(); } }
public void emit(Emitter emitter) { StringBuilder sb = emitter.getTextBuffer(); if (getCustomizedPrecedingComment().length() > 0) { sb.append("\n"); sb.append(getCustomizedPrecedingComment()); } emitAllElements(sb, emitter.getDocument()); if (getCustomizedTrailingComment().length() > 0) { sb.append("\n"); sb.append(getCustomizedTrailingComment()); } /** emit corresponding setter, overloaded methods, and related methods, if any. */ ListIterator li; if (isGetter()) { for (MethodEntry entry : myCorrespondingGetterSetters) { entry.emit(emitter); } } for (MethodEntry me : myOverloadedMethods) { me.emit(emitter); } for (MethodEntry me : sortedMethods) { me.emit(emitter); } }
private static void appendAbbreviated( StringBuilder to, String text, int start, int end, FontMetrics metrics, int maxWidth, boolean replaceLineTerminators) { int abbreviationLength = abbreviationLength(text, start, end, metrics, maxWidth, replaceLineTerminators); if (!replaceLineTerminators) { to.append(text, start, start + abbreviationLength); } else { CharSequenceSubSequence subSeq = new CharSequenceSubSequence(text, start, start + abbreviationLength); for (LineTokenizer lt = new LineTokenizer(subSeq); !lt.atEnd(); lt.advance()) { to.append(subSeq, lt.getOffset(), lt.getOffset() + lt.getLength()); if (lt.getLineSeparatorLength() > 0) { to.append(RETURN_SYMBOL); } } } if (abbreviationLength != end - start) { to.append(ABBREVIATION_SUFFIX); } }
@Override public String getEventMessage(LocatableEvent event) { final Location location = event.location(); String sourceName; try { sourceName = location.sourceName(); } catch (AbsentInformationException e) { sourceName = getFileName(); } final boolean printFullTrace = Registry.is("debugger.breakpoint.message.full.trace"); StringBuilder builder = new StringBuilder(); if (printFullTrace) { builder.append( DebuggerBundle.message( "status.line.breakpoint.reached.full.trace", DebuggerUtilsEx.getLocationMethodQName(location))); try { final List<StackFrame> frames = event.thread().frames(); renderTrace(frames, builder); } catch (IncompatibleThreadStateException e) { builder.append("Stacktrace not available: ").append(e.getMessage()); } } else { builder.append( DebuggerBundle.message( "status.line.breakpoint.reached", DebuggerUtilsEx.getLocationMethodQName(location), sourceName, getLineIndex() + 1)); } return builder.toString(); }
@Override JComponent description() { StringBuilder sb = new StringBuilder( "<html>" + Localization.lang("Changes have been made to the following metadata elements") + ":<p>"); for (MetaDataChangeUnit unit : changes) { sb.append("<br> "); sb.append(unit.key); /*switch (unit.type) { case ADD: sb.append("<p>Added: "+unit.key); break; case REMOVE: sb.append("<p>Removed: "+unit.key); break; case MODIFY: sb.append("<p>Modified: "+unit.key); break; }*/ } sb.append("</html>"); tp.setText(sb.toString()); return sp; }
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); }
@Override public void keyTyped(final KeyEvent e) { if (undo == null || control(e) || DELNEXT.is(e) || DELPREV.is(e) || ESCAPE.is(e)) return; text.pos(text.cursor()); // string to be added String ch = String.valueOf(e.getKeyChar()); // remember if marked text is to be deleted boolean del = true; final byte[] txt = text.text(); if (TAB.is(e)) { if (text.marked()) { // check if lines are to be indented final int s = Math.min(text.pos(), text.start()); final int l = Math.max(text.pos(), text.start()) - 1; for (int p = s; p <= l && p < txt.length; p++) del &= txt[p] != '\n'; if (!del) { text.indent(s, l, e.isShiftDown()); ch = null; } } else { boolean c = true; for (int p = text.pos() - 1; p >= 0 && c; p--) { final byte b = txt[p]; c = ws(b); if (b == '\n') break; } if (c) ch = " "; } } // delete marked text if (text.marked() && del) text.delete(); if (ENTER.is(e)) { // adopt indentation from previous line final StringBuilder sb = new StringBuilder(1).append(e.getKeyChar()); int s = 0; for (int p = text.pos() - 1; p >= 0; p--) { final byte b = txt[p]; if (b == '\n') break; if (b == '\t') { s += 2; } else if (b == ' ') { s++; } else { s = 0; } } for (int p = 0; p < s; p++) sb.append(' '); ch = sb.toString(); } if (ch != null) text.add(ch); text.setCaret(); rend.calc(); showCursor(2); e.consume(); }
private void setupPanels(@Nullable ProjectTemplate template) { restorePanel(myNamePathComponent, 4); restorePanel(myModulePanel, myWizardContext.isCreatingNewProject() ? 8 : 6); restorePanel(myExpertPanel, myWizardContext.isCreatingNewProject() ? 1 : 0); mySettingsStep = myModuleBuilder == null ? null : myModuleBuilder.modifySettingsStep(this); String description = null; if (template != null) { description = template.getDescription(); if (StringUtil.isNotEmpty(description)) { StringBuilder sb = new StringBuilder("<html><body><font "); sb.append(SystemInfo.isMac ? "" : "face=\"Verdana\" size=\"-1\"").append('>'); sb.append(description).append("</font></body></html>"); description = sb.toString(); myDescriptionPane.setText(description); } } myExpertPlaceholder.setVisible( !(myModuleBuilder instanceof TemplateModuleBuilder) && myExpertPanel.getComponentCount() > 0); for (int i = 0; i < 6; i++) { myModulePanel.getComponent(i).setVisible(!(myModuleBuilder instanceof EmptyModuleBuilder)); } myDescriptionPanel.setVisible(StringUtil.isNotEmpty(description)); mySettingsPanel.revalidate(); mySettingsPanel.repaint(); }
public static String ObtenerHash(String stringToHash) { if (stringToHash.length() > 5) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] bytes = md5.digest(stringToHash.getBytes()); StringBuilder sb = new StringBuilder(2 * bytes.length); for (int i = 0; i < bytes.length; i++) { int low = bytes[i] & 0x0f; int high = (bytes[i] & 0xf0) >> 4; sb.append(HEXADECIMAL[high]); sb.append(HEXADECIMAL[low]); } return sb.toString(); } catch (NoSuchAlgorithmException e) { // Manejo de Excepcion System.out.println("Excepción: No se pudo obtener la suma de verificación"); return null; } } else { System.out.println("Se necesitan 5 caracteres como minimo para crear la suma"); System.out.println("LA cedena devuelsa sera nula"); } return null; }
public static EventHandler<ActionEvent> getBrowseHandler( FXController controller, TextField filePath) { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Select a file to upload..."); return e -> { if (AESCTR.secretKey == null) { new Alert(Alert.AlertType.INFORMATION, "Please generate or choose a key", ButtonType.OK) .showAndWait(); return; } selectedFiles = fileChooser.showOpenMultipleDialog(null); if (selectedFiles != null) { controller.writeLog("Selected files: "); StringBuilder sb = new StringBuilder(1024); for (int i = 0; i < selectedFiles.size(); i++) { if (i == selectedFiles.size() - 1) { sb.append(selectedFiles.get(i).getAbsolutePath()); } else { sb.append(selectedFiles.get(i).getAbsolutePath() + ", "); } controller.writeLog(selectedFiles.get(i).getName()); } filePath.setText(sb.toString()); } }; }
private String getFormattedStackTrace(StackTraceElement[] stacktrace) { StringBuilder sb = new StringBuilder(); for (StackTraceElement element : stacktrace) { sb.append(element.toString()).append("\n"); } return sb.toString(); }
/** * InputMethod implementation For details read * http://docs.oracle.com/javase/7/docs/technotes/guides/imf/api-tutorial.html */ @Override protected void processInputMethodEvent(InputMethodEvent e) { int commitCount = e.getCommittedCharacterCount(); if (commitCount > 0) { myInputMethodUncommitedChars = null; AttributedCharacterIterator text = e.getText(); if (text != null) { StringBuilder sb = new StringBuilder(); //noinspection ForLoopThatDoesntUseLoopVariable for (char c = text.first(); commitCount > 0; c = text.next(), commitCount--) { if (c >= 0x20 && c != 0x7F) { // Hack just like in // javax.swing.text.DefaultEditorKit.DefaultKeyTypedAction sb.append(c); } } myTerminalStarter.sendString(sb.toString()); } } else { myInputMethodUncommitedChars = uncommitedChars(e.getText()); } }
private String convertTraceToSeq(XTrace trace) { StringBuilder sb = new StringBuilder(); for (XEvent e : trace) { sb.append(e.getAttributes().get("concept:name")); sb.append(" "); } return sb.toString(); }
public String toString() { StringBuilder sb = new StringBuilder(); for (Iterator<Integer> integerIterator = digits.iterator(); integerIterator.hasNext(); ) { sb.append(integerIterator.next()); if (integerIterator.hasNext()) sb.append("."); } return sb.toString(); }
protected String consume(BufferedReader br) throws Exception { StringBuilder ret = new StringBuilder(); int ch; while ((ch = br.read()) != -1) ret.appendCodePoint(ch); return ret.toString(); }
private static String generateKey(final int size) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < size; i++) { int idx = rand.nextInt(ALPHANUMERIC.length()); sb.append(ALPHANUMERIC.substring(idx, idx + 1)); } return (sb.toString()); }
@Override @NonNls public String toString() { StringBuilder sb = new StringBuilder("Content name=").append(myDisplayName); if (myIsLocked) sb.append(", pinned"); if (myExecutionId != 0) sb.append(", executionId=").append(myExecutionId); return sb.toString(); }