/** * Forces the action set to be loaded. Plugins and macros should not call this method. * * @since jEdit 4.2pre1 */ public void load() { if (loaded) return; loaded = true; // actions.clear(); if (uri == null) return; try { Log.log(Log.DEBUG, this, "Loading actions from " + uri); ActionListHandler ah = new ActionListHandler(uri.toString(), this); InputStream in = uri.openStream(); if (in == null) { // this happened when calling generateCache() in the context of 'find orphan jars' // in org.gjt.sp.jedit.pluginmgr.ManagePanel.FindOrphan.actionPerformed(ActionEvent) // because for not loaded plugins, the plugin will not be added to the list of pluginJars // so the org.gjt.sp.jedit.proto.jeditresource.PluginResURLConnection will not find the // plugin // to read the resource from. // Better log a small error message than a big stack trace Log.log(Log.WARNING, this, "Unable to open: " + uri); } else if (XMLUtilities.parseXML(in, ah)) { Log.log(Log.ERROR, this, "Unable to parse: " + uri); } } catch (IOException e) { Log.log(Log.ERROR, this, uri, e); } } // }}}
@Override public void endElement(String uri, String localName, String name) { if ("ENTRY".equals(name)) { result.addLast(new Entry(path, caret, selection, encoding, mode)); path = null; caret = 0; selection = null; encoding = null; mode = null; } else if ("PATH".equals(name)) path = charData.toString(); else if ("CARET".equals(name)) { try { String s = charData.toString().trim(); if (s.length() != charData.length()) { Log.log( Log.WARNING, this, "The caret position in recent.xml was wrong: '" + charData + "', fixing it"); } caret = Integer.parseInt(s); } catch (NumberFormatException e) { Log.log(Log.ERROR, this, "Unable to parse caret position " + charData); } } else if ("SELECTION".equals(name)) selection = charData.toString(); else if ("ENCODING".equals(name)) encoding = charData.toString(); else if ("MODE".equals(name)) mode = charData.toString(); charData.setLength(0); }
/** * @param evt the keyboard event * @param from the source, it can be {@link org.gjt.sp.jedit.View#VIEW}, {@link * org.gjt.sp.jedit.View#ACTION_BAR} or {@link org.gjt.sp.jedit.View#TEXT_AREA} * @param mode the mode is "press" or "type" and is used for debug only * @param global tell if the event comes from the DefaultKeyboardFocusManager or not */ protected void processKeyEventKeyStrokeHandling( KeyEvent evt, int from, String mode, boolean global) { KeyEventTranslator.Key keyStroke = KeyEventTranslator.translateKeyEvent(evt); if (keyStroke != null) { keyStroke.setIsFromGlobalContext(global); if (Debug.DUMP_KEY_EVENTS) { Log.log(Log.DEBUG, this, "Translated (key " + mode + "): " + keyStroke + " from " + from); } boolean consumed = false; if (handleKey(keyStroke, false)) { evt.consume(); consumed = true; } if (Debug.DUMP_KEY_EVENTS) { Log.log( Log.DEBUG, this, "Translated (key " + mode + "): " + keyStroke + " from " + from + ": consumed=" + consumed + '.'); } } } // }}}
/** * overriding getResource() because we want to search FIRST in this ClassLoader, then the parent, * the path, etc. */ public URL getResource(String name) { try { if (jar != null) { ZipFile zipFile = jar.getZipFile(); ZipEntry entry = zipFile.getEntry(name); if (entry != null) { return new URL(getResourceAsPath(name)); } } Object obj = resourcesHash.get(name); if (obj instanceof JARClassLoader) { JARClassLoader classLoader = (JARClassLoader) obj; return classLoader.getResource(name); } else { URL ret = getSystemResource(name); if (ret != null) { Log.log( Log.DEBUG, JARClassLoader.class, "Would have returned null for getResource(" + name + ")"); Log.log(Log.DEBUG, JARClassLoader.class, "returning(" + ret + ")"); } return ret; } } catch (IOException io) { Log.log(Log.ERROR, this, io); return null; } } // }}}
public ErrorEntry(String path, String messageProp, Object[] args) { this.path = path; String message = jEdit.getProperty(messageProp, args); if (message == null) message = "Undefined property: " + messageProp; Log.log(Log.ERROR, this, path + ":"); Log.log(Log.ERROR, this, message); Vector tokenizedMessage = new Vector(); int lastIndex = -1; for (int i = 0; i < message.length(); i++) { if (message.charAt(i) == '\n') { tokenizedMessage.addElement(message.substring(lastIndex + 1, i)); lastIndex = i; } } if (lastIndex != message.length()) { tokenizedMessage.addElement(message.substring(lastIndex + 1)); } messages = new String[tokenizedMessage.size()]; tokenizedMessage.copyInto(messages); }
// NOTE leaves standard-out going to log public static <T> T suppressJEditErrorLog(Function<T> func, Object... params) { try { org.gjt.sp.util.Log.init(true, org.gjt.sp.util.Log.ERROR + 1); return func.apply(params); } finally { org.gjt.sp.util.Log.init(false, org.gjt.sp.util.Log.WARNING); } }
/** For debugging. */ public static void dump() { Log.log(Log.DEBUG, JARClassLoader.class, "Total instances created: " + INDEX); Log.log(Log.DEBUG, JARClassLoader.class, "Live instances: " + live); synchronized (classHash) { for (Map.Entry<String, Object> entry : classHash.entrySet()) { if (entry.getValue() != NO_CLASS) { Log.log(Log.DEBUG, JARClassLoader.class, entry.getKey() + " ==> " + entry.getValue()); } } } } // }}}
/** * Logs an error which threw an exception * * @param command The command that was running * @param message A message to the user * @param ex The exception */ public static void doError(String command, String message, Exception ex) { JOptionPane.showMessageDialog( null, "There was an error running the XInsert Script:\nCommand: " + command + ((message == null) ? "" : "\nMessage: " + message) + ((ex == null) ? "" : "\nException: " + ex.toString()), "Error Running XinsertScript", JOptionPane.ERROR_MESSAGE); Log.log(Log.ERROR, XScripter.class, command + ":" + message); Log.log(Log.ERROR, XScripter.class, ex); }
/** Load class from this JAR only. */ private synchronized Class _loadClass(String clazz, boolean resolveIt) throws ClassNotFoundException { jar.activatePlugin(); synchronized (this) { Class cls = findLoadedClass(clazz); if (cls != null) { if (resolveIt) resolveClass(cls); return cls; } String name = MiscUtilities.classToFile(clazz); try { definePackage(clazz); ZipFile zipFile = jar.getZipFile(); ZipEntry entry = zipFile.getEntry(name); if (entry == null) throw new ClassNotFoundException(clazz); InputStream in = zipFile.getInputStream(entry); int len = (int) entry.getSize(); byte[] data = new byte[len]; int success = 0; int offset = 0; while (success < len) { len -= success; offset += success; success = in.read(data, offset, len); if (success == -1) { Log.log( Log.ERROR, this, "Failed to load class " + clazz + " from " + zipFile.getName()); throw new ClassNotFoundException(clazz); } } cls = defineClass(clazz, data, 0, data.length); if (resolveIt) resolveClass(cls); return cls; } catch (IOException io) { Log.log(Log.ERROR, this, io); throw new ClassNotFoundException(clazz); } } } // }}}
// {{{ startDocument() method public void startDocument() { try { pushElement(null); } catch (Exception e) { Log.log(Log.ERROR, this, e); } } // }}}
public static Properties loadProperties(String fileName) { diag_println(DIAG_OFF, ".props : ", fileName); Properties props = new Properties(); if (notNullOrEmpty(fileName)) { InputStream in = null; try { JarFile jarFile = null; if (isJarUri(fileName)) { URL url = new URL(fileName); url = new URL(url.getFile()); String[] parts = url.getFile().split("!/"); jarFile = new JarFile(new File(parts[0])); JarEntry jarEntry = jarFile.getJarEntry(parts[1]); in = jarFile.getInputStream(jarEntry); } else { File file = new File(fileName); if (file.isFile()) { in = new FileInputStream(file); } else { in = PluginUtils.class.getResourceAsStream(fileName); } } props.load(in); if (jarFile != null) jarFile.close(); } catch (Exception e) { Log.log(Log.ERROR, PluginUtils.class + ".loadProperties", e); } finally { IOUtilities.closeQuietly((Closeable) in); } } return props; }
// {{{ getPrintJob() method private static PrinterJob getPrintJob(String jobName) { job = PrinterJob.getPrinterJob(); format = new HashPrintRequestAttributeSet(); String settings = jEdit.getSettingsDirectory(); if (settings != null) { String printSpecPath = MiscUtilities.constructPath(settings, "printspec"); File filePrintSpec = new File(printSpecPath); if (filePrintSpec.exists()) { try { FileInputStream fileIn = new FileInputStream(filePrintSpec); ObjectInputStream obIn = new ObjectInputStream(fileIn); format = (HashPrintRequestAttributeSet) obIn.readObject(); } catch (Exception e) { Log.log(Log.ERROR, BufferPrinter1_4.class, e); } // for backwards compatibility, the color variable is stored also as a property if (jEdit.getBooleanProperty("print.color")) format.add(Chromaticity.COLOR); else format.add(Chromaticity.MONOCHROME); // no need to always keep the same job name for every printout. format.add(new JobName(jobName, null)); } } return job; } // }}}
// {{{ load() method public static void load() { if (recentXML == null) return; if (!recentXML.fileExists()) return; Log.log(Log.MESSAGE, BufferHistory.class, "Loading " + recentXML); RecentHandler handler = new RecentHandler(); try { recentXML.load(handler); } catch (IOException e) { Log.log(Log.ERROR, BufferHistory.class, e); } trimToLimit(handler.result); history = handler.result; } // }}}
// {{{ EditServer constructor EditServer(String portFile) { super("jEdit server daemon [" + portFile + "]"); setDaemon(true); this.portFile = portFile; try { // On Unix, set permissions of port file to rw-------, // so that on broken Unices which give everyone read // access to user home dirs, people can't see your // port file (and hence send arbitriary BeanShell code // your way. Nasty.) if (OperatingSystem.isUnix()) { new File(portFile).createNewFile(); FileVFS.setPermissions(portFile, 0600); } // Bind to any port on localhost; accept 2 simultaneous // connection attempts before rejecting connections socket = new ServerSocket(0, 2, InetAddress.getByName("127.0.0.1")); authKey = new Random().nextInt(Integer.MAX_VALUE); int port = socket.getLocalPort(); FileWriter out = new FileWriter(portFile); try { out.write("b\n"); out.write(String.valueOf(port)); out.write("\n"); out.write(String.valueOf(authKey)); out.write("\n"); } finally { out.close(); } ok = true; Log.log(Log.DEBUG, this, "jEdit server started on port " + socket.getLocalPort()); Log.log(Log.DEBUG, this, "Authorization key is " + authKey); } catch (IOException io) { /* on some Windows versions, connections to localhost * fail if the network is not running. To avoid * confusing newbies with weird error messages, log * errors that occur while starting the server * as NOTICE, not ERROR */ Log.log(Log.NOTICE, this, io); } } // }}}
/** @deprecated Call <code>PluginJAR.getZipFile()</code> instead. */ public ZipFile getZipFile() { try { return jar.getZipFile(); } catch (IOException io) { Log.log(Log.ERROR, this, io); return null; } } // }}}
public static void registerVFS(String protocol, VFS vfs) { Log.log( Log.DEBUG, VFSManager.class, "Registered " + vfs.getName() + " filesystem for " + protocol + " protocol"); vfsHash.put(vfs.getName(), vfs); protocolHash.put(protocol, vfs); }
// {{{ _run() method @Override public void _run() { Log.log(Log.DEBUG, this, this + ".run()"); if (source != null) { // single file copy try { VFS.copy(this, source, target, comp, false, false); } catch (IOException e) { Log.log(Log.ERROR, this, e, e); } finally { if (latch != null) latch.countDown(); } } else { // List file copy copyFileList(); } } // }}}
// {{{ handleError() method static void handleError(Component comp, Exception e) { Log.log(Log.ERROR, SearchAndReplace.class, e); if (comp instanceof Dialog) { new TextAreaDialog((Dialog) comp, beanshell ? "searcherror-bsh" : "searcherror", e); } else { new TextAreaDialog((Frame) comp, beanshell ? "searcherror-bsh" : "searcherror", e); } } // }}}
/** Shows JSort help in the jEdit help viewer */ private void showHelp() { java.net.URL helpUrl = TextToolsSortDialog.class.getResource("TextTools.html"); if (helpUrl == null) { Log.log(Log.NOTICE, this, "Help URL is null, cannot display help"); } else { new org.gjt.sp.jedit.help.HelpViewer(helpUrl.toString()); } } // }}}
public static void setupSpellChecker(String path) { if (!fileExists(new File(path, "dictionaries.cnf"))) return; SpellChecker.setUserDictionaryProvider(new FileUserDictionary(path)); try { SpellChecker.registerDictionaries(new URL("file", null, path + "/"), null); } catch (MalformedURLException e) { Log.log(Log.ERROR, PluginUtils.class + ".setupSpellChecker", e); } }
// {{{ invoke() method public void invoke(View view) { try { BeanShell.runCachedBlock( code.get(), view, new NameSpace(BeanShell.getNameSpace(), "BeanShellAction.invoke()")); } catch (Throwable e) { Log.log(Log.ERROR, this, e); new BeanShellErrorDialog(view, e); } } // }}}
public static void parseBufferLocalProperties(Buffer buffer) { try { Class<?> cl = Class.forName("org.gjt.sp.jedit.buffer.JEditBuffer"); Method method = cl.getDeclaredMethod("parseBufferLocalProperties"); method.setAccessible(true); method.invoke(buffer); } catch (Exception e) { Log.log(Log.ERROR, PluginUtils.class + ".parseBufferLocalProperties", e); } }
// {{{ handleClient() method private boolean handleClient(final Socket client, DataInputStream in) throws Exception { int key = in.readInt(); if (key != authKey) { Log.log( Log.ERROR, this, client + ": wrong" + " authorization key (got " + key + ", expected " + authKey + ")"); in.close(); client.close(); return false; } else { // Reset the timeout client.setSoTimeout(0); Log.log(Log.DEBUG, this, client + ": authenticated" + " successfully"); final String script = in.readUTF(); Log.log(Log.DEBUG, this, script); SwingUtilities.invokeLater( new Runnable() { public void run() { try { NameSpace ns = new NameSpace(BeanShell.getNameSpace(), "EditServer namespace"); ns.setVariable("socket", client); BeanShell.eval(null, ns, script); } catch (org.gjt.sp.jedit.bsh.UtilEvalError e) { Log.log(Log.ERROR, this, e); } finally { try { BeanShell.getNameSpace().setVariable("socket", null); } catch (org.gjt.sp.jedit.bsh.UtilEvalError e) { Log.log(Log.ERROR, this, e); } } } }); return true; } } // }}}
public static void setEditPane(EditPane editPane) { View view = editPane.getView(); try { Class<?> cl = Class.forName("org.gjt.sp.jedit.View"); Method method = cl.getDeclaredMethod("setEditPane", EditPane.class); method.setAccessible(true); method.invoke(view, editPane); } catch (Exception e) { Log.log(Log.ERROR, PluginUtils.class + ".setEditPane", e); } }
// {{{ copyFileList() method private void copyFileList() { VFS vfs = VFSManager.getVFSForPath(target); Object targetSession = null; try { targetSession = vfs.createVFSSession(target, comp); if (targetSession == null) { Log.log(Log.ERROR, this, "Target VFS path cannot be reached"); return; } VFSFile targetFile = vfs._getFile(targetSession, target, comp); if (targetFile == null) { Log.log(Log.ERROR, this, "Target is unreachable or do not exist"); return; } if (targetFile.getType() != VFSFile.DIRECTORY) { Log.log(Log.ERROR, this, "Target is not a directory"); return; } if (sources != null) { setMaximum(sources.size()); for (int i = 0; i < sources.size(); i++) { setValue(i); String sourcePath = sources.get(i); String sourceName = MiscUtilities.getFileName(sourcePath); setLabel(sourceName); copy(targetSession, vfs, sourcePath, sourceName, target); } } } catch (IOException e) { Log.log(Log.ERROR, this, e); } catch (InterruptedException e) { Log.log(Log.WARNING, this, "Copy was interrupted"); } finally { VFSManager.sendVFSUpdate(vfs, target, true); try { if (targetSession != null) vfs._endVFSSession(targetSession, comp); } catch (IOException e) { } } } // }}}
/** * Returns an array of all action names in this action set that should be cached; namely, <code> * BeanShellAction</code>s. * * @since jEdit 4.2pre1 */ public String[] getCacheableActionNames() { LinkedList<String> retVal = new LinkedList<String>(); for (Object obj : actions.values()) { if (obj == placeholder) { // ??? this should only be called with // fully loaded action set Log.log(Log.WARNING, this, "Action set not up " + "to date"); } else if (obj instanceof JEditBeanShellAction) retVal.add(((JEditBeanShellAction) obj).getName()); } return retVal.toArray(new String[retVal.size()]); } // }}}
/** * Returns an action with the specified name. * * <p><b>Deferred loading:</b> this will load the action set if necessary. * * @param name The action name * @since jEdit 4.0pre1 */ public E getAction(String name) { Object obj = actions.get(name); if (obj == placeholder) { load(); obj = actions.get(name); if (obj == placeholder) { Log.log(Log.WARNING, this, "Outdated cache"); obj = null; } } return (E) obj; } // }}}
public void toggle(boolean featured, Job<Container> inIsolation, Object... args) { Object[] params = {null}; if (isolate(params)) { Container container = (Container) params[0]; if (inIsolation != null) try { inIsolation.perform(container, args); } catch (Exception e) { Log.log(Log.ERROR, getClass().getName() + ".toggle", e); } integrate(container, featured); } }
// {{{ loadMode() method public void loadMode(Mode mode, XModeHandler xmh) { String fileName = (String) mode.getProperty("file"); Log.log(Log.NOTICE, this, "Loading edit mode " + fileName); XMLReader parser; try { parser = XMLReaderFactory.createXMLReader(); } catch (SAXException saxe) { Log.log(Log.ERROR, this, saxe); return; } mode.setTokenMarker(xmh.getTokenMarker()); InputStream resource = ClassLoader.getSystemClassLoader().getResourceAsStream(fileName); if (resource == null) { // don't just print an error to console. This is a problem. throw new RuntimeException("File not found " + fileName); } BufferedReader br = new BufferedReader(new InputStreamReader(resource)); try { InputSource isrc = new InputSource(br); // isrc.setSystemId("jedit.jar"); parser.setContentHandler(xmh); parser.setDTDHandler(xmh); parser.setEntityResolver(xmh); parser.setErrorHandler(xmh); parser.parse(isrc); mode.setProperties(xmh.getModeProperties()); } catch (Throwable e) { error(fileName, e); } finally { IOUtilities.closeQuietly(resource); } } // }}}
// {{{ run() method public void run() { for (; ; ) { if (abort) return; Socket client = null; try { client = socket.accept(); // Stop script kiddies from opening the edit // server port and just leaving it open, as a // DoS client.setSoTimeout(1000); Log.log(Log.MESSAGE, this, client + ": connected"); DataInputStream in = new DataInputStream(client.getInputStream()); if (!handleClient(client, in)) abort = true; } catch (Exception e) { if (!abort) Log.log(Log.ERROR, this, e); abort = true; } finally { /* if(client != null) { try { client.close(); } catch(Exception e) { Log.log(Log.ERROR,this,e); } client = null; } */ } } } // }}}