JRuby issues creating Java type cast float array - jruby

I'm using jruby-9.2.6.0 to import a Java pdf library. PDColor is a class that becomes instantiated with an array of floats as well as a string constant. The Java example code that I'm referencing looks like the following:
import org.apache.pdfbox.pdmodel.graphics.color.PDColor;
PDColor componentColor = new PDColor(new float[]{1, 0, 0}, PDDeviceRGB.INSTANCE);
In jruby, my code looks like the following:
import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB;
float_arr = [1.to_f, 0.to_f, 0.to_f]
componentColor = PDColor.new(float_arr, PDDeviceRGB::INSTANCE)
The issue is, it seems that the float_arr param is not typed as a float array, and thus we get the following error:
NameError (no constructor for arguments (org.jruby.RubyArray,org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB) on Java::OrgApachePdfboxPdmodelGraphicsColor::PDColor)
available overloads:
(org.apache.pdfbox.cos.COSArray,org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace)
(org.apache.pdfbox.cos.COSName,org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace)
(float[],org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace)
Is there a known way in jruby to convert a Ruby array of floats into a Java float array?

As mentioned by #TilmanHausherr, the constructor expects a Java array of primitive floats. To create it, you can call Array#to_java(:float).
Here's a small program to test this behavior. pdfbox-2.0.15.jar should be in the same folder as the script, which should be run with jruby:
require './pdfbox-2.0.15.jar'
java_import 'org.apache.pdfbox.pdmodel.graphics.color.PDColor'
java_import 'org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB'
red = PDColor.new([1.0, 0, 0].to_java(:float), PDDeviceRGB::INSTANCE)
puts red
#=> PDColor{components=[1.0, 0.0, 0.0], patternName=null}

Related

Scala Mock: MockFunction0-1() once (never called - UNSATISFIED)

I'm working on a scala object in order to perform some testing
My start object is as follows
object obj1 {
def readvalue : IO[Float] = IO{
scala.io.StdIn.readFloat()
}
}
The testing should be
1- value of type FLOAT
2- should be less than 3
As we can not mock singleton objects I've used mocking functions here is what I've done.
class FileUtilitiesSpec
extends FlatSpec
with Matchers
with MockFactory
{
"value" should "be of Type Float" in {
val alpha = mockFunction[() => IO[Float]]
alpha.expects shouldBe a[IO[Float]]
}
"it" should "be less than 3" in {
val alpha = mockFunction[() => IO[Float]]
alpha.expects shouldBe <(3)
}
}
Im getting an error saying that :
MockFunction0-1() once (never called - UNSATISFIED) was not an instance of cats.effect.IO, but an instance of org.scalamock.handlers.CallHandler0
ScalaTestFailureLocation: util.FileUtilitiesSpec at (FileUtilitiesSpec.scala:16)
Expected :cats.effect.IO
Actual :org.scalamock.handlers.CallHandler0 ```
I would recommend reading the examples here as a starting point: https://scalamock.org/quick-start/
Using mock objects only makes sense if you are planning to use them in some other code, e.g. dependencies you do not want to make part of your module under test, or are beyond your control.
An example might be a database connection where you would depend on an actual system, making the code hard to test without simulating it.
The example you provided only has mocks, but no code using it, hence the error you are getting is absolutely correct. The mock expects to be used, but was not called.
The desired behaviour for a mocking library in this case is to make the test fail as the developer intended for this interaction with a mock to happen, but it was not recorded - so something is wrong.

no cloneType for Mem?

I'm wrapping a block of Mem in a fairly generic module called "bank" and instantiating it in a Vec as follows:
val rams = Vec.fill( 100 ) { Module( new bank ).io }
So far so good. I'm running into problems when I connect the signals. If I connect the vector of modules' signals directly to vectors of signals, like so:
rams(i).in := io.ins(i)
io.outs(i) := rams(i).out
...and so forth, I get no errors.
If I connect them in a non-trivial pattern, however, such as to a crossbar, I start getting a weird error that appears to refer to the Mem wrapper I call "bank":
"Parameterized Bundle class ascenium.bank$$anon$1 needs cloneType method."
This error is specifically a Chisel error. Can anybody tells me what it means and how to fix it?
I can provide source code if need be.
Errors like this can usually be addressed by adding a cloneType method to classes you define:
class MyModule extends Module
{
// Your class definition here
override def cloneType = new MyModule.asInstanceOf[this.type]
}

Custom Object Parameter Conversion and Parametarised Scenarios in jBehave

I am having a problem for which I cannot find a solution anywhere in the jBehave documentation. I have a story like this:
Given We have a JSON {boo: <boo>, foo: <foo>}.
When We get this.
Then We shall assert.
Examples:
|boo|foo|
|3|4|
And a step like this:
#Given("We have a JSON {$obj}.")
public void given(#Named("obj") final OwrObj obj) {
// Some code...
}
I also have a custom parameter converter which converts to OwrObj objects. My problem is that the converter gets a String input:
"{boo: <boo>, foo: <foo>}"
instead of:
"{boo: 3, foo: 4}".
In short, what is inside the curly brackets is seen as a parameter value.
Does anyone have any ideas on how to accomplish what I am trying to do. That is, get a custom object from a parametarised JSON structure in the story?

Serializing and unserializing case classes with lift-json

I'm attempting basic serialization/hydration with lift-json, but without success. As near as I can tell from the package readme, this should work. Help?
I'm using Scala 2.8.0 and Lift 2.2 cross-built for 2.8 with sbt ("net.liftweb" %% "lift-json" % "2.2").
import net.liftweb.json._
import net.liftweb.json.Serialization.{read, write}
implicit val formats = Serialization.formats(NoTypeHints)
case class Route(title: String)
val rt = new Route("x277a1")
val ser = write(rt)
// ser: String = {} ...
val deser = read[Route]("""{"title":"Some Title"}""")
// net.liftweb.json.MappingException: Parsed JSON values do not match with class constructor
Lift JSON's serialization does not work for case classes defined in REPL (paranamer can't find the bytecode to read the type metadata). Compile Route with scalac and then the above example works.
The same problem applies every time when the (de)serialuzed class is not on the classpath. In such case, paranamer can't read the parameter names. It is necessary to provide a custom ParameterNameReader.
Such problem applies for e.g.:
REPL (as mentioned) - unless you define the class outside the REPL and add via classpath.
Play Framework - unless you provide a simple custom ParameterNameReader (see below) or load the (de)serialized class as a Maven/Play/... dependency
Feel free to add another situation (you can edit this post).
The PlayParameterNameReader:
import net.liftweb.json.ParameterNameReader
import java.lang.reflect.Constructor
import play.classloading.enhancers.LocalvariablesNamesEnhancer
import scala.collection.JavaConversions._
object PlayParameterReader extends ParameterNameReader{
def lookupParameterNames(constructor: Constructor[_]) = LocalvariablesNamesEnhancer.lookupParameterNames(constructor)
}

how to extract from dispatch.json.JsObject

What do i need to do to extract the value for friends_count. i noticed that screen_name are already define in the Status object and case class. Do still require to extends Js or JsObject different
object TweetDetails extends Js { val friends_count = 'friends_count ? num }
and then pattern match it against each json object in the list of JsObjects as represented below. The symbols are confusing:
scala> val friends_count = 'friends_count ! num // I wish SO understood Scala's symbols
val twtJsonList = http(Status("username").timeline)
twtJsonList foreach {
js =>
val Status.user.screen_name(screen_name) = js
val Status.text(text) = js
val friends_counts(friends_count) = js //i cannot figure out how to extract this
println(friends_count)
println(screen_name)
println(text)
}
Normally, Scala symbols can be thought of as a unique identifier which will always be the same. Every symbol that is lexi-graphically identical refers to the exact same memory space. There's nothing else that's special about them from Scala's point of view.
However, Dispatch-Json pimps out symbols making them JSON property extractors. To see the code which is responsible for the pimping, check out the SymOp class and the rest of the JsonExtractor.scala code.
Let's write some code which solves the problem you are looking at and then analyze what's going on:
trait ExtUserProps extends UserProps with Js {
val friends_count = 'friends_count ! num
}
object ExtUser extends ExtUserProps with Js
val good_stuff = for {
item <- http(Status("username").timeline)
msg = Status.text(item)
user = Status.user(item)
screen_name = ExtUser.screen_name(user)
friend_count = ExtUser.friends_count(user)
} yield (screen_name, msg, friend_count)
The first thing that we're doing is extending the UserProps trait in the Dispatch-Twitter module to give it a friends_count extractor and then defining a ExtUser object which we can use to get access to that extractor. Because the ExtUserProps extends UserProps, which also extends Js, we get the method sym_add_operators in scope which turns our symbol 'friends_count into a SymOp case class. We then call the ! method on that SymOp which we then pass the Extractor num to, which creates an Extractor that looks for a property "friends_count" on a JSON object and then parses it as a number before returning. Quite a bit going on there for such a small bit of code.
The next part of the program is just a for-comprehension that calls out to the Twitter timeline for a user and parses it into JsObjects which represent each status item, them we apply the Status.text extractor to pull out the status message. Then we do the same to pull out the user. We then pull the screen_name and friend_count out of the user JsObject and finally we yield a Tuple3 back with all of the properties we were looking for. We're then left with a List[Tuple3[String,String,BigDecimal]] which you could then iterate on to print out or do whatever with.
I hope that clears some things up. The Dispatch library is very expressive but can be a little tough to wrap your head around as it uses a lot of Scala tricks which someone just learning Scala won't get right away. But keep plugging around and playing with, as well as looking at the tests and source code, and you'll see how to create powerful DSL's using Scala.