private static void addBackTraceElement( Ruby runtime, RubyArray backtrace, RubyStackTraceElement frame, RubyStackTraceElement previousFrame) { if (frame != previousFrame && // happens with native exceptions, should not filter those out frame.getLineNumber() == previousFrame.getLineNumber() && frame.getMethodName() != null && frame.getMethodName().equals(previousFrame.getMethodName()) && frame.getFileName() != null && frame.getFileName().equals(previousFrame.getFileName())) { return; } RubyString traceLine; String fileName = frame.getFileName(); if (fileName == null) fileName = ""; if (previousFrame.getMethodName() == UNKNOWN_NAME) { traceLine = RubyString.newString(runtime, fileName + ':' + (frame.getLineNumber())); } else { traceLine = RubyString.newString( runtime, fileName + ':' + (frame.getLineNumber()) + ":in `" + previousFrame.getMethodName() + '\''); } backtrace.append(traceLine); }
private static void addBackTraceElement( Ruby runtime, RubyArray backtrace, Frame frame, Frame previousFrame) { if (frame != previousFrame && // happens with native exceptions, should not filter those out frame.getLine() == previousFrame.getLine() && frame.getName() != null && frame.getName().equals(previousFrame.getName()) && frame.getFile().equals(previousFrame.getFile())) { return; } RubyString traceLine; if (previousFrame.getName() != null) { traceLine = RubyString.newString( runtime, frame.getFile() + ':' + (frame.getLine() + 1) + ":in `" + previousFrame.getName() + '\''); } else if (runtime.is1_9()) { // TODO: This probably isn't the best hack, but it works until we can have different // root frame setup for 1.9 easily. traceLine = RubyString.newString( runtime, frame.getFile() + ':' + (frame.getLine() + 1) + ":in `<main>'"); } else { traceLine = RubyString.newString(runtime, frame.getFile() + ':' + (frame.getLine() + 1)); } backtrace.append(traceLine); }
/** * Take the boolean value and convert it to its bytes. * * @param bool The Ruby boolean value. * @return The byte array. * @since 2.0.0 */ private static RubyString toBsonBoolean(final IRubyObject bool) { final Ruby runtime = bool.getRuntime(); if (bool == runtime.getTrue()) { return RubyString.newString(runtime, TRUE_BYTES); } else { return RubyString.newString(runtime, FALSE_BYTES); } }
public void testUnicodeChars() throws Exception { File file = new File("unicodeáéíóú"); if (file.exists()) { if (!file.delete()) { fail("Unable to delete file: " + file); } } try { if (!file.mkdirs()) { fail("Unable to create directory: " + file); } Ruby runtime; RubyInstanceConfig.nativeEnabled = false; runtime = Ruby.newInstance(); JRubyFile rubyFile = RubyFile.file(RubyString.newString(runtime, file.getAbsolutePath())); assertTrue(rubyFile.exists()); assertTrue(file.exists()); assertTrue(file.isDirectory()); try { assertTrue(runtime.getPosix().stat(rubyFile.getAbsolutePath()).isDirectory()); } catch (Exception e) { throw new RuntimeException("Expecting posix layer to work properly", e); } } finally { if (file.exists()) { file.delete(); } } }
@JRubyMethod(name = "sign") public IRubyObject sign(IRubyObject digest, IRubyObject data) { if (!this.callMethod(getRuntime().getCurrentContext(), "private?").isTrue()) { throw getRuntime().newArgumentError("Private key is needed."); } String digAlg = ((Digest) digest).getShortAlgorithm(); try { Signature signature = SecurityHelper.getSignature(digAlg + "WITH" + getAlgorithm()); signature.initSign(getPrivateKey()); byte[] inp = data.convertToString().getBytes(); signature.update(inp); byte[] sigge = signature.sign(); return RubyString.newString(getRuntime(), sigge); } catch (GeneralSecurityException gse) { throw newPKeyError(getRuntime(), gse.getMessage()); } /* GetPKey(self, pkey); EVP_SignInit(&ctx, GetDigestPtr(digest)); StringValue(data); EVP_SignUpdate(&ctx, RSTRING(data)->ptr, RSTRING(data)->len); str = rb_str_new(0, EVP_PKEY_size(pkey)+16); if (!EVP_SignFinal(&ctx, RSTRING(str)->ptr, &buf_len, pkey)) ossl_raise(ePKeyError, NULL); assert(buf_len <= RSTRING(str)->len); RSTRING(str)->len = buf_len; RSTRING(str)->ptr[buf_len] = 0; return str; */ }
protected boolean tryLoadingLibraryOrScript(Ruby runtime, SearchState state) { // attempt to load the found library RubyString loadNameRubyString = RubyString.newString(runtime, state.loadName); try { synchronized (loadedFeaturesInternal) { if (loadedFeaturesInternal.contains(loadNameRubyString)) { return false; } else { addLoadedFeature(loadNameRubyString); } } // otherwise load the library we've found state.library.load(runtime, false); return true; } catch (MainExitException mee) { // allow MainExitException to propagate out for exec and friends throw mee; } catch (Throwable e) { if (isJarfileLibrary(state, state.searchFile)) { return true; } removeLoadedFeature(loadNameRubyString); reraiseRaiseExceptions(e); if (runtime.getDebug().isTrue()) e.printStackTrace(runtime.getErr()); RaiseException re = newLoadErrorFromThrowable(runtime, state.searchFile, e); re.initCause(e); throw re; } }
@JRubyMethod public IRubyObject to_der() { try { return RubyString.newString(getRuntime(), crl_v.getEncoded()); } catch (IOException ioe) { throw newX509CRLError(getRuntime(), ioe.getMessage()); } }
// Make string based on internal data encoding (which ironically is its // external encoding. This seems messy and we should consider a more // uniform method for makeing strings (we have a slightly different variant // of this in RubyIO. private RubyString makeString(Ruby runtime, ByteList buf) { if (runtime.is1_9()) buf.setEncoding(data.internal.getEncoding()); RubyString str = RubyString.newString(runtime, buf); str.setTaint(true); return str; }
// Make string based on internal data encoding (which ironically is its // external encoding. This seems messy and we should consider a more // uniform method for makeing strings (we have a slightly different variant // of this in RubyIO. private RubyString makeString(Ruby runtime, ByteList buf, boolean setEncoding) { if (runtime.is1_9() && setEncoding) buf.setEncoding(ptr.string.getEncoding()); RubyString str = RubyString.newString(runtime, buf); str.setTaint(true); return str; }
public void trySearch(SearchState state) throws AlreadyLoaded { for (String suffix : state.suffixType.getSuffixes()) { String searchName = state.searchFile + suffix; RubyString searchNameString = RubyString.newString(runtime, searchName); if (featureAlreadyLoaded(searchNameString)) { throw new AlreadyLoaded(searchNameString); } } }
@Override @JRubyMethod public RubyString inspect() { StringBuilder str = new StringBuilder(); str.append("#<"); str.append(getDeclaringClass().nameOnInspection()); inspectParameterTypes(str, this); str.append('>'); return RubyString.newString(getRuntime(), str); }
@JRubyMethod public IRubyObject recv(ThreadContext context, IRubyObject _length) { Ruby runtime = context.runtime; ByteList bytes = doReceive(context, RubyNumeric.fix2int(_length)); if (bytes == null) return context.nil; return RubyString.newString(runtime, bytes); }
@Override public Object retrieve( ThreadContext context, IRubyObject self, StaticScope currScope, DynamicScope currDynScope, Object[] temp) { return context.runtime.freezeAndDedupString( RubyString.newString(context.runtime, bytelist, coderange)); }
@JRubyMethod public IRubyObject to_der() { try { byte[] bytes = org.jruby.ext.openssl.impl.PKey.toDerDSAKey(pubKey, privKey); return RubyString.newString(getRuntime(), bytes); } catch (NoClassDefFoundError ncdfe) { throw newDSAError(getRuntime(), OpenSSLReal.bcExceptionMessage(ncdfe)); } catch (IOException ioe) { throw newDSAError(getRuntime(), ioe.getMessage()); } }
public void testStrConvEncThatGrows() throws Exception { String javaStr = "--- こんにちは!"; RubyString rubyStr = RubyString.newString(runtime, javaStr); rubyStr = EncodingUtils.strConvEnc( runtime.getCurrentContext(), rubyStr, rubyStr.getEncoding(), SJISEncoding.INSTANCE); assertEquals(rubyStr.getEncoding(), SJISEncoding.INSTANCE); rubyStr = EncodingUtils.strConvEnc( runtime.getCurrentContext(), rubyStr, SJISEncoding.INSTANCE, UTF8Encoding.INSTANCE); assertEquals(rubyStr.getEncoding(), UTF8Encoding.INSTANCE); }
@Override @JRubyMethod( name = {"to_s", "inspect"}, optional = 1) public IRubyObject to_s(ThreadContext context, IRubyObject[] args) { String s = size != Long.MAX_VALUE ? String.format( "#<%s address=0x%x size=%s>", getMetaClass().getName(), getAddress(), size) : String.format("#<%s address=0x%x>", getMetaClass().getName(), getAddress()); return RubyString.newString(context.runtime, s); }
private IRubyObject userUnmarshal(MarshalState state) throws IOException { String className = unmarshalObject(false).asJavaString(); ByteList marshaled = unmarshalString(); RubyClass classInstance = findClass(className); RubyString data = RubyString.newString(getRuntime(), marshaled); if (state.isIvarWaiting()) { defaultVariablesUnmarshal(data); state.setIvarWaiting(false); } IRubyObject unmarshaled = classInstance.smartLoadOldUser(data); registerLinkTarget(unmarshaled); return unmarshaled; }
@JRubyMethod public IRubyObject recv_nonblock(ThreadContext context, IRubyObject _length) { Ruby runtime = context.runtime; ByteList bytes = doReceiveNonblock(context, RubyNumeric.fix2int(_length)); if (bytes == null) { if (runtime.is1_9()) { throw runtime.newErrnoEAGAINReadableError("recvfrom(2)"); } else { throw runtime.newErrnoEAGAINError("recvfrom(2)"); } } return RubyString.newString(runtime, bytes); }
public static IRubyObject createRawBacktrace( Ruby runtime, StackTraceElement[] stackTrace, boolean filter) { RubyArray traceArray = RubyArray.newArray(runtime); for (int i = 0; i < stackTrace.length; i++) { StackTraceElement element = stackTrace[i]; if (filter) { if (element.getClassName().startsWith("org.jruby") || element.getLineNumber() < 0) { continue; } } RubyString str = RubyString.newString(runtime, createRubyBacktraceString(element)); traceArray.append(str); } return traceArray; }
public static IRubyObject createRubyCompiledBacktrace( Ruby runtime, StackTraceElement[] stackTrace) { RubyArray traceArray = RubyArray.newArray(runtime); for (int i = 17; i < stackTrace.length; i++) { StackTraceElement element = stackTrace[i]; int index = element.getMethodName().indexOf("$RUBY$"); if (index < 0) continue; String unmangledMethod = element.getMethodName().substring(index + 6); RubyString str = RubyString.newString( runtime, element.getFileName() + ":" + element.getLineNumber() + ":in `" + unmangledMethod + "'"); traceArray.append(str); } return traceArray; }
public static IRubyObject generateMRIBacktrace(Ruby runtime, RubyStackTraceElement[] trace) { if (trace == null) { return runtime.getNil(); } RubyArray traceArray = RubyArray.newArray(runtime); for (int i = 0; i < trace.length; i++) { RubyStackTraceElement element = trace[i]; RubyString str = RubyString.newString( runtime, element.getFileName() + ":" + element.getLineNumber() + ":in `" + element.getMethodName() + "'"); traceArray.append(str); } return traceArray; }
@JRubyMethod(rest = true) public IRubyObject recv(ThreadContext context, IRubyObject[] args) { OpenFile openFile = getOpenFileChecked(); try { context.getThread().beforeBlockingCall(); return RubyString.newString( context.getRuntime(), openFile.getMainStream().read(RubyNumeric.fix2int(args[0]))); } catch (BadDescriptorException e) { throw context.getRuntime().newErrnoEBADFError(); } catch (EOFException e) { // recv returns nil on EOF return context.getRuntime().getNil(); } catch (IOException e) { // All errors to sysread should be SystemCallErrors, but on a closed stream // Ruby returns an IOError. Java throws same exception for all errors so // we resort to this hack... if ("Socket not open".equals(e.getMessage())) { throw context.getRuntime().newIOError(e.getMessage()); } throw context.getRuntime().newSystemCallError(e.getMessage()); } finally { context.getThread().afterBlockingCall(); } }
@JRubyMethod(name = "ruby") public IRubyObject ruby(final ThreadContext ctx) { RubyString string = RubyString.newString(ctx.runtime, value.getBytes(), 0, value.getLength()); string.setEncoding(UTF8Encoding.INSTANCE); return string; }
@JRubyMethod(name = "inspect") public IRubyObject inspect(ThreadContext context) { return RubyString.newString(context.getRuntime(), String.format("#<Buffer size=%d>", size)); }
@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); } } return this; }
public static IRubyObject createRubyHybridBacktrace( Ruby runtime, RubyStackTraceElement[] backtraceFrames, RubyStackTraceElement[] stackTrace, boolean debug) { RubyArray traceArray = RubyArray.newArray(runtime); ThreadContext context = runtime.getCurrentContext(); int rubyFrameIndex = backtraceFrames.length - 1; for (int i = 0; i < stackTrace.length; i++) { RubyStackTraceElement element = stackTrace[i]; // look for mangling markers for compiled Ruby in method name int index = element.getMethodName().indexOf("$RUBY$"); if (index >= 0) { String unmangledMethod = element.getMethodName().substring(index + 6); RubyString str = RubyString.newString( runtime, element.getFileName() + ":" + element.getLineNumber() + ":in `" + unmangledMethod + "'"); traceArray.append(str); // if it's not a rescue or ensure, there's a frame associated, so decrement if (!(element.getMethodName().contains("__rescue__") || element.getMethodName().contains("__ensure__"))) { rubyFrameIndex--; } continue; } // look for __file__ method name for compiled roots if (element.getMethodName().equals("__file__")) { RubyString str = RubyString.newString( runtime, element.getFileName() + ":" + element.getLineNumber() + ": `<toplevel>'"); traceArray.append(str); rubyFrameIndex--; continue; } // look for mangling markers for bound, unframed methods in class name index = element.getClassName().indexOf("$RUBYINVOKER$"); if (index >= 0) { // unframed invokers have no Ruby frames, so pull from class name // but use current frame as file and line String unmangledMethod = element.getClassName().substring(index + 13); Frame current = context.frameStack[rubyFrameIndex]; RubyString str = RubyString.newString( runtime, current.getFile() + ":" + (current.getLine() + 1) + ":in `" + unmangledMethod + "'"); traceArray.append(str); continue; } // look for mangling markers for bound, framed methods in class name index = element.getClassName().indexOf("$RUBYFRAMEDINVOKER$"); if (index >= 0) { // framed invokers will have Ruby frames associated with them addBackTraceElement( traceArray, backtraceFrames[rubyFrameIndex], backtraceFrames[rubyFrameIndex - 1], FrameType.METHOD); rubyFrameIndex--; continue; } // try to mine out a Ruby frame using our list of interpreter entry-point markers String classMethod = element.getClassName() + "." + element.getMethodName(); FrameType frameType = INTERPRETED_FRAMES.get(classMethod); if (frameType != null) { // Frame matches one of our markers for "interpreted" calls if (rubyFrameIndex == 0) { addBackTraceElement( traceArray, backtraceFrames[rubyFrameIndex], backtraceFrames[rubyFrameIndex], frameType); } else { addBackTraceElement( traceArray, backtraceFrames[rubyFrameIndex], backtraceFrames[rubyFrameIndex - 1], frameType); rubyFrameIndex--; } continue; } else { // Frame is extraneous runtime information, skip it unless debug if (debug) { RubyString str = RubyString.newString(runtime, createRubyBacktraceString(element.getElement())); traceArray.append(str); } continue; } } return traceArray; }
private static IRubyObject number(Ruby runtime, int s) { return RubyString.newString(runtime, Pack.packInt_i(new ByteList(4), s)); }
@JRubyMethod(name = "initialize", rest = true, frame = true) public IRubyObject _initialize(IRubyObject[] args, Block block) { extensions = new ArrayList<IRubyObject>(); if (org.jruby.runtime.Arity.checkArgumentCount(getRuntime(), args, 0, 1) == 0) { version = getRuntime().getNil(); issuer = getRuntime().getNil(); last_update = getRuntime().getNil(); next_update = getRuntime().getNil(); revoked = getRuntime().newArray(); return this; } ByteArrayInputStream bis = new ByteArrayInputStream(args[0].convertToString().getBytes()); try { // SunJCE throws java.security.cert.CRLException: Invalid encoding of // AuthorityKeyIdentifierExtension. // FIXME: use BC for now. CertificateFactory cf = OpenSSLReal.getX509CertificateFactoryBC(); crl = (java.security.cert.X509CRL) cf.generateCRL(bis); } catch (GeneralSecurityException gse) { throw newX509CRLError(getRuntime(), gse.getMessage()); } byte[] crl_bytes = args[0].convertToString().getBytes(); // Parse PEM if we ever get passed some PEM contents try { StringReader in = new StringReader(args[0].toString()); byte[] bytes = OpenSSLReal.getFormatHandler().readPEMToDER(in); if (bytes != null) crl_bytes = bytes; in.close(); } catch (Exception e) { // this is not PEM encoded, let's use the default argument } try { crl_v = new ASN1InputStream(new ByteArrayInputStream(crl_bytes)).readObject(); } catch (IOException ioe) { throw newX509CRLError(getRuntime(), ioe.getMessage()); } DEREncodable v0 = ((DERSequence) (((DERSequence) crl_v).getObjectAt(0))).getObjectAt(0); if (v0 instanceof DERInteger) { set_version(getRuntime().newFixnum(((DERInteger) v0).getValue().intValue())); } else { set_version(getRuntime().newFixnum(2)); } set_last_update(RubyTime.newTime(getRuntime(), crl.getThisUpdate().getTime())); set_next_update(RubyTime.newTime(getRuntime(), crl.getNextUpdate().getTime())); RubyString name = RubyString.newString(getRuntime(), crl.getIssuerX500Principal().getEncoded()); set_issuer(Utils.newRubyInstance(getRuntime(), "OpenSSL::X509::Name", name)); revoked = getRuntime().newArray(); DERSequence seqa = (DERSequence) ((DERSequence) crl_v).getObjectAt(0); DERObject maybe_ext = (DERObject) seqa.getObjectAt(seqa.size() - 1); if (maybe_ext instanceof DERTaggedObject && ((DERTaggedObject) maybe_ext).getTagNo() == 0) { DERSequence exts = (DERSequence) ((DERTaggedObject) maybe_ext).getObject(); for (int i = 0; i < exts.size(); i++) { DERSequence seq2 = (DERSequence) exts.getObjectAt(i); boolean critical = false; String oid = ((DERObjectIdentifier) seq2.getObjectAt(0)).getId(); if (seq2.getObjectAt(1) == DERBoolean.TRUE) { critical = true; } byte[] value = crl.getExtensionValue(oid); IRubyObject mASN1 = getRuntime().getClassFromPath("OpenSSL::ASN1"); IRubyObject rValue = null; try { rValue = ASN1.decode( mASN1, ASN1.decode(mASN1, RubyString.newString(getRuntime(), value)) .callMethod(getRuntime().getCurrentContext(), "value")); } catch (Exception e) { rValue = RubyString.newString(getRuntime(), value); } X509Extensions.Extension ext1 = (X509Extensions.Extension) Utils.newRubyInstance(getRuntime(), "OpenSSL::X509::Extension"); ext1.setRealOid(ext1.getObjectIdentifier(oid)); ext1.setRealValue(rValue); ext1.setRealCritical(critical); add_extension(ext1); } } changed = false; return this; }