org.jruby.RubyString Java Examples
The following examples show how to use
org.jruby.RubyString.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MarathonRuby.java From marathonv5 with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") private static RubyArray map2list(Ruby ruby, List<?> list) { RubyArray array = new RubyArray(ruby, list.size()); int index = 0; for (Object v : list) { if (v instanceof String) { array.set(index++, RubyString.newString(ruby, (String) v)); } else if (v instanceof Boolean) { array.set(index++, RubyBoolean.newBoolean(ruby, (boolean) v)); } else if (v instanceof List) { array.set(index++, map2list(ruby, (List<?>) v)); } else { array.set(index++, map2hash(ruby, (Map<String, Object>) v)); } } return array; }
Example #2
Source File: RubySchema.java From spork with Apache License 2.0 | 6 votes |
/** * This method allows the user to set the name of the alias of the FieldSchema of the encapsulated * Schema. This method only works if the Schema has one FieldSchema. * * @param arg a RubyString to set the name to * @return the new name */ @JRubyMethod(name = "name=") public RubyString setName(IRubyObject arg) { if (arg instanceof RubyString) { if (internalSchema.size() != 1) throw new RuntimeException("Can only set name if there is one schema present"); try { internalSchema.getField(0).alias = arg.toString(); return (RubyString)arg; } catch (FrontendException e) { throw new RuntimeException("Unable to get field from Schema", e); } } else { throw new RuntimeException("Improper argument passed to 'name=':" + arg); } }
Example #3
Source File: PigJrubyLibrary.java From spork with Apache License 2.0 | 6 votes |
/** * A type specific conversion routine. * * @param rbObject object to convert * @return analogous Pig type */ @SuppressWarnings("unchecked") public static Map<String, ?> rubyToPig(RubyHash rbObject) throws ExecException { Map<String, Object> newMap = Maps.newHashMap(); for (Map.Entry<Object, Object> entry : (Set<Map.Entry<Object, Object>>)rbObject.entrySet()) { Object key = entry.getKey(); if (!(key instanceof String || key instanceof RubyString || key instanceof RubySymbol)) throw new ExecException("Hash must have String or Symbol key. Was given: " + key.getClass().getName()); String keyStr = key.toString(); if (entry.getValue() instanceof IRubyObject) { newMap.put(keyStr, rubyToPig((IRubyObject)entry.getValue())); } else { newMap.put(keyStr, entry.getValue()); } } return newMap; }
Example #4
Source File: RubyHashUtil.java From asciidoctorj with Apache License 2.0 | 6 votes |
public static RubyHash convertMapToRubyHashWithStrings(Ruby rubyRuntime, Map<String, Object> attributes) { if (attributes instanceof RubyHashMapDecorator) { return ((RubyHashMapDecorator) attributes).getRubyHash(); } else if (attributes instanceof RubyHash) { return (RubyHash) attributes; } RubyHash rubyHash = new RubyHash(rubyRuntime); Set<Entry<String, Object>> optionsSet = attributes.entrySet(); for (Entry<String, Object> entry : optionsSet) { String key = entry.getKey(); Object value = entry.getValue(); RubyString newKey = rubyRuntime.newString(key); IRubyObject iRubyValue = toRubyObject(rubyRuntime, value); rubyHash.put(newKey, iRubyValue); } return rubyHash; }
Example #5
Source File: RubyHashUtil.java From asciidoctorj with Apache License 2.0 | 6 votes |
public static Map<String, Object> convertRubyHashMapToStringObjectMap(RubyHash rubyHashMap) { Map<String, Object> map = new HashMap<String, Object>(); Set<Entry<Object, Object>> elements = rubyHashMap.entrySet(); for (Entry<Object, Object> element : elements) { if(element.getKey() instanceof RubySymbol) { map.put(toJavaString((RubySymbol)element.getKey()), toJavaObject(element.getValue())); } else if (element.getKey() instanceof RubyString) { map.put(((RubyString) element.getKey()).asJavaString(), toJavaObject(element.getValue())); } else if (element.getKey() instanceof String) { map.put((String) element.getKey(), toJavaObject(element.getValue())); } } return map; }
Example #6
Source File: RubyAttributesMapDecorator.java From asciidoctorj with Apache License 2.0 | 6 votes |
private Map<String, Object> createJavaMap() { Map<String, Object> copy = new HashMap<String, Object>(); Set<Entry<Object, Object>> rubyEntrySet = rubyHash.entrySet(); for (Entry<Object, Object> o: rubyEntrySet) { String key; Object rubyKey = o.getKey(); Object rubyValue = o.getValue(); if (rubyKey instanceof RubyString) { key = ((RubyString) rubyKey).asJavaString(); } else if (rubyKey instanceof String) { key = (String) rubyKey; } else if (rubyKey instanceof Number) { key = String.valueOf(rubyKey); } else { continue; } Object value = convertRubyValue(rubyValue); copy.put(key, value); } return copy; }
Example #7
Source File: AbstractScriptRunner.java From APICloud-Studio with GNU General Public License v3.0 | 6 votes |
/** * applyLoadPaths * * @param container */ protected void applyLoadPaths(Ruby runtime) { if (this._loadPaths != null && this._loadPaths.size() > 0) { IRubyObject object = runtime.getLoadService().getLoadPath(); if (object instanceof RubyArray) { RubyArray loadPathArray = (RubyArray) object; // save copy for later this._originalLoadPaths = (RubyArray) loadPathArray.dup(); // Add our custom load paths for (String loadPath : this._loadPaths) { RubyString toAdd = runtime.newString(loadPath.replace('\\', '/')); loadPathArray.append(toAdd); } } } }
Example #8
Source File: RubyHashMapDecorator.java From asciidoctorj with Apache License 2.0 | 6 votes |
private Map<String, Object> createJavaMap() { Map<String, Object> copy = new HashMap<String, Object>(); Set<Entry<Object, Object>> rubyEntrySet = rubyHash.entrySet(); for (Map.Entry<Object, Object> o: rubyEntrySet) { String key = null; Object value; Object rubyKey = o.getKey(); Object rubyValue = o.getValue(); if (rubyKey instanceof RubySymbol) { key = ((RubySymbol) rubyKey).asJavaString(); } else if (rubyKey instanceof RubyString) { key = ((RubyString) rubyKey).asJavaString(); } else if (rubyKey instanceof String) { key = (String) rubyKey; } else if (rubyKey instanceof Long) { // Skip it silently, it is a positional attribute } else { throw new IllegalStateException("Did not expect key " + rubyKey + " of type " + rubyKey.getClass()); } if (key != null) { value = convertRubyValue(rubyValue); copy.put(key, value); } } return copy; }
Example #9
Source File: WhenAnAsciidoctorClassIsInstantiatedInAnEnvironmentWithGemPath.java From asciidoctorj with Apache License 2.0 | 6 votes |
@Test public void should_have_gempath_in_ruby_env_when_created_with_gempath() { // Given: Our environment is polluted (Cannot set these env vars here, so just check that gradle has set them correctly) final String gemPath = "/another/path"; assertThat(System.getenv("GEM_PATH"), notNullValue()); assertThat(System.getenv("GEM_HOME"), notNullValue()); // When: A new Asciidoctor instance is created passing in a null GEM_PATH Asciidoctor asciidoctor = AsciidoctorJRuby.Factory.create(gemPath); // Then: The org.jruby.JRuby instance does not see this variable Ruby rubyRuntime = JRubyRuntimeContext.get(asciidoctor); RubyString rubyGemPath = rubyRuntime.newString(gemPath); assertThat(rubyRuntime.evalScriptlet("ENV['GEM_PATH']"), is((Object) rubyGemPath)); assertThat(rubyRuntime.evalScriptlet("ENV['GEM_HOME']"), is((Object) rubyGemPath)); }
Example #10
Source File: MarathonRuby.java From marathonv5 with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") private static RubyHash map2hash(Ruby ruby, Map<String, Object> ourCaps) { RubyHash hash = new RubyHash(ruby); Set<String> keySet = ourCaps.keySet(); for (String key : keySet) { RubySymbol keySym = RubySymbol.newSymbol(ruby, key); Object v = ourCaps.get(key); if (v instanceof String) { hash.put(keySym, RubyString.newString(ruby, (String) v)); } else if (v instanceof Boolean) { hash.put(keySym, RubyBoolean.newBoolean(ruby, (boolean) v)); } else if (v instanceof List) { hash.put(keySym, map2list(ruby, (List<?>) v)); } else { hash.put(keySym, map2hash(ruby, (Map<String, Object>) v)); } } return hash; }
Example #11
Source File: TextAreaReadline.java From ramus with GNU General Public License v3.0 | 6 votes |
/** * Hooks this <code>TextAreaReadline</code> instance into the runtime, * redefining the <code>Readline</code> module so that it uses this object. * This method does not redefine the standard input-output streams. If you * need that, use {@link #hookIntoRuntimeWithStreams(Ruby)}. * * @param runtime The runtime. * @see #hookIntoRuntimeWithStreams(Ruby) */ public void hookIntoRuntime(final Ruby runtime) { this.runtime = runtime; /* Hack in to replace usual readline with this */ runtime.getLoadService().require("readline"); RubyModule readlineM = runtime.fastGetModule("Readline"); readlineM.defineModuleFunction("readline", new Callback() { public IRubyObject execute(IRubyObject recv, IRubyObject[] args, Block block) { String line = readLine(args[0].toString()); if (line != null) { return RubyString.newUnicodeString(runtime, line); } else { return runtime.getNil(); } } public Arity getArity() { return Arity.twoArguments(); } }); }
Example #12
Source File: RubyDebugger.java From marathonv5 with Apache License 2.0 | 6 votes |
@Override public String run(String script) { try { script = asciize(script); IRubyObject evalScriptlet = interpreter.evalScriptlet(script); if (evalScriptlet instanceof RubyString) { return RubyScriptModel.inspect(evalScriptlet.toString()); } else { return evalScriptlet.inspect().toString(); } } catch (Throwable t) { LOGGER.warning("Script:\n" + script); t.printStackTrace(); } return ""; }
Example #13
Source File: RubyOutputStreamWrapper.java From asciidoctorj with Apache License 2.0 | 5 votes |
private byte[] convertToBytes(IRubyObject arg) { if (arg instanceof RubyString) { return ((RubyString) arg).getBytes(); } else if (arg instanceof RubyNumeric) { return arg.asString().getBytes(); } else { throw new IllegalArgumentException("Don't know how to write a " + arg + " " + arg.getClass()); } }
Example #14
Source File: DefaultCssResolver.java From asciidoctorj with Apache License 2.0 | 5 votes |
private String gemClasspath() { RubyString gemLocationRubyObject = (RubyString) evaler.eval(runtime, "Gem.loaded_specs['asciidoctor'].full_gem_path"); String gemLocation = gemLocationRubyObject.asJavaString(); return gemLocation.substring(gemLocation.indexOf("gems"), gemLocation.length()); }
Example #15
Source File: PigJrubyLibrary.java From spork with Apache License 2.0 | 5 votes |
/** * This method facilitates conversion from Ruby objects to Pig objects. This is * a general class which detects the subclass and invokes the appropriate conversion * routine. It will fail on an unsupported datatype. * * @param rbObject a Ruby object to convert * @return the Pig analogue of the Ruby object * @throws ExecException if rbObject is not of a known type that can be converted */ @SuppressWarnings("unchecked") public static Object rubyToPig(IRubyObject rbObject) throws ExecException { if (rbObject == null || rbObject instanceof RubyNil) { return null; } else if (rbObject instanceof RubyArray) { return rubyToPig((RubyArray)rbObject); } else if (rbObject instanceof RubyHash) { return rubyToPig((RubyHash)rbObject); } else if (rbObject instanceof RubyString) { return rubyToPig((RubyString)rbObject); } else if (rbObject instanceof RubyBignum) { return rubyToPig((RubyBignum)rbObject); } else if (rbObject instanceof RubyFixnum) { return rubyToPig((RubyFixnum)rbObject); } else if (rbObject instanceof RubyFloat) { return rubyToPig((RubyFloat)rbObject); } else if (rbObject instanceof RubyInteger) { return rubyToPig((RubyInteger)rbObject); } else if (rbObject instanceof RubyDataBag) { return rubyToPig((RubyDataBag)rbObject); } else if (rbObject instanceof RubyDataByteArray) { return rubyToPig((RubyDataByteArray)rbObject); } else if (rbObject instanceof RubySchema) { return rubyToPig((RubySchema)rbObject); } else if (rbObject instanceof RubyBoolean) { return rubyToPig((RubyBoolean)rbObject); } else { throw new ExecException("Cannot cast into any pig supported type: " + rbObject.getClass().getName()); } }
Example #16
Source File: JRubyRackInput.java From rack-servlet with Apache License 2.0 | 5 votes |
private IRubyObject toRubyString(byte[] bytes) { if (bytes == null) { return getRuntime().getNil(); } else { return RubyString.newString(getRuntime(), new ByteList(bytes, ascii8bitEncoding)); } }
Example #17
Source File: RubyDataBag.java From spork with Apache License 2.0 | 5 votes |
/** * This method returns a string representation of the RubyDataBag. If given an optional * argument, then if that argument is true, the contents of the bag will also be printed. * * @param context the context the method is being executed in * @param args optional true/false argument passed to inspect * @return string representation of the RubyDataBag */ @JRubyMethod(name = {"inspect", "to_s", "to_string"}, optional = 1) public RubyString inspect(ThreadContext context, IRubyObject[] args) { Ruby runtime = context.getRuntime(); StringBuilder sb = new StringBuilder(); sb.append("[DataBag: size: ").append(internalDB.size()); if (args.length > 0 && args[0].isTrue()) sb.append(" = ").append(internalDB.toString()); sb.append("]"); return RubyString.newString(runtime, sb); }
Example #18
Source File: RubyDataByteArray.java From spork with Apache License 2.0 | 5 votes |
/** * This method calls the set method of the underlying DataByteArray with one exception: * if given a RubyDataByteArray, it will set the encapsulated DataByteArray to be equal. * * @param arg an object to set the encapsulated DataByteArray's bits to. In the case of * a RubyString or byte array, the underlying bytes will be sit directly. In * the case of a RubyDataByteArray, the encapsulated DataByteArray will be set * equal to arg. */ @JRubyMethod public void set(IRubyObject arg) { if (arg instanceof RubyDataByteArray) { internalDBA = ((RubyDataByteArray)arg).getDBA(); } else if (arg instanceof RubyString) { internalDBA.set(arg.toString()); } else { internalDBA.set((byte[])arg.toJava(byte[].class)); } }
Example #19
Source File: RubySchema.java From spork with Apache License 2.0 | 5 votes |
/** * This method allows the user to see the name of the alias of the FieldSchema of the encapsulated * Schema. This method only works if the Schema has one FieldSchema. * * @param context the context the method is being executed in * @return the name of the Schema */ @JRubyMethod(name = "name") public RubyString getName(ThreadContext context) { try { if (internalSchema.size() != 1) throw new RuntimeException("Can only get name if there is one schema present"); return RubyString.newString(context.getRuntime(), internalSchema.getField(0).alias); } catch (FrontendException e) { throw new RuntimeException("Unable to get field from Schema", e); } }
Example #20
Source File: RubySchema.java From spork with Apache License 2.0 | 5 votes |
/** * Given a field name, this will return the index of it in the schema. * * @param context the context the method is being executed in * @param arg a field name to look for * @return the index for that field name */ @JRubyMethod public RubyFixnum index(ThreadContext context, IRubyObject arg) { if (arg instanceof RubyString) { try { return new RubyFixnum(context.getRuntime(), internalSchema.getPosition(arg.toString())); } catch (FrontendException e) { throw new RuntimeException("Unable to find position for argument: " + arg); } } else { throw new RuntimeException("Invalid arguement passed to index: " + arg); } }
Example #21
Source File: RubySchema.java From spork with Apache License 2.0 | 5 votes |
/** * Given a field name this string will search the RubySchema for a FieldSchema * with that name and return it encapsulated in a Schema. * * @param context the context the method is being executed in * @param arg a RubyString serving as an alias to look * for in the Schema * @return the found RubySchema */ @JRubyMethod public RubySchema find(ThreadContext context, IRubyObject arg) { if (arg instanceof RubyString) { Ruby runtime = context.getRuntime(); return new RubySchema(runtime, runtime.getClass("Schema"), RubySchema.find(internalSchema, arg.toString()), false); } else { throw new RuntimeException("Invalid arguement passed to find: " + arg); } }
Example #22
Source File: RubySchema.java From spork with Apache License 2.0 | 5 votes |
/** * This is just a convenience method which sets the name of the internalSchema to the argument that was given. * * @param arg a RubyString to set the name of the encapsulated Schema object */ private void setNameIf(IRubyObject arg) { if (arg instanceof RubyString) { setName(arg.toString()); } else { throw new RuntimeException("Bad name given"); } }
Example #23
Source File: RubyRegexpAutoIndentStrategy.java From APICloud-Studio with GNU General Public License v3.0 | 5 votes |
protected boolean matchesRegexp(RubyRegexp regexp, String lineContent) { if (regexp == null) return false; RubyString string = regexp.getRuntime().newString(lineContent); IRubyObject matcher = regexp.match_m(regexp.getRuntime().getCurrentContext(), string); return !matcher.isNil(); }
Example #24
Source File: DissectPair.java From logstash-filter-dissect with Apache License 2.0 | 5 votes |
private DissectPair(final RubyString left, final String val) { lhs = left; jlhs = lhs.toString(); empty = val.isEmpty(); if (empty) { dissector = new Dissector(); } else { dissector = Dissector.create(val); } }
Example #25
Source File: RubyDataByteArray.java From spork with Apache License 2.0 | 4 votes |
/** * @param context the context the method is being executed in * @return the string representation of the encapsulated DataByteArray */ @JRubyMethod(name = {"to_s", "inspect"}) public IRubyObject toString(ThreadContext context) { return RubyString.newString(context.getRuntime(), internalDBA.toString()); }
Example #26
Source File: RubyRegexpFolder.java From APICloud-Studio with GNU General Public License v3.0 | 4 votes |
public Map<ProjectionAnnotation, Position> emitFoldingRegions(boolean initialReconcile, IProgressMonitor monitor, IParseRootNode ast) throws BadLocationException { int lineCount = fDocument.getNumberOfLines(); if (lineCount <= 1) // Quick hack fix for minified files. We need at least two lines to have folding! { return Collections.emptyMap(); } Map<ProjectionAnnotation, Position> newPositions = new HashMap<ProjectionAnnotation, Position>(lineCount >> 2); Map<Integer, Integer> starts = new HashMap<Integer, Integer>(3); if (monitor != null) { monitor.beginTask(Messages.CommonReconcilingStrategy_FoldingTaskName, lineCount); } for (int currentLine = 0; currentLine < lineCount; currentLine++) { // Check for cancellation if (monitor != null && monitor.isCanceled()) return newPositions; IRegion lineRegion = fDocument.getLineInformation(currentLine); int offset = lineRegion.getOffset(); String line = fDocument.get(offset, lineRegion.getLength()); // Use scope at beginning of line for start regexp RubyRegexp startRegexp = getStartFoldRegexp(getScopeAtOffset(offset)); if (startRegexp == null) { if (monitor != null) monitor.worked(1); continue; } // Use scope at end of line for end regexp RubyRegexp endRegexp = getEndFoldRegexp(getScopeAtOffset(offset + lineRegion.getLength())); if (endRegexp == null) { if (monitor != null) monitor.worked(1); continue; } // Look for an open... RubyString rLine = startRegexp.getRuntime().newString(line); IRubyObject startMatcher = startRegexp.match_m(startRegexp.getRuntime().getCurrentContext(), rLine); if (!startMatcher.isNil()) { starts.put(findIndent(line), offset); // cheat and just give offset of line since line resolution is all // that matters } // Don't look for an end if there's no open yet! if (starts.size() > 0) { // check to see if we have an open folding region at this indent level... int indent = findIndent(line); // Subtract one if we're handling /* */ folding! if (line.trim().startsWith("*")) //$NON-NLS-1$ { indent--; } if (starts.containsKey(indent)) { IRubyObject endMatcher = endRegexp.match_m(endRegexp.getRuntime().getCurrentContext(), rLine); if (!endMatcher.isNil()) { int startingOffset = starts.remove(indent); int startLine = fDocument.getLineOfOffset(startingOffset); if (startLine != currentLine) { int end = lineRegion.getOffset() + lineRegion.getLength() + 1; // cheat and just use end of // line if (end > fDocument.getLength()) { end = fDocument.getLength(); } int posLength = end - startingOffset; if (posLength > 0) { Position position = new Position(startingOffset, posLength); newPositions.put(new ProjectionAnnotation(), position); } } } } } if (monitor != null) monitor.worked(1); } if (monitor != null) { monitor.done(); } return newPositions; }
Example #27
Source File: DissectPair.java From logstash-filter-dissect with Apache License 2.0 | 4 votes |
RubyString key() { return lhs; }
Example #28
Source File: JavaDissectorLibrary.java From logstash-filter-dissect with Apache License 2.0 | 4 votes |
private void invokeDissection(final ThreadContext ctx, final JrubyEventExtLibrary.RubyEvent rubyEvent, final Event event) { // as there can be multiple dissect patterns, any success is a positive metric for (final DissectPair dissectPair : dissectors) { if (dissectPair.isEmpty()) { continue; } if (!event.includes(dissectPair.javaKey())) { invokeFailuresMetric(ctx); LOGGER.warn("Dissector mapping, field not found in event", addLoggableEvent(ctx, rubyEvent, createHashInclField(ctx, dissectPair.key()))); continue; } // use ruby event here because we want the bytelist bytes // from the ruby extract without converting to Java final RubyString src = rubyEvent.ruby_get_field(ctx, dissectPair.key()).asString(); if (src.isNil()) { LOGGER.warn("Dissector mapping, no value found for field", addLoggableEvent(ctx, rubyEvent, createHashInclField(ctx, dissectPair.key()))); invokeFailureTagsAndMetric(ctx, event); continue; } if (src.isEmpty()) { invokeFailureTagsAndMetric(ctx, event); LOGGER.warn("Dissector mapping, field found in event but it was empty", addLoggableEvent(ctx, rubyEvent, createHashInclField(ctx, dissectPair.key()))); continue; } final byte[] bytes = src.getBytes(); final DissectResult result = dissectPair.dissector().dissect(bytes, event); if (result.matched()) { if (runMatched) { invokeFilterMatched(ctx, rubyEvent); } invokeMatchesMetric(ctx); } else { invokeFailureTagsAndMetric(ctx, event); final RubyHash loggableMap = createHashInclField(ctx, dissectPair.key()); loggableMap.put("pattern", dissectPair.dissector().getMapping()); LOGGER.warn("Dissector mapping, pattern not found", addLoggableEvent(ctx, rubyEvent, loggableMap)); } } }
Example #29
Source File: WhenEnvironmentVariablesAreSet.java From asciidoctorj with Apache License 2.0 | 3 votes |
@Test public void they_should_be_available_inside_ruby_engine() { JRubyAsciidoctor asciidoctor = (JRubyAsciidoctor) JRubyAsciidoctor.create("My_gem_path"); IRubyObject evalScriptlet = asciidoctor.rubyRuntime.evalScriptlet("ENV['GEM_PATH']"); RubyString gemPathValue = (RubyString)evalScriptlet; assertThat(gemPathValue.asJavaString(), is("My_gem_path")); }
Example #30
Source File: PigJrubyLibrary.java From spork with Apache License 2.0 | 2 votes |
/** * A type specific conversion routine. * * @param rbObject object to convert * @return analogous Pig type */ public static String rubyToPig(RubyString rbObject) { return rbObject.toString(); }