/text/src/test/resources/examples/java/jruby.in.java
Java | 13963 lines | 12550 code | 421 blank | 992 comment | 360 complexity | 177e0295a7887cd9ab9c9ef722d9455d MD5 | raw file
Possible License(s): EPL-1.0, MPL-2.0-no-copyleft-exception
Large files files are truncated, but you can click here to view the full file
- package org.jruby;
- public enum CompatVersion {
- RUBY1_8, RUBY1_9, BOTH;
- public static CompatVersion getVersionFromString(String compatString) {
- if (compatString.equalsIgnoreCase("RUBY1_8")) {
- return CompatVersion.RUBY1_8;
- } else if (compatString.equalsIgnoreCase("RUBY1_9")) {
- return CompatVersion.RUBY1_9;
- } else {
- return null;
- }
- }
- }
- /***** BEGIN LICENSE BLOCK *****
- * Version: CPL 1.0/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Common Public
- * License Version 1.0 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of
- * the License at http://www.eclipse.org/legal/cpl-v10.html
- *
- * Software distributed under the License is distributed on an "AS
- * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
- * implied. See the License for the specific language governing
- * rights and limitations under the License.
- *
- * Copyright (C) 2007 Damian Steer <pldms@mac.com>
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either of the GNU General Public License Version 2 or later (the "GPL"),
- * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the CPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the CPL, the GPL or the LGPL.
- ***** END LICENSE BLOCK *****/
- package org.jruby;
- /**
- * An almost entirely useless interface for those objects that we _really_ want
- * to finalise.
- *
- * @author pldms
- *
- */
- public interface Finalizable {
- public void finalize();
- }
- /***** BEGIN LICENSE BLOCK *****
- * Version: CPL 1.0/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Common Public
- * License Version 1.0 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of
- * the License at http://www.eclipse.org/legal/cpl-v10.html
- *
- * Software distributed under the License is distributed on an "AS
- * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
- * implied. See the License for the specific language governing
- * rights and limitations under the License.
- *
- * Copyright (C) 2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
- * Copyright (C) 2002 Jan Arne Petersen <jpetersen@uni-bonn.de>
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either of the GNU General Public License Version 2 or later (the "GPL"),
- * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the CPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the CPL, the GPL or the LGPL.
- ***** END LICENSE BLOCK *****/
- package org.jruby;
- /**
- * Error numbers.
- * @fixme
- * this interface is a big hack defining a bunch of arbitrary valor as system call error numbers
- * this is actually because I need them but will probably need to be changed to something smarter
- * sooner or later.
- * The purpose of this class it to help implement the Errno module which in turn in needed by rubicon.
- * @author Benoit Cerrina
- **/
- public interface IErrno
- {
- int EPERM = 1;
- int ENOENT = 2;
- int ESRCH = 3;
- int EINTR = 4;
- int EIO = 5;
- int ENXIO = 6;
- int E2BIG = 7;
- int ENOEXEC = 8;
- int EBADF = 9;
- int ECHILD = 10;
- int EDEADLK = 11;
- int ENOMEM = 12;
- int EACCES = 13;
- int EFAULT = 14;
- int ENOTBLK = 15;
- int EBUSY = 16;
- int EEXIST = 17;
- int EXDEV = 18;
- int ENODEV = 19;
- int ENOTDIR = 20;
- int EISDIR = 21;
- int EINVAL = 22;
- int ENFILE = 23;
- int EMFILE = 24;
- int ENOTTY = 25;
- int ETXTBSY = 26;
- int EFBIG = 27;
- int ENOSPC = 28;
- int ESPIPE = 29;
- int EROFS = 30;
- int EMLINK = 31;
- int EPIPE = 32;
- int EDOM = 33;
- int ERANGE = 34;
- int EWOULDBLOCK = 35;
- int EAGAIN = 35;
- int EINPROGRESS = 36;
- int EALREADY = 37;
- int ENOTSOCK = 38;
- int EDESTADDRREQ = 39;
- int EMSGSIZE = 40;
- int EPROTOTYPE = 41;
- int ENOPROTOOPT = 42;
- int EPROTONOSUPPORT = 43;
- int ESOCKTNOSUPPORT = 44;
- int EOPNOTSUPP = 45;
- int EPFNOSUPPORT = 46;
- int EAFNOSUPPORT = 47;
- int EADDRINUSE = 48;
- int EADDRNOTAVAIL = 49;
- int ENETDOWN = 50;
- int ENETUNREACH = 51;
- int ENETRESET = 52;
- int ECONNABORTED = 53;
- int ECONNRESET = 54;
- int ENOBUFS = 55;
- int EISCONN = 56;
- int ENOTCONN = 57;
- int ESHUTDOWN = 58;
- int ETOOMANYREFS = 59;
- int ETIMEDOUT = 60;
- int ECONNREFUSED = 61;
- int ELOOP = 62;
- int ENAMETOOLONG = 63;
- int EHOSTDOWN = 64;
- int EHOSTUNREACH = 65;
- int ENOTEMPTY = 66;
- int EUSERS = 68;
- int EDQUOT = 69;
- int ESTALE = 70;
- int EREMOTE = 71;
- int ENOLCK = 77;
- int ENOSYS = 78;
- int EOVERFLOW = 84;
- int EIDRM = 90;
- int ENOMSG = 91;
- int EILSEQ = 92;
- int EBADMSG = 94;
- int EMULTIHOP = 95;
- int ENODATA = 96;
- int ENOLINK = 97;
- int ENOSR = 98;
- int ENOSTR = 99;
- int EPROTO = 100;
- int ETIME = 101;
- int EOPNOTSUPP_DARWIN = 102;
- }
- /*
- ***** BEGIN LICENSE BLOCK *****
- * Version: CPL 1.0/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Common Public
- * License Version 1.0 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of
- * the License at http://www.eclipse.org/legal/cpl-v10.html
- *
- * Software distributed under the License is distributed on an "AS
- * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
- * implied. See the License for the specific language governing
- * rights and limitations under the License.
- *
- * Copyright (C) 2002-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
- * Copyright (C) 2004-2006 Thomas E Enebo <enebo@acm.org>
- * Copyright (C) 2005 Charles O Nutter <headius@headius.com>
- * Copyright (C) 2006 Miguel Covarrubias <mlcovarrubias@gmail.com>
- * Copyright (C) 2007 William N Dortch <bill.dortch@gmail.com>
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either of the GNU General Public License Version 2 or later (the "GPL"),
- * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the CPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the CPL, the GPL or the LGPL.
- ***** END LICENSE BLOCK *****/
- package org.jruby;
- import java.util.List;
- import java.util.Map;
- import org.jruby.internal.runtime.methods.DynamicMethod;
- import org.jruby.runtime.builtin.IRubyObject;
- import org.jruby.runtime.builtin.Variable;
- /**
- * This class is used to provide an intermediate superclass for modules and classes that include
- * other modules. It inserts itself as the immediate superClass of the includer, but defers all
- * module methods to the actual superclass. Multiple of these intermediate superclasses can be
- * added for multiple included modules.
- *
- * This allows the normal superclass-based searches (searchMethod, getConstant, etc) to traverse
- * the superclass ancestors as normal while the included modules do not actually show up in
- * direct inheritance traversal.
- *
- * @see org.jruby.RubyModule
- */
- public final class IncludedModuleWrapper extends RubyClass {
- private final RubyModule delegate;
- public IncludedModuleWrapper(Ruby runtime, RubyClass superClass, RubyModule delegate) {
- super(runtime, superClass, false);
- this.delegate = delegate;
- this.metaClass = delegate.metaClass;
- }
- /**
- * Overridden newIncludeClass implementation to allow attaching future includes to the correct module
- * (i.e. the one to which this is attached)
- *
- * @see org.jruby.RubyModule#newIncludeClass(RubyClass)
- */
- @Override
- public IncludedModuleWrapper newIncludeClass(RubyClass superClass) {
- IncludedModuleWrapper includedModule = new IncludedModuleWrapper(getRuntime(), superClass, getNonIncludedClass());
-
- // include its parent (and in turn that module's parents)
- if (getSuperClass() != null) {
- includedModule.includeModule(getSuperClass());
- }
-
- return includedModule;
- }
- @Override
- public boolean isModule() {
- return false;
- }
- @Override
- public boolean isClass() {
- return false;
- }
- @Override
- public boolean isIncluded() {
- return true;
- }
-
- @Override
- public boolean isImmediate() {
- return true;
- }
- @Override
- public void setMetaClass(RubyClass newRubyClass) {
- throw new UnsupportedOperationException("An included class is only a wrapper for a module");
- }
- @Override
- public Map<String, DynamicMethod> getMethods() {
- return delegate.getMethods();
- }
- @Override
- public void addMethod(String name, DynamicMethod method) {
- throw new UnsupportedOperationException("An included class is only a wrapper for a module");
- }
- public void setMethods(Map newMethods) {
- throw new UnsupportedOperationException("An included class is only a wrapper for a module");
- }
- @Override
- public String getName() {
- return delegate.getName();
- }
- @Override
- public RubyModule getNonIncludedClass() {
- return delegate;
- }
-
- @Override
- public RubyClass getRealClass() {
- return getSuperClass().getRealClass();
- }
- @Override
- protected boolean isSame(RubyModule module) {
- return delegate.isSame(module);
- }
-
- /**
- * We don't want to reveal ourselves to Ruby code, so delegate this
- * operation.
- */
- @Override
- public IRubyObject id() {
- return delegate.id();
- }
- //
- // VARIABLE TABLE METHODS - pass to delegate
- //
- @Override
- protected boolean variableTableContains(String name) {
- return delegate.variableTableContains(name);
- }
- @Override
- protected boolean variableTableFastContains(String internedName) {
- return delegate.variableTableFastContains(internedName);
- }
- @Override
- protected IRubyObject variableTableFetch(String name) {
- return delegate.variableTableFetch(name);
- }
- @Override
- protected IRubyObject variableTableFastFetch(String internedName) {
- return delegate.variableTableFastFetch(internedName);
- }
- @Override
- protected IRubyObject variableTableStore(String name, IRubyObject value) {
- return delegate.variableTableStore(name, value);
- }
- @Override
- protected IRubyObject variableTableFastStore(String internedName, IRubyObject value) {
- return delegate.variableTableFastStore(internedName, value);
- }
- @Override
- protected IRubyObject variableTableRemove(String name) {
- return delegate.variableTableRemove(name);
- }
- @Override
- protected VariableTableEntry[] variableTableGetTable() {
- return delegate.variableTableGetTable();
- }
- @Override
- protected int variableTableGetSize() {
- return delegate.variableTableGetSize();
- }
- @Override
- protected void variableTableSync(List<Variable<IRubyObject>> vars) {
- delegate.variableTableSync(vars);
- }
- @Override
- protected IRubyObject variableTableReadLocked(VariableTableEntry entry) {
- return delegate.variableTableReadLocked(entry);
- }
- /**
- * Method to help ease transition to new variables implementation.
- * Will likely be deprecated in the near future.
- */
- @SuppressWarnings("unchecked")
- @Override
- @Deprecated // born deprecated
- protected Map variableTableGetMap() {
- return delegate.variableTableGetMap();
- }
- /**
- * Method to help ease transition to new variables implementation.
- * Will likely be deprecated in the near future.
- */
- @SuppressWarnings("unchecked")
- @Override
- @Deprecated // born deprecated
- protected Map variableTableGetMap(Map map) {
- return delegate.variableTableGetMap(map);
- }
- //
- // CONSTANT TABLE METHODS - pass to delegate
- //
- @Override
- protected boolean constantTableContains(String name) {
- return delegate.constantTableContains(name);
- }
- @Override
- protected boolean constantTableFastContains(String internedName) {
- return delegate.constantTableFastContains(internedName);
- }
- @Override
- protected IRubyObject constantTableFetch(String name) {
- return delegate.constantTableFetch(name);
- }
- @Override
- protected IRubyObject constantTableFastFetch(String internedName) {
- return delegate.constantTableFastFetch(internedName);
- }
- @Override
- protected IRubyObject constantTableStore(String name, IRubyObject value) {
- // FIXME: legal here? may want UnsupportedOperationException
- return delegate.constantTableStore(name, value);
- }
- @Override
- protected IRubyObject constantTableFastStore(String internedName, IRubyObject value) {
- // FIXME: legal here? may want UnsupportedOperationException
- return delegate.constantTableFastStore(internedName, value);
- }
- @Override
- protected IRubyObject constantTableRemove(String name) {
- // this _is_ legal (when removing an undef)
- return delegate.constantTableRemove(name);
- }
- @Override
- protected ConstantTableEntry[] constantTableGetTable() {
- return delegate.constantTableGetTable();
- }
- @Override
- protected int constantTableGetSize() {
- return delegate.constantTableGetSize();
- }
- @Override
- protected void constantTableSync(List<Variable<IRubyObject>> vars) {
- // FIXME: legal here? may want UnsupportedOperationException
- delegate.constantTableSync(vars);
- }
- /**
- * Method to help ease transition to new variables implementation.
- * Will likely be deprecated in the near future.
- */
- @SuppressWarnings("unchecked")
- @Override
- @Deprecated // born deprecated
- protected Map constantTableGetMap() {
- return delegate.constantTableGetMap();
- }
- /**
- * Method to help ease transition to new variables implementation.
- * Will likely be deprecated in the near future.
- */
- @SuppressWarnings("unchecked")
- @Override
- @Deprecated // born deprecated
- protected Map constantTableGetMap(Map map) {
- return delegate.constantTableGetMap(map);
- }
- }
- /***** BEGIN LICENSE BLOCK *****
- * Version: CPL 1.0/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Common Public
- * License Version 1.0 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of
- * the License at http://www.eclipse.org/legal/cpl-v10.html
- *
- * Software distributed under the License is distributed on an "AS
- * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
- * implied. See the License for the specific language governing
- * rights and limitations under the License.
- *
- * Copyright (C) 2007 Charles Nutter <charles.o.nutter@sun.com>
- * Copyright (C) 2008 MenTaLguY <mental@rydia.net>
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either of the GNU General Public License Version 2 or later (the "GPL"),
- * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the CPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the CPL, the GPL or the LGPL.
- ***** END LICENSE BLOCK *****/
- package org.jruby;
- import java.applet.Applet;
- import java.awt.BorderLayout;
- import java.awt.Color;
- import java.awt.Container;
- import java.awt.EventQueue;
- import java.awt.Font;
- import java.awt.Insets;
- import java.awt.Graphics;
- import java.awt.GraphicsConfiguration;
- import java.awt.GraphicsEnvironment;
- import java.awt.image.VolatileImage;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.PrintStream;
- import java.net.URL;
- import java.util.Arrays;
- import java.lang.reflect.InvocationTargetException;
- import org.jruby.anno.JRubyMethod;
- import org.jruby.demo.TextAreaReadline;
- import org.jruby.javasupport.JavaUtil;
- import org.jruby.runtime.Block;
- import org.jruby.runtime.ThreadContext;
- import org.jruby.runtime.builtin.IRubyObject;
- import javax.swing.JScrollPane;
- import javax.swing.JTextPane;
- /**
- * @author <a href="mailto:mental@rydia.net">MenTaLguY</a>
- *
- * The JRubyApplet class provides a simple way to write Java applets using
- * JRuby without needing to create a custom Java applet class. At applet
- * initialization time, JRubyApplet starts up a JRuby runtime, then evaluates
- * the scriptlet given as the "eval" applet parameter.
- *
- * The Java applet instance is available to the Ruby script as
- * JRUBY_APPLET; the script can define callbacks for applet start, stop,
- * and destroy by passing blocks to JRUBY_APPLET.on_start,
- * JRUBY_APPLET.on_stop, and JRUBY_APPLET.on_destroy, respectively.
- *
- * Ruby code can install a custom paint callback using JRUBY_APPLET.on_paint
- * (the Graphics2D object is passed as an argument to the callback). By
- * default, JRubyApplet painting is double-buffered, but you can select
- * single-buffered painting via JRUBY_APPLET.double_buffered = false.
- *
- * The applet's background color can be set via JRUBY_APPLET.background_color=.
- * You may want to set it to nil if you're not using double-buffering, so that
- * no background color will be drawn (your own paint code is then responsible
- * for filling the area).
- *
- * Beyond these things, you should be able to use JRuby's Java integration
- * to do whatever you would do in Java with the applet instance.
- *
- */
- public class JRubyApplet extends Applet {
- private Ruby runtime;
- private boolean doubleBuffered = true;
- private Color backgroundColor = Color.WHITE;
- private RubyProc startProc;
- private RubyProc stopProc;
- private RubyProc destroyProc;
- private RubyProc paintProc;
- private Graphics priorGraphics;
- private IRubyObject wrappedGraphics;
- private VolatileImage backBuffer;
- private Graphics backBufferGraphics;
- private Facade facade;
- private interface Facade {
- public InputStream getInputStream();
- public PrintStream getOutputStream();
- public PrintStream getErrorStream();
- public void attach(Ruby runtime, Applet applet);
- public void destroy();
- }
- private static RubyProc blockToProc(Ruby runtime, Block block) {
- if (block.isGiven()) {
- RubyProc proc = block.getProcObject();
- if (proc == null) {
- proc = RubyProc.newProc(runtime, block, block.type);
- }
- return proc;
- } else {
- return null;
- }
- }
- private boolean getBooleanParameter(String name, boolean defaultValue) {
- String value = getParameter(name);
- if ( value != null ) {
- return value.equals("true");
- } else {
- return defaultValue;
- }
- }
- private InputStream getCodeResourceAsStream(String name) {
- if (name == null) {
- return null;
- }
- try {
- final URL directURL = new URL(getCodeBase(), name);
- return directURL.openStream();
- } catch (IOException e) {
- }
- return JRubyApplet.class.getClassLoader().getResourceAsStream(name);
- }
- private static void safeInvokeAndWait(Runnable runnable) throws InvocationTargetException, InterruptedException {
- if (EventQueue.isDispatchThread()) {
- try {
- runnable.run();
- } catch (Exception e) {
- throw new InvocationTargetException(e);
- }
- } else {
- EventQueue.invokeAndWait(runnable);
- }
- }
- public static class RubyMethods {
- @JRubyMethod
- public static IRubyObject on_start(IRubyObject recv, Block block) {
- JRubyApplet applet = (JRubyApplet)recv.dataGetStruct();
- synchronized (applet) {
- applet.startProc = blockToProc(applet.runtime, block);
- }
- return recv;
- }
- @JRubyMethod
- public static IRubyObject on_stop(IRubyObject recv, Block block) {
- JRubyApplet applet = (JRubyApplet)recv.dataGetStruct();
- synchronized (applet) {
- applet.stopProc = blockToProc(applet.runtime, block);
- }
- return recv;
- }
- @JRubyMethod
- public static IRubyObject on_destroy(IRubyObject recv, Block block) {
- JRubyApplet applet = (JRubyApplet)recv.dataGetStruct();
- synchronized (applet) {
- applet.destroyProc = blockToProc(applet.runtime, block);
- }
- return recv;
- }
- @JRubyMethod
- public static IRubyObject on_paint(IRubyObject recv, Block block) {
- JRubyApplet applet = (JRubyApplet)recv.dataGetStruct();
- synchronized (applet) {
- applet.paintProc = blockToProc(applet.runtime, block);
- applet.repaint();
- }
- return recv;
- }
- }
- @Override
- public void init() {
- super.init();
- if (getBooleanParameter("jruby.console", false)) {
- facade = new ConsoleFacade(getParameter("jruby.banner"));
- } else {
- facade = new TrivialFacade();
- }
- synchronized (this) {
- if (runtime != null) {
- return;
- }
- final RubyInstanceConfig config = new RubyInstanceConfig() {{
- setInput(facade.getInputStream());
- setOutput(facade.getOutputStream());
- setError(facade.getErrorStream());
- setObjectSpaceEnabled(getBooleanParameter("jruby.objectspace", false));
- }};
- Ruby.setSecurityRestricted(true);
- runtime = Ruby.newInstance(config);
- }
- final String scriptName = getParameter("jruby.script");
- final InputStream scriptStream = getCodeResourceAsStream(scriptName);
- final String evalString = getParameter("jruby.eval");
- try {
- final JRubyApplet applet = this;
- safeInvokeAndWait(new Runnable() {
- public void run() {
- applet.setLayout(new BorderLayout());
- applet.facade.attach(applet.runtime, applet);
- if (scriptStream != null) {
- applet.runtime.runFromMain(scriptStream, scriptName);
- }
- if (evalString != null) {
- applet.runtime.evalScriptlet(evalString);
- }
- }
- });
- } catch (InterruptedException e) {
- } catch (InvocationTargetException e) {
- throw new RuntimeException("Error running script", e.getCause());
- }
- }
- private void invokeCallback(final RubyProc proc, final IRubyObject[] args) {
- if (proc == null) {
- return;
- }
- final Ruby runtime = this.runtime;
- try {
- safeInvokeAndWait(new Runnable() {
- public void run() {
- ThreadContext context = runtime.getCurrentContext();
- proc.call(context, args);
- }
- });
- } catch (InterruptedException e) {
- } catch (InvocationTargetException e) {
- throw new RuntimeException("Ruby callback failed", e.getCause());
- }
- }
- public synchronized void setBackgroundColor(Color color) {
- backgroundColor = color;
- repaint();
- }
- public synchronized Color getBackgroundColor() {
- return backgroundColor;
- }
- public synchronized boolean isDoubleBuffered() {
- return doubleBuffered;
- }
- public synchronized void setDoubleBuffered(boolean shouldBuffer) {
- doubleBuffered = shouldBuffer;
- repaint();
- }
- @Override
- public synchronized void start() {
- super.start();
- invokeCallback(startProc, new IRubyObject[] {});
- }
- @Override
- public synchronized void stop() {
- invokeCallback(stopProc, new IRubyObject[] {});
- super.stop();
- }
- @Override
- public synchronized void destroy() {
- try {
- invokeCallback(destroyProc, new IRubyObject[] {});
- } finally {
- facade.destroy();
- final Ruby runtime = this.runtime;
- this.runtime = null;
- startProc = null;
- stopProc = null;
- destroyProc = null;
- paintProc = null;
- priorGraphics = null;
- wrappedGraphics = null;
- runtime.tearDown();
- super.destroy();
- }
- }
- @Override
- public void update(Graphics g) {
- paint(g);
- }
- @Override
- public synchronized void paint(Graphics g) {
- if (doubleBuffered) {
- paintBuffered(g);
- } else {
- paintUnbuffered(g);
- }
- }
- private synchronized void paintBuffered(Graphics g) {
- do {
- GraphicsConfiguration config = getGraphicsConfiguration();
- int width = getWidth();
- int height = getHeight();
- if (backBuffer == null || width != backBuffer.getWidth() || height != backBuffer.getHeight() || backBuffer.validate(config) == VolatileImage.IMAGE_INCOMPATIBLE) {
- if (backBuffer != null) {
- backBufferGraphics.dispose();
- backBufferGraphics = null;
- backBuffer.flush();
- backBuffer = null;
- }
- backBuffer = config.createCompatibleVolatileImage(width, height);
- backBufferGraphics = backBuffer.createGraphics();
- }
- backBufferGraphics.setClip(g.getClip());
- paintUnbuffered(backBufferGraphics);
- g.drawImage(backBuffer, 0, 0, this);
- } while (backBuffer.contentsLost());
- }
- private synchronized void paintUnbuffered(Graphics g) {
- if (backgroundColor != null) {
- g.setColor(backgroundColor);
- g.fillRect(0, 0, getWidth(), getHeight());
- }
- if (paintProc != null) {
- if (priorGraphics != g) {
- wrappedGraphics = JavaUtil.convertJavaToUsableRubyObject(runtime, g);
- priorGraphics = g;
- }
- ThreadContext context = runtime.getCurrentContext();
- paintProc.call(context, new IRubyObject[] {wrappedGraphics});
- }
- super.paint(g);
- }
- private static class TrivialFacade implements Facade {
- public TrivialFacade() {}
- public InputStream getInputStream() { return System.in; }
- public PrintStream getOutputStream() { return System.out; }
- public PrintStream getErrorStream() { return System.err; }
- public void attach(Ruby runtime, Applet applet) {
- final IRubyObject wrappedApplet = JavaUtil.convertJavaToUsableRubyObject(runtime, applet);
- wrappedApplet.dataWrapStruct(applet);
- runtime.defineGlobalConstant("JRUBY_APPLET", wrappedApplet);
- wrappedApplet.getMetaClass().defineAnnotatedMethods(RubyMethods.class);
- }
- public void destroy() {}
- }
- private static class ConsoleFacade implements Facade {
- private JTextPane textPane;
- private JScrollPane scrollPane;
- private TextAreaReadline adaptor;
- private InputStream inputStream;
- private PrintStream outputStream;
- private PrintStream errorStream;
-
- public ConsoleFacade(String bannerText) {
- textPane = new JTextPane();
- textPane.setMargin(new Insets(4, 4, 0, 4));
- textPane.setCaretColor(new Color(0xa4, 0x00, 0x00));
- textPane.setBackground(new Color(0xf2, 0xf2, 0xf2));
- textPane.setForeground(new Color(0xa4, 0x00, 0x00));
- Font font = findFont("Monospaced", Font.PLAIN, 14,
- new String[] {"Monaco", "Andale Mono"});
- textPane.setFont(font);
- scrollPane = new JScrollPane(textPane);
- scrollPane.setDoubleBuffered(true);
- if ( bannerText != null ) {
- bannerText = " " + bannerText + " \n\n";
- }
- adaptor = new TextAreaReadline(textPane, bannerText);
- inputStream = adaptor.getInputStream();
- outputStream = new PrintStream(adaptor.getOutputStream());
- errorStream = new PrintStream(adaptor.getOutputStream());
- }
- public InputStream getInputStream() { return inputStream; }
- public PrintStream getOutputStream() { return outputStream; }
- public PrintStream getErrorStream() { return errorStream; }
- public void attach(Ruby runtime, Applet applet) {
- adaptor.hookIntoRuntime(runtime);
- applet.add(scrollPane);
- applet.validate();
- }
- public void destroy() {
- Container parent = scrollPane.getParent();
- adaptor.shutdown();
- if (parent != null) {
- parent.remove(scrollPane);
- }
- }
- private Font findFont(String otherwise, int style, int size, String[] families) {
- String[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
- Arrays.sort(fonts);
- for (int i = 0; i < families.length; i++) {
- if (Arrays.binarySearch(fonts, families[i]) >= 0) {
- return new Font(families[i], style, size);
- }
- }
- return new Font(otherwise, style, size);
- }
- }
- }
- /***** BEGIN LICENSE BLOCK *****
- * Version: CPL 1.0/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Common Public
- * License Version 1.0 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of
- * the License at http://www.eclipse.org/legal/cpl-v10.html
- *
- * Software distributed under the License is distributed on an "AS
- * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
- * implied. See the License for the specific language governing
- * rights and limitations under the License.
- *
- * Copyright (C) 2007 Ola Bini <ola@ologix.com>
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either of the GNU General Public License Version 2 or later (the "GPL"),
- * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the CPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the CPL, the GPL or the LGPL.
- ***** END LICENSE BLOCK *****/
- package org.jruby;
- import java.io.BufferedWriter;
- import java.io.OutputStreamWriter;
- import java.net.InetAddress;
- import java.net.Socket;
- /**
- * @author <a href="mailto:ola.bini@ki.se">Ola Bini</a>
- */
- public class JRubyClient extends JRubyService {
- public JRubyClient(String[] args) throws Exception {
- Configuration conf = new Configuration(args[0]);
- if(conf.isDebug()) {
- System.err.println("Starting client with port " + conf.getPort() + ", key " + conf.getKey() + " and command " + conf.getCommand());
- }
- Socket socket = new Socket(InetAddress.getLocalHost(), conf.getPort());
- BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
- if(conf.terminate()) {
- writer.write(CMD_TERM + " " + conf.getKey() + "\n");
- } else if(conf.noMore()) {
- writer.write(CMD_NO_MORE + " " + conf.getKey() + "\n");
- } else {
- writer.write(CMD_START + " " + conf.getKey() + " " + conf.getCommand() + "\n");
- }
- writer.flush();
- writer.close();
- socket.close();
- }
- public static void main(String[] args) throws Exception {
- new JRubyClient(args);
- }
- }// JRubyClient
- /*
- ***** BEGIN LICENSE BLOCK *****
- * Version: CPL 1.0/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Common Public
- * License Version 1.0 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of
- * the License at http://www.eclipse.org/legal/cpl-v10.html
- *
- * Software distributed under the License is distributed on an "AS
- * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
- * implied. See the License for the specific language governing
- * rights and limitations under the License.
- *
- * Copyright (C) 2007 Ola Bini <ola@ologix.com>
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either of the GNU General Public License Version 2 or later (the "GPL"),
- * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the CPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the CPL, the GPL or the LGPL.
- ***** END LICENSE BLOCK *****/
- package org.jruby;
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.net.InetAddress;
- import java.net.InetSocketAddress;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.util.List;
- import java.util.ArrayList;
- /**
- * @author <a href="mailto:ola.bini@ki.se">Ola Bini</a>
- */
- public class JRubyServer extends JRubyService {
- private Configuration conf;
- private boolean stillStarting = true;
- private JRubyServer(String[] args) throws Exception {
- conf = new Configuration(args[0]);
- if(conf.isDebug()) {
- System.err.println("Starting server with port " + conf.getPort() + " and key " + conf.getKey());
- }
- ServerSocket server = new ServerSocket();
- server.bind(new InetSocketAddress(InetAddress.getLocalHost(),conf.getPort()));
- while(true) {
- Thread t1 = new Thread(new Handler(server.accept()));
- t1.setDaemon(true);
- t1.start();
- }
- }
- private class Handler implements Runnable {
- private Socket socket;
- public Handler(Socket socket) {
- this.socket = socket;
- }
- public void run() {
- try {
- BufferedReader rr = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
- String command = rr.readLine();
- rr.close();
- this.socket.close();
- this.socket = null;
- if(conf.isDebug()) {
- System.err.println("Got command: " + command);
- }
- String[] cmds = command.split(" ", 3);
- if(cmds[1].equals(conf.getKey())) {
- if(cmds[0].equals(CMD_TERM)) {
- if(conf.isDebug()) {
- System.err.println("Terminating hard");
- }
- System.exit(0);
- } else if(cmds[0].equals(CMD_NO_MORE)) {
- if(conf.isDebug()) {
- System.err.println("Accepting no more START");
- }
- stillStarting = false;
- } else if(cmds[0].equals(CMD_START)) {
- if(stillStarting) {
- if(conf.isDebug()) {
- System.err.println("Doing START on command " + cmds[2]);
- }
- new Main().run(intoCommandArguments(cmds[2].trim()));
- } else {
- if(conf.isDebug()) {
- System.err.println("Not doing START anymore, invalid command");
- }
- }
- } else {
- if(conf.isDebug()) {
- System.err.println("Unrecognized command");
- }
- }
- } else {
- if(conf.isDebug()) {
- System.err.println("Invalid key");
- }
- }
- } catch(Exception e) {}
- }
- }
- protected static String[] intoCommandArguments(String str) {
- List<String> args = new ArrayList<String>();
- boolean inSingle = false;
- int contentStart = -1;
- for(int i=0,j=str.length();i<j;i++) {
- if(str.charAt(i) == ' ' && !inSingle && contentStart != -1) {
- args.add(str.substring(contentStart,i));
- contentStart = -1;
- continue;
- }
- if(str.charAt(i) == ' ') {
- continue;
- }
- if(str.charAt(i) == '\'' && !inSingle) {
- inSingle = true;
- contentStart = i+1;
- continue;
- }
- if(str.charAt(i) == '\'') {
- inSingle = false;
- args.add(str.substring(contentStart,i));
- contentStart = -1;
- continue;
- }
- if(contentStart == -1) {
- contentStart = i;
- }
- }
- if(contentStart != -1) {
- args.add(str.substring(contentStart));
- }
- return (String[])args.toArray(new String[0]);
- }
- public static void main(String[] args) throws Exception {
- new JRubyServer(args);
- }
- }// JRubyServer
- /***** BEGIN LICENSE BLOCK *****
- * Version: CPL 1.0/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Common Public
- * License Version 1.0 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of
- * the License at http://www.eclipse.org/legal/cpl-v10.html
- *
- * Software distributed under the License is distributed on an "AS
- * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
- * implied. See the License for the specific language governing
- * rights and limitations under the License.
- *
- * Copyright (C) 2007 Ola Bini <ola@ologix.com>
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either of the GNU General Public License Version 2 or later (the "GPL"),
- * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the CPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the CPL, the GPL or the LGPL.
- ***** END LICENSE BLOCK *****/
- package org.jruby;
- /**
- * @author <a href="mailto:ola.bini@ki.se">Ola Bini</a>
- */
- public abstract class JRubyService {
- protected static class Configuration {
- private final static int DEFAULT_PORT = 19222;
- private String key;
- private int port = DEFAULT_PORT;
- private boolean terminate;
- private boolean noMore;
- private boolean debug;
- private String command;
- public Configuration(String args) {
- int i=0;
- int stop;
- loop: for(int j=args.length();i<j;i++) {
- if(args.charAt(i) == '-' && i+1 < j) {
- switch(args.charAt(++i)) {
- case 'k':
- stop = args.indexOf(" ", (++i) + 1);
- if(stop == -1) {
- stop = args.length();
- }
- key = args.substring(i, stop).trim();
- i = stop;
- break;
- case 'p':
- stop = args.indexOf(" ", (++i) + 1);
- if(stop == -1) {
- stop = args.length();
- }
- port = Integer.parseInt(args.substring(i, stop).trim());
- i = stop;
- break;
- case 't':
- terminate = true;
- i++;
- break;
- case 'n':
- noMore = true;
- i++;
- break;
- case 'd':
- debug = true;
- i++;
- break;
- case '-': // handle everything after -- as arguments to the jruby process
- i++;
- break loop;
- default:
- i--;
- break loop;
- }
- } else if(args.charAt(i) != ' ') {
- break loop;
- }
- }
- if(i<args.length()) {
- command = args.substring(i).trim();
- }
- }
-
- public String getKey() {
- return key;
- }
- public int getPort() {
- return port;
- }
- public boolean terminate() {
- return terminate;
- }
- public boolean noMore() {
- return noMore;
- }
- public boolean isDebug() {
- return debug;
- }
- public String getCommand() {
- return command;
- }
- }
- public static final String CMD_START = "START";
- public static final String CMD_NO_MORE = "NO_MORE";
- public static final String CMD_TERM = "TERM";
- }// JRubyService
- /*
- ***** BEGIN LICENSE BLOCK *****
- * Version: CPL 1.0/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Common Public
- * License Version 1.0 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of
- * the License at http://www.eclipse.org/legal/cpl-v10.html
- *
- * Software distributed under the License is distributed on an "AS
- * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
- * implied. See the License for the specific language governing
- * rights and limitations under the License.
- *
- * Copyright (C) 2001 Alan Moore <alan_moore@gmx.net>
- * Copyright (C) 2001-2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
- * Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
- * Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
- * Copyright (C) 2004 Thomas E Enebo <enebo@acm.org>
- * Copyright (C) 2004-2006 Charles O Nutter <headius@headius.com>
- * Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
- * Copyright (C) 2005 Kiel Hodges <jruby-devel@selfsosoft.com>
- * Copyright (C) 2005 Jason Voegele <jason@jvoegele.com>
- * Copyright (C) 2005 Tim Azzopardi <tim@tigerfive.com>
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either of the GNU General Public License Version 2 or later (the "GPL"),
- * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the CPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the CPL, the GPL or the LGPL.
- ***** END LICENSE BLOCK *****/
- package org.jruby;
- import java.io.InputStream;
- import java.io.PrintStream;
- import org.jruby.exceptions.MainExitException;
- import org.jruby.exceptions.RaiseException;
- import org.jruby.exceptions.ThreadKill;
- import org.jruby.runtime.ThreadContext;
- import org.jruby.runtime.builtin.IRubyObject;
- import org.jruby.util.SafePropertyAccessor;
- import org.jruby.util.SimpleSampler;
- /**
- * Class used to launch the interpreter.
- * This is the main class as defined in the jruby.mf manifest.
- * It is very basic and does not support yet the same array of switches
- * as the C interpreter.
- * Usage: java -jar jruby.jar [switches] [rubyfile.rb] [arguments]
- * -e 'command' one line of script. Several -e's allowed. Omit [programfile]
- * @author jpetersen
- */
- public class Main {
- private boolean hasPrintedUsage = false;
- private final RubyInstanceConfig config;
- public Main(RubyInstanceConfig config) {
- this.config = config;
- }
- public Main(final InputStream in, final PrintStream out, final PrintStream err) {
- this(new RubyInstanceConfig(){{
- setInput(in);
- setOutput(out);
- setError(err);
- }});
- }
- public Main() {
- this(new RubyInstanceConfig());
- }
- public static void main(String[] args) {
- Main main = new Main();
-
- try {
- int status = main.run(args);
- if (status != 0) {
- System.exit(status);
- }
- } catch (RaiseException re) {
- throw re;
- } catch (Throwable t) {
- // print out as a nice Ruby backtrace
- System.err.println(ThreadContext.createRawBacktraceStringFromThrowable(t));
- System.exit(1);
- }
- }
- public int run(String[] args) {
- try {
- config.processArguments(args);
- return run();
- } catch (MainExitException mee) {
- if (!mee.isAborted()) {
- config.getOutput().println(mee.getMessage());
- if (mee.isUsageError()) {
- printUsage();
- }
- }
- return mee.getStatus();
- } catch (OutOfMemoryError oome) {
- // produce a nicer error since Rubyists aren't used to seeing this
- System.gc();
-
- String memoryMax = SafePropertyAccessor.getProperty("jruby.memory.max");
- String message = "";
- if (memoryMax != null) {
- message = " of " + memoryMax;
- }
- System.err.println("Error: Your application used more memory than the safety cap" + message + ".");
- System.err.println("Specify -J-Xmx####m to increase it (#### = cap size in MB).");
-
- if (config.getVerbose()) {
- System.err.println("Exception trace follows:");
- oome.printStackTrace();
- } else {
- System.err.println("Specify -w for full OutOfMemoryError stack trace");
- }
- return 1;
- } catch (StackOverflowError soe) {
- // produce a nicer error since Rubyists aren't used to seeing this
- System.gc();
-
- String stackMax = SafePropertyAccessor.getProperty("jruby.stack.max");
- …
Large files files are truncated, but you can click here to view the full file