Exemple #1
0
  @JRubyMethod(rest = true)
  public static IRubyObject set_types(IRubyObject recv, IRubyObject[] args) {
    Ruby runtime = recv.getRuntime();
    RubyArray types = RubyArray.newArray(runtime, args);
    RubyArray type_strings = RubyArray.newArray(runtime);

    for (IRubyObject arg : args) {
      if (arg instanceof RubyClass) {
        type_strings.append(arg);
      } else if (arg instanceof RubyArray) {
        for (IRubyObject sub_arg : arg.convertToArray().toJavaArray()) {
          if (sub_arg instanceof RubyClass) {
            type_strings.append(sub_arg);
          } else {
            throw runtime.newArgumentError("Invalid type given");
          }
        }
      } else {
        throw runtime.newArgumentError("Invalid type given");
      }
    }

    api.setInstanceVariable(recv, "@field_types", type_strings);
    return types;
  }
Exemple #2
0
 private RubyClass findClass(String className) {
   RubyModule classInstance;
   try {
     classInstance = runtime.getClassFromPath(className);
   } catch (RaiseException e) {
     if (runtime.getModule("NameError").isInstance(e.getException())) {
       throw runtime.newArgumentError("undefined class/module " + className);
     }
     throw e;
   }
   if (!(classInstance instanceof RubyClass)) {
     throw runtime.newArgumentError(className + " does not refer class"); // sic
   }
   return (RubyClass) classInstance;
 }
Exemple #3
0
  public static int symbolToInterestOps(
      Ruby ruby, SelectableChannel channel, IRubyObject interest) {
    if (interest == ruby.newSymbol("r")) {
      if ((channel.validOps() & SelectionKey.OP_ACCEPT) != 0) {
        return SelectionKey.OP_ACCEPT;
      } else {
        return SelectionKey.OP_READ;
      }
    } else if (interest == ruby.newSymbol("w")) {
      if (channel instanceof SocketChannel && !((SocketChannel) channel).isConnected()) {
        return SelectionKey.OP_CONNECT;
      } else {
        return SelectionKey.OP_WRITE;
      }
    } else if (interest == ruby.newSymbol("rw")) {
      int interestOps = 0;

      /* nio4r emulates the POSIX behavior, which is sloppy about allowed modes */
      if ((channel.validOps() & (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT)) != 0) {
        interestOps |= symbolToInterestOps(ruby, channel, ruby.newSymbol("r"));
      }

      if ((channel.validOps() & (SelectionKey.OP_WRITE | SelectionKey.OP_CONNECT)) != 0) {
        interestOps |= symbolToInterestOps(ruby, channel, ruby.newSymbol("w"));
      }

      return interestOps;
    } else {
      throw ruby.newArgumentError("invalid interest type: " + interest);
    }
  }
Exemple #4
0
  private IRubyObject uclassUnmarshall() throws IOException {
    RubySymbol className = (RubySymbol) unmarshalObject(false);

    RubyClass type = (RubyClass) runtime.getClassFromPath(className.asJavaString());

    // singleton, raise error
    if (type.isSingleton()) throw runtime.newTypeError("singleton can't be loaded");

    // All "C" marshalled objects descend from core classes, which are all at least RubyObject
    RubyObject result = (RubyObject) unmarshalObject();

    // if result is a module or type doesn't extend result's class...
    if (result.getMetaClass() == runtime.getModule()
        || !type.isKindOfModule(result.getMetaClass())) {
      // if allocators do not match, error
      // Note: MRI is a bit different here, and tests TYPE(type.allocate()) != TYPE(result)
      if (type.getAllocator() != result.getMetaClass().getRealClass().getAllocator()) {
        throw runtime.newArgumentError("dump format error (user class)");
      }
    }

    result.setMetaClass(type);

    return result;
  }
  /**
   * Find a non-special encoding Entry, raising argument error if it does not exist.
   *
   * @param name the name of the encoding to look up
   * @return the EncodingDB.Entry object found, or raises ArgumentError
   */
  private Entry findEntryWithError(ByteList name) {
    Entry e = findEncodingOrAliasEntry(name);

    if (e == null) throw runtime.newArgumentError("unknown encoding name - " + name);

    return e;
  }
  @JRubyMethod(required = 1, optional = 1)
  public RubyObject new_instance(IRubyObject[] args, Block block) {
    final Ruby runtime = getRuntime();

    final int last = Arity.checkArgumentCount(runtime, args, 1, 2) - 1;

    final RubyProc proc;
    // Is there a supplied proc arg or do we assume a block was supplied
    if (args[last] instanceof RubyProc) {
      proc = (RubyProc) args[last];
    } else {
      proc = runtime.newProc(Block.Type.PROC, block);
    }

    final Object[] convertedArgs = convertArguments((RubyArray) args[0]);

    JavaProxyInvocationHandler handler = new ProcInvocationHandler(runtime, proc);
    try {
      return JavaObject.wrap(runtime, newInstance(convertedArgs, handler));
    } catch (Exception e) {
      RaiseException ex =
          runtime.newArgumentError("Constructor invocation failed: " + e.getMessage());
      ex.initCause(e);
      throw ex;
    }
  }
Exemple #7
0
  public String getModeAsString(Ruby runtime) {
    String modeString = getStringFromMode(mode);

    if (modeString == null) {
      throw runtime.newArgumentError("Illegal access modenum " + Integer.toOctalString(mode));
    }

    return modeString;
  }
Exemple #8
0
    @JRubyMethod
    public IRubyObject register(ThreadContext context, IRubyObject io, IRubyObject interests) {
      Ruby runtime = context.getRuntime();
      Channel rawChannel = RubyIO.convertToIO(context, io).getChannel();

      if (!this.selector.isOpen()) {
        throw context.getRuntime().newIOError("selector is closed");
      }

      if (!(rawChannel instanceof SelectableChannel)) {
        throw runtime.newArgumentError("not a selectable IO object");
      }

      SelectableChannel channel = (SelectableChannel) rawChannel;

      try {
        channel.configureBlocking(false);
      } catch (IOException ie) {
        throw runtime.newIOError(ie.getLocalizedMessage());
      }

      int interestOps = Nio4r.symbolToInterestOps(runtime, channel, interests);
      SelectionKey key;

      key = this.cancelledKeys.remove(channel);

      if (key != null) {
        key.interestOps(interestOps);
      } else {
        try {
          key = channel.register(this.selector, interestOps);
        } catch (java.lang.IllegalArgumentException ia) {
          throw runtime.newArgumentError("mode not supported for this object: " + interests);
        } catch (java.nio.channels.ClosedChannelException cce) {
          throw context.runtime.newIOError(cce.getLocalizedMessage());
        }
      }

      RubyClass monitorClass = runtime.getModule("NIO").getClass("Monitor");
      Monitor monitor = (Monitor) monitorClass.newInstance(context, io, interests, this, null);
      monitor.setSelectionKey(key);

      return monitor;
    }
 @Override
 public void prepare(
     ThreadContext context,
     Ruby runtime,
     IRubyObject self,
     IRubyObject arg0,
     IRubyObject arg1,
     IRubyObject arg2,
     Block block) {
   throw runtime.newArgumentError(3, 2);
 }
Exemple #10
0
  /**
   * Returns a {@link Member} descriptor for a struct field.
   *
   * @param name The name of the struct field.
   * @return A <tt>Member</tt> descriptor.
   */
  final Member getMember(Ruby runtime, IRubyObject name) {
    Member f = fieldSymbolMap.get(name);
    if (f != null) {
      return f;
    }

    f = fieldStringMap.get(name);
    if (f != null) {
      return f;
    }

    throw runtime.newArgumentError("Unknown field: " + name);
  }
  public JavaObject newInstance(final IRubyObject self, Object[] args) throws RaiseException {
    final Ruby runtime = getRuntime();

    JavaProxyInvocationHandler handler = new MethodInvocationHandler(runtime, self);
    try {
      return JavaObject.wrap(runtime, newInstance(args, handler));
    } catch (Throwable t) {
      while (t.getCause() != null) t = t.getCause();
      RaiseException ex =
          runtime.newArgumentError("Constructor invocation failed: " + t.getMessage());
      ex.initCause(t);
      throw ex;
    }
  }
Exemple #12
0
  private static RaiseException newQueryError(
      Ruby runtime, SQLException sqle, Statement statement) {
    // TODO: provide an option to display extended debug information, for
    // driver developers, etc. Otherwise, keep it off to keep noise down for
    // end-users.
    Pattern p = Pattern.compile("Statement parameter (\\d+) not set.");
    Matcher m = p.matcher(sqle.getMessage());

    if (m.matches()) {
      return runtime.newArgumentError("Binding mismatch: 0 for " + m.group(1));
    } else {
      return DataObjectsUtils.newDriverError(runtime, errorName, sqle, statement);
    }
  }
Exemple #13
0
  public void defaultVariablesUnmarshal(IRubyObject object) throws IOException {
    int count = unmarshalInt();

    RubyClass cls = object.getMetaClass().getRealClass();

    for (int i = 0; i < count; i++) {

      IRubyObject key = unmarshalObject(false);

      if (i == 0) { // first ivar provides encoding

        if (object instanceof EncodingCapable) {

          EncodingCapable strObj = (EncodingCapable) object;

          if (key.asJavaString().equals(MarshalStream.SYMBOL_ENCODING_SPECIAL)) {

            // special case for USASCII and UTF8
            if (unmarshalObject().isTrue()) {
              strObj.setEncoding(UTF8Encoding.INSTANCE);
            } else {
              strObj.setEncoding(USASCIIEncoding.INSTANCE);
            }
            continue;

          } else if (key.asJavaString().equals("encoding")) {

            IRubyObject encodingNameObj = unmarshalObject(false);
            String encodingNameStr = encodingNameObj.asJavaString();
            ByteList encodingName = new ByteList(ByteList.plain(encodingNameStr));

            Entry entry = runtime.getEncodingService().findEncodingOrAliasEntry(encodingName);
            if (entry == null) {
              throw runtime.newArgumentError(
                  "invalid encoding in marshaling stream: " + encodingName);
            }
            Encoding encoding = entry.getEncoding();
            strObj.setEncoding(encoding);
            continue;
          } // else fall through as normal ivar
        }
      }

      String name = key.asJavaString();
      IRubyObject value = unmarshalObject();

      cls.getVariableAccessorForWrite(name).set(object, value);
    }
  }
Exemple #14
0
 public static IRubyObject interestOpsToSymbol(Ruby ruby, int interestOps) {
   switch (interestOps) {
     case SelectionKey.OP_READ:
     case SelectionKey.OP_ACCEPT:
       return ruby.newSymbol("r");
     case SelectionKey.OP_WRITE:
     case SelectionKey.OP_CONNECT:
       return ruby.newSymbol("w");
     case SelectionKey.OP_READ | SelectionKey.OP_CONNECT:
     case SelectionKey.OP_READ | SelectionKey.OP_WRITE:
       return ruby.newSymbol("rw");
     default:
       throw ruby.newArgumentError("unknown interest op combination");
   }
 }
Exemple #15
0
  /**
   * @param args
   * @return
   */
  @JRubyMethod(rest = true)
  public IRubyObject set_types(IRubyObject[] args) {
    Ruby runtime = getRuntime();
    RubyArray types = RubyArray.newArray(runtime, args);
    fieldTypes = new ArrayList<RubyType>(types.size());

    for (IRubyObject arg : args) {
      if (arg instanceof RubyClass) {
        fieldTypes.add(RubyType.getRubyType((RubyClass) arg));
      } else if (arg instanceof RubyArray) {
        for (IRubyObject sub_arg : arg.convertToArray().toJavaArray()) {
          if (sub_arg instanceof RubyClass) {
            fieldTypes.add(RubyType.getRubyType((RubyClass) sub_arg));
          } else {
            throw runtime.newArgumentError("Invalid type given");
          }
        }
      } else {
        throw runtime.newArgumentError("Invalid type given");
      }
    }

    return types;
  }
  private IRubyObject shutdownInternal(ThreadContext context, int how)
      throws BadDescriptorException {
    Ruby runtime = context.runtime;
    Channel channel;

    switch (how) {
      case 0:
        channel = getOpenChannel();
        try {
          SocketType.forChannel(channel).shutdownInput(channel);

        } catch (IOException e) {
          throw runtime.newIOError(e.getMessage());
        }

        if (openFile.getPipeStream() != null) {
          openFile.setMainStream(openFile.getPipeStream());
          openFile.setPipeStream(null);
        }

        openFile.setMode(openFile.getMode() & ~OpenFile.READABLE);

        return RubyFixnum.zero(runtime);

      case 1:
        channel = getOpenChannel();
        try {
          SocketType.forChannel(channel).shutdownOutput(channel);

        } catch (IOException e) {
          throw runtime.newIOError(e.getMessage());
        }

        openFile.setPipeStream(null);
        openFile.setMode(openFile.getMode() & ~OpenFile.WRITABLE);

        return RubyFixnum.zero(runtime);

      case 2:
        shutdownInternal(context, 0);
        shutdownInternal(context, 1);

        return RubyFixnum.zero(runtime);

      default:
        throw runtime.newArgumentError("`how' should be either :SHUT_RD, :SHUT_WR, :SHUT_RDWR");
    }
  }
  @Override
  protected ChannelFD initChannelFD(Ruby runtime) {
    Channel channel;

    try {
      if (soType == Sock.SOCK_STREAM) {
        channel = ServerSocketChannel.open();
      } else {
        throw runtime.newArgumentError("unsupported server socket type `" + soType + "'");
      }

      return newChannelFD(runtime, channel);
    } catch (IOException e) {
      throw sockerr(runtime, "initialize: " + e.toString(), e);
    }
  }
  @JRubyMethod(rest = true)
  public RubyObject new_instance2(IRubyObject[] args, Block unusedBlock) {
    final Ruby runtime = getRuntime();
    Arity.checkArgumentCount(runtime, args, 2, 2);

    final IRubyObject self = args[0];
    final Object[] convertedArgs = convertArguments((RubyArray) args[1]); // constructor arguments

    JavaProxyInvocationHandler handler = new MethodInvocationHandler(runtime, self);
    try {
      return JavaObject.wrap(runtime, newInstance(convertedArgs, handler));
    } catch (Exception e) {
      RaiseException ex =
          runtime.newArgumentError("Constructor invocation failed: " + e.getMessage());
      ex.initCause(e);
      throw ex;
    }
  }
Exemple #19
0
  private void strioInit(ThreadContext context, IRubyObject[] args) {
    Ruby runtime = context.runtime;
    RubyString string;
    IRubyObject mode;
    boolean trunc = false;

    switch (args.length) {
      case 2:
        mode = args[1];
        if (mode instanceof RubyFixnum) {
          int flags = RubyFixnum.fix2int(mode);
          ptr.flags = ModeFlags.getOpenFileFlagsFor(flags);
          trunc = (flags & ModeFlags.TRUNC) != 0;
        } else {
          String m = args[1].convertToString().toString();
          ptr.flags = OpenFile.ioModestrFmode(runtime, m);
          trunc = m.charAt(0) == 'w';
        }
        string = args[0].convertToString();
        if ((ptr.flags & OpenFile.WRITABLE) != 0 && string.isFrozen()) {
          throw runtime.newErrnoEACCESError("Permission denied");
        }
        if (trunc) {
          string.resize(0);
        }
        break;
      case 1:
        string = args[0].convertToString();
        ptr.flags = string.isFrozen() ? OpenFile.READABLE : OpenFile.READWRITE;
        break;
      case 0:
        string = RubyString.newEmptyString(runtime, runtime.getDefaultExternalEncoding());
        ptr.flags = OpenFile.READWRITE;
        break;
      default:
        throw runtime.newArgumentError(args.length, 2);
    }

    ptr.string = string;
    ptr.pos = 0;
    ptr.lineno = 0;
    // funky way of shifting readwrite flags into object flags
    flags |= (ptr.flags & OpenFile.READWRITE) * (STRIO_READABLE / OpenFile.READABLE);
  }
Exemple #20
0
  private IRubyObject defaultObjectUnmarshal() throws IOException {
    RubySymbol className = (RubySymbol) unmarshalObject(false);

    RubyClass type = null;
    try {
      type = getClassFromPath(runtime, className.toString());
    } catch (RaiseException e) {
      if (runtime.getModule("NameError").isInstance(e.getException())) {
        throw runtime.newArgumentError("undefined class/module " + className.asJavaString());
      }

      throw e;
    }

    assert type != null : "type shouldn't be null.";

    IRubyObject result = (IRubyObject) type.unmarshal(this);

    return result;
  }
Exemple #21
0
    @JRubyMethod(name = "registered?")
    public IRubyObject isRegistered(ThreadContext context, IRubyObject io) {
      Ruby runtime = context.getRuntime();
      Channel rawChannel = RubyIO.convertToIO(context, io).getChannel();

      if (!(rawChannel instanceof SelectableChannel)) {
        throw runtime.newArgumentError("not a selectable IO object");
      }

      SelectableChannel channel = (SelectableChannel) rawChannel;
      SelectionKey key = channel.keyFor(this.selector);

      if (key == null) return context.nil;

      if (((Monitor) key.attachment()).isClosed(context) == runtime.getTrue()) {
        return runtime.getFalse();
      } else {
        return runtime.getTrue();
      }
    }
Exemple #22
0
    @JRubyMethod
    public IRubyObject deregister(ThreadContext context, IRubyObject io) {
      Ruby runtime = context.getRuntime();
      Channel rawChannel = RubyIO.convertToIO(context, io).getChannel();

      if (!(rawChannel instanceof SelectableChannel)) {
        throw runtime.newArgumentError("not a selectable IO object");
      }

      SelectableChannel channel = (SelectableChannel) rawChannel;
      SelectionKey key = channel.keyFor(this.selector);

      if (key == null) return context.nil;

      Monitor monitor = (Monitor) key.attachment();
      monitor.close(context, runtime.getFalse());
      cancelledKeys.put(channel, key);

      return monitor;
    }
Exemple #23
0
  @JRubyMethod(name = "readlines", optional = 2)
  public IRubyObject readlines(ThreadContext context, IRubyObject[] args) {
    Ruby runtime = context.runtime;

    if (args.length > 0
        && !args[args.length - 1].isNil()
        && args[args.length - 1].checkStringType19().isNil()
        && RubyNumeric.num2long(args[args.length - 1]) == 0) {
      throw runtime.newArgumentError("invalid limit: 0 for each_line");
    }

    RubyArray ary = runtime.newArray();
    IRubyObject line;

    checkReadable();

    while (!(line = getline(context, args)).isNil()) {
      ary.append(line);
    }
    return ary;
  }
    private IRubyObject invokeRuby(
        final DynamicMethod method,
        final JavaProxyMethod proxyMethod,
        final RubyClass metaClass,
        final String name,
        final Object[] nargs) {
      final IRubyObject[] newArgs = new IRubyObject[nargs.length];
      for (int i = nargs.length; --i >= 0; ) {
        newArgs[i] = JavaUtil.convertJavaToUsableRubyObject(runtime, nargs[i]);
      }

      final int arity = method.getArity().getValue();

      if (arity < 0 || arity == newArgs.length) {
        final ThreadContext context = runtime.getCurrentContext();
        return method.call(context, self, metaClass, name, newArgs);
      }
      if (proxyMethod.hasSuperImplementation()) {
        final ThreadContext context = runtime.getCurrentContext();
        final RubyClass superClass = metaClass.getSuperClass();
        return Helpers.invokeAs(context, superClass, self, name, newArgs, Block.NULL_BLOCK);
      }
      throw runtime.newArgumentError(newArgs.length, arity);
    }
Exemple #25
0
    /* Run the selector */
    private int doSelect(Ruby runtime, ThreadContext context, IRubyObject timeout) {
      int result;

      cancelKeys();
      try {
        context.getThread().beforeBlockingCall();
        if (timeout.isNil()) {
          result = this.selector.select();
        } else {
          double t = RubyNumeric.num2dbl(timeout);
          if (t == 0) {
            result = this.selector.selectNow();
          } else if (t < 0) {
            throw runtime.newArgumentError("time interval must be positive");
          } else {
            result = this.selector.select((long) (t * 1000));
          }
        }
        context.getThread().afterBlockingCall();
        return result;
      } catch (IOException ie) {
        throw runtime.newIOError(ie.getLocalizedMessage());
      }
    }
Exemple #26
0
  public static IRubyObject getnameinfo(ThreadContext context, IRubyObject[] args) {
    Ruby runtime = context.runtime;
    int flags = args.length == 2 ? RubyNumeric.num2int(args[1]) : 0;
    IRubyObject arg0 = args[0];
    String host, port;

    if (arg0 instanceof RubyArray) {
      List list = ((RubyArray) arg0).getList();
      int len = list.size();

      if (len < 3 || len > 4) {
        throw runtime.newArgumentError("array size should be 3 or 4, " + len + " given");
      }

      // if array has 4 elements, third element is ignored
      host = list.size() == 3 ? list.get(2).toString() : list.get(3).toString();
      port = list.get(1).toString();

    } else if (arg0 instanceof RubyString) {
      String arg = ((RubyString) arg0).toString();
      Matcher m = STRING_IPV4_ADDRESS_PATTERN.matcher(arg);

      if (!m.matches()) {
        IRubyObject obj = unpack_sockaddr_in(context, arg0);

        if (obj instanceof RubyArray) {
          List list = ((RubyArray) obj).getList();
          int len = list.size();

          if (len != 2) {
            throw runtime.newArgumentError("invalid address representation");
          }

          host = list.get(1).toString();
          port = list.get(0).toString();

        } else {
          throw runtime.newArgumentError("invalid address string");
        }

      } else if ((host = m.group(IPV4_HOST_GROUP)) == null
          || host.length() == 0
          || (port = m.group(IPV4_PORT_GROUP)) == null
          || port.length() == 0) {

        throw runtime.newArgumentError("invalid address string");

      } else {

        // Try IPv6
        try {
          InetAddress ipv6_addr = InetAddress.getByName(host);

          if (ipv6_addr instanceof Inet6Address) {
            host = ipv6_addr.getHostAddress();
          }

        } catch (UnknownHostException uhe) {
          throw runtime.newArgumentError("invalid address string");
        }
      }

    } else {
      throw runtime.newArgumentError("invalid args");
    }

    InetAddress addr;

    try {
      addr = InetAddress.getByName(host);

    } catch (UnknownHostException e) {
      throw sockerr(runtime, "unknown host: " + host);
    }

    if ((flags & NI_NUMERICHOST.intValue()) == 0) {
      host = addr.getCanonicalHostName();

    } else {
      host = addr.getHostAddress();
    }

    jnr.netdb.Service serv = jnr.netdb.Service.getServiceByPort(Integer.parseInt(port), null);

    if (serv != null) {

      if ((flags & NI_NUMERICSERV.intValue()) == 0) {
        port = serv.getName();

      } else {
        port = Integer.toString(serv.getPort());
      }
    }

    return runtime.newArray(runtime.newString(host), runtime.newString(port));
  }
 @Override
 public void checkArgCount(Ruby runtime, int length) {
   if (length != 2) throw runtime.newArgumentError(length, 2);
 }
Exemple #28
0
  @JRubyMethod
  public IRubyObject parse(ThreadContext context, IRubyObject target) {
    Ruby runtime = context.runtime;

    // FIXME? only supports Unicode, since we have to produces strings...
    StreamReader reader;
    if (target.respondsTo("read")) {
      reader = new StreamReader(new InputStreamReader(new IOInputStream(target)));
    } else {
      reader = new StreamReader(new StringReader(target.convertToString().asJavaString()));
    }
    Parser parser = new ParserImpl(reader);
    IRubyObject handler = getInstanceVariable("@handler");
    Event event;

    while (true) {
      try {
        event = parser.getEvent();

        // FIXME: Event should expose a getID, so it can be switched
        if (event.is(ID.StreamStart)) {
          invoke(context, handler, "start_stream", runtime.newFixnum(YAML_ANY_ENCODING));
        } else if (event.is(ID.DocumentStart)) {
          DocumentStartEvent dse = (DocumentStartEvent) event;

          Integer[] versionInts = dse.getVersion();
          IRubyObject version =
              versionInts == null
                  ? runtime.getNil()
                  : RubyArray.newArray(
                      runtime,
                      runtime.newFixnum(versionInts[0]),
                      runtime.newFixnum(versionInts[1]));

          Map<String, String> tagsMap = dse.getTags();
          RubyArray tags = RubyArray.newArray(runtime);
          if (tags.size() > 0) {
            for (Map.Entry<String, String> tag : tagsMap.entrySet()) {
              tags.append(
                  RubyArray.newArray(
                      runtime,
                      RubyString.newString(runtime, tag.getKey()),
                      RubyString.newString(runtime, tag.getValue())));
            }
          }

          invoke(
              context,
              handler,
              "start_document",
              version,
              tags,
              runtime.newBoolean(dse.getExplicit()));
        } else if (event.is(ID.DocumentEnd)) {
          DocumentEndEvent dee = (DocumentEndEvent) event;
          invoke(context, handler, "end_document", runtime.newBoolean(dee.getExplicit()));
        } else if (event.is(ID.Alias)) {
          AliasEvent ae = (AliasEvent) event;
          IRubyObject alias = runtime.getNil();
          if (ae.getAnchor() != null) {
            alias = RubyString.newString(runtime, ae.getAnchor());
          }

          invoke(context, handler, "alias", alias);
        } else if (event.is(ID.Scalar)) {
          ScalarEvent se = (ScalarEvent) event;
          IRubyObject anchor =
              se.getAnchor() == null
                  ? runtime.getNil()
                  : RubyString.newString(runtime, se.getAnchor());
          IRubyObject tag =
              se.getTag() == null ? runtime.getNil() : RubyString.newString(runtime, se.getTag());
          IRubyObject plain_implicit = runtime.newBoolean(se.getImplicit().isFirst());
          IRubyObject quoted_implicit = runtime.newBoolean(se.getImplicit().isSecond());
          IRubyObject style = runtime.newFixnum(se.getStyle());
          IRubyObject val = RubyString.newString(runtime, se.getValue());

          invoke(
              context, handler, "scalar", val, anchor, tag, plain_implicit, quoted_implicit, style);
        } else if (event.is(ID.SequenceStart)) {
          SequenceStartEvent sse = (SequenceStartEvent) event;
          IRubyObject anchor =
              sse.getAnchor() == null
                  ? runtime.getNil()
                  : RubyString.newString(runtime, sse.getAnchor());
          IRubyObject tag =
              sse.getTag() == null ? runtime.getNil() : RubyString.newString(runtime, sse.getTag());
          IRubyObject implicit = runtime.newBoolean(sse.getImplicit());
          IRubyObject style = runtime.newFixnum(sse.getFlowStyle() ? 1 : 0);

          invoke(context, handler, "start_sequence", anchor, tag, implicit, style);
        } else if (event.is(ID.SequenceEnd)) {
          invoke(context, handler, "end_sequence");
        } else if (event.is(ID.MappingStart)) {
          MappingStartEvent mse = (MappingStartEvent) event;
          IRubyObject anchor =
              mse.getAnchor() == null
                  ? runtime.getNil()
                  : RubyString.newString(runtime, mse.getAnchor());
          IRubyObject tag =
              mse.getTag() == null ? runtime.getNil() : RubyString.newString(runtime, mse.getTag());
          IRubyObject implicit = runtime.newBoolean(mse.getImplicit());
          IRubyObject style = runtime.newFixnum(mse.getFlowStyle() ? 1 : 0);

          invoke(context, handler, "start_mapping", anchor, tag, implicit, style);
        } else if (event.is(ID.MappingEnd)) {
          invoke(context, handler, "end_mapping");
        } else if (event.is(ID.StreamEnd)) {
          invoke(context, handler, "end_stream");
          break;
        }
      } catch (ParserException pe) {
        parser = null;
        RubyKernel.raise(
            context,
            runtime.getModule("Psych").getConstant("SyntaxError"),
            new IRubyObject[] {runtime.newString(pe.getLocalizedMessage())},
            Block.NULL_BLOCK);
      } catch (ScannerException se) {
        parser = null;
        StringBuilder message = new StringBuilder("syntax error");
        if (se.getProblemMark() != null) {
          message.append(se.getProblemMark().toString());
        }
        throw runtime.newArgumentError(message.toString());
      }
    }

    return this;
  }
Exemple #29
0
  public static void buildAddrinfoList(
      ThreadContext context, IRubyObject[] args, AddrinfoCallback callback) {
    Ruby runtime = context.runtime;
    IRubyObject host = args[0];
    IRubyObject port = args[1];
    boolean emptyHost = host.isNil() || host.convertToString().isEmpty();

    try {
      if (port instanceof RubyString) {
        port = getservbyname(context, new IRubyObject[] {port});
      }

      IRubyObject family = args.length > 2 ? args[2] : context.nil;
      IRubyObject socktype = args.length > 3 ? args[3] : context.nil;
      // IRubyObject protocol = args[4];
      IRubyObject flags = args.length > 5 ? args[5] : context.nil;
      IRubyObject reverseArg = args.length > 6 ? args[6] : context.nil;

      // The Ruby Socket.getaddrinfo function supports boolean/nil/Symbol values for the
      // reverse_lookup parameter. We need to massage all valid inputs to true/false/null.
      Boolean reverseLookup = null;
      if (reverseArg instanceof RubyBoolean) {
        reverseLookup = reverseArg.isTrue();
      } else if (reverseArg instanceof RubySymbol) {
        String reverseString = reverseArg.toString();
        if ("hostname".equals(reverseString)) {
          reverseLookup = true;
        } else if ("numeric".equals(reverseString)) {
          reverseLookup = false;
        } else {
          throw runtime.newArgumentError("invalid reverse_lookup flag: :" + reverseString);
        }
      }

      AddressFamily addressFamily = AF_INET;
      if (!family.isNil()) {
        addressFamily = addressFamilyFromArg(family);
      }
      boolean is_ipv6 = addressFamily == AddressFamily.AF_INET6;
      boolean sock_stream = true;
      boolean sock_dgram = true;

      Sock sock = SOCK_STREAM;
      if (!socktype.isNil()) {
        sockFromArg(socktype);

        if (sock == SOCK_STREAM) {
          sock_dgram = false;

        } else if (sock == SOCK_DGRAM) {
          sock_stream = false;
        }
      }

      // When Socket::AI_PASSIVE and host is nil, return 'any' address.
      InetAddress[] addrs = null;

      if (!flags.isNil() && RubyFixnum.fix2int(flags) > 0) {
        // The value of 1 is for Socket::AI_PASSIVE.
        int flag = RubyNumeric.fix2int(flags);

        if ((flag == 1) && emptyHost) {
          // use RFC 2732 style string to ensure that we get Inet6Address
          addrs = InetAddress.getAllByName(is_ipv6 ? "[::]" : "0.0.0.0");
        }
      }

      if (addrs == null) {
        addrs =
            InetAddress.getAllByName(
                emptyHost ? (is_ipv6 ? "[::1]" : null) : host.convertToString().toString());
      }

      for (int i = 0; i < addrs.length; i++) {
        int p = port.isNil() ? 0 : (int) port.convertToInteger().getLongValue();
        callback.addrinfo(addrs[i], p, sock, reverseLookup);
      }

    } catch (UnknownHostException e) {
      throw sockerr(runtime, "getaddrinfo: name or service not known");
    }
  }
Exemple #30
0
  @JRubyMethod(rest = true)
  public IRubyObject initialize(ThreadContext context, IRubyObject[] _events, final Block block) {
    final Ruby runtime = context.runtime;

    if (!block.isGiven()) throw runtime.newThreadError("must be called with a block");

    RubyEvent[] events = new RubyEvent[_events.length];
    for (int i = 0; i < _events.length; i++) {
      IRubyObject _event = _events[i];
      if (_event instanceof RubySymbol || _event instanceof RubyString) {
        String eventName = _event.asJavaString();
        RubyEvent event = RubyEvent.valueOf(eventName);

        if (event == null) throw runtime.newArgumentError("unknown event: " + eventName);

        events[i] = event;
      }
    }

    EnumSet<RubyEvent> _eventSet;
    if (events.length > 0) {
      _eventSet = EnumSet.copyOf(Arrays.asList(events));
    } else {
      _eventSet = EnumSet.allOf(RubyEvent.class);
    }

    final EnumSet<RubyEvent> eventSet = _eventSet;
    hook =
        new EventHook() {
          @Override
          public synchronized void eventHandler(
              ThreadContext context,
              String eventName,
              String file,
              int line,
              String name,
              IRubyObject type) {
            if (!enabled || context.isWithinTrace()) return;

            inside = true;
            try {
              if (file == null) file = "(ruby)";
              if (type == null) type = context.runtime.getFalse();

              RubyBinding binding =
                  RubyBinding.newBinding(context.runtime, context.currentBinding());

              context.preTrace();

              // FIXME: get return value
              update(
                  eventName, file, line, name, type, context.getErrorInfo(), context.nil, binding);

              block.yieldSpecific(context, TracePoint.this);
            } finally {
              update(null, null, line, null, context.nil, context.nil, context.nil, context.nil);
              context.postTrace();
              inside = false;
            }
          }

          @Override
          public boolean isInterestedInEvent(RubyEvent event) {
            return eventSet.contains(event);
          }
        };

    return context.nil;
  }