rJava .jcall return type issue - rjava

I am facing an issue with returning any type of array with .jcall(). Here is my code.
public class Test(){
public static double[] sample(){
double[] nobjarr = new double[5]
nobjarr[0] = 1.0;
nobjarr[1] = 1.0;
nobjarr[2] = 1.0;
nobjarr[3] = 1.0;
nobjarr[4] = 1.0;
return nobjarr;
}
}
In R, I am calling using .jcall
library(rJava)
.jinit()
.jaddClassPath("path to .class file")
objT <- .jnew("Test")
res <- .jcall(objT,"[D","sample")
For this I get an error saying "Error in .jcall(objT, "[D", "sample") :method sample with signature ()[D not found"

Have you tried something like this:
Test <- J( "Test" )
Test$sample()
This uses the reflection based API that is in rJava for several years now and is much more convenient than the low level .jnew, .jcall interface.

I don't know rJava, but it looks like you were telling the library to look for an instance method when the method is actually static. Check the documentation to see what the first argument to jcall should be for a static method.

Related

Junit for generateToken() method for JWT in Springboot

public String generateToken(final String id) {
Claims claims = Jwts.claims().setSubject(id);
long nowMillis = System.currentTimeMillis();
long expMillis = nowMillis + tokenValidity;
Date exp = new Date(expMillis);
return Jwts.builder().setClaims(claims).setIssuedAt(new Date(nowMillis)).setExpiration(exp)
.signWith(SignatureAlgorithm.HS512, jwtSecret).compact();
}
Now I want to write JUnit for this method and I am trying like below, but I am getting error
#Test
#Order(1)
public void test_generateToken() throws JwtTokenMalformedException, JwtTokenMissingException {
final String subject_id = "123456789";
final Long tokenValidity = 180000L;
final String jwtSecret = "jwtSecret";
when(Jwts.claims().setSubject(subject_id)).thenReturn(new DefaultClaims()); //** line no: 10
when(Jwts.builder().setClaims(claims).setIssuedAt(new Date(nowMillis)).setExpiration(exp)
.signWith(SignatureAlgorithm.HS512, jwtSecret).compact()).thenReturn(new String());
}
getting error at line number 10:
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other > object.
Two problems need to be solved in your code: mocking static methods and multiple chained calls on a mocked object. Please, find the code with inline comments below as well as some references for further reading. Important note: mockito-inline should be used (see docs links below).
void test_generateToken() {
var tested = new TestedClass();
var jwtSecret = "jwtSecret";
var claims = new DefaultClaims();
var mockedValue = "mocked value";
var builder = mock(Jwts.JwtsBuilder.class, RETURNS_DEEP_STUBS);
try (var mockedStatic = mockStatic(Jwts.class)) {
// to mock static methods the object returned from the mockStatic method should be used
mockedStatic.when(Jwts::claims)
.thenReturn(claims);
mockedStatic.when(Jwts::builder)
.thenReturn(builder);
// here we're not mocking static methods, so a standard when method is used
// thanks to RETURNS_DEEP_STUBS we can mock a chain of method calls
when(builder.setClaims(claims)
// other argument matchers like argThat() can be used here
.setIssuedAt(any())
.setExpiration(any())
.signWith(SignatureAlgorithm.HS512, jwtSecret)
.compact())
.thenReturn(mockedValue);
var result = tested.generateToken("value");
assertEquals(mockedValue, result);
}
}
mockStatic method docs
example of static mocking from the docs
RETURNS_DEEP_STUBS docs
ArgumentMatchers docs (see: any(), argThat())
mockito-inline docs
I've created a commit in a GitHub repository, where you can find the code above as well as mockito-inline dependency reference and a few fake classes representing the missing code from your question (which is not important as it's all mocked). The test shown in the example passes.

JDK8 type inference issue

I'm trying to run the following code which is compiled fine under JDK8 thanks to type inference:
public static <A,B> B convert(A a) {
return (B) new CB();
}
public static void main(String[] args) {
CA a = new CA();
CB b = convert(a); //this runs fine
List<CB> bl = Arrays.asList(b); //this also runs fine
List<CB> bl1 = Arrays.asList(convert(a)); //ClassCastException here
}
However, running this throws ClassCastException: CB cannot be cast to [Ljava.lang.Object, but the CB b = convert(a) works fine.
Any idea why?
Whenever you create a generic method with a signature that promises to return whatever the caller wishes, you are asking for trouble. You should have got an “unchecked” warning from the compiler which basically means: unexpected ClassCastExceptions may occur.
You expect the compiler to infer
List<CB> bl1 = Arrays.asList(YourClass.<CA,CB>convert(a));
whereas the compiler actually inferred
List<CB> bl1 = Arrays.asList(YourClass.<CA,CB[]>convert(a));
as far as I know, because it prefers method invocations not requiring a varargs packaging (which is compatible with pre-varargs code).
This fails because your convert method does not return the expected array type.

control p5 slider.setRange() not found in subclass

Im trying to set the Range of a slider within a subclass, catching the respective controller using getController, which works fine, proven by the returned value i get within the print. But controller.setRange() doesnt get recognized as a function.
can the range only be initialized during the creation of the object or does getController return a different object than i expect it does?
thanks!
class Stepper
{
String stepperName = "default";
int ID = motorID;
int stepperValue;
Stepper(String givenName) {
stepperName = givenName;
cp5.addSlider(stepperName)
.setPosition(sliderPosX+(sliderWidth+100)*surgeonBotID, sliderPosY+90*servoList.length+30*(motorID-servoList.length))
.setSize(sliderWidth, int(sliderHeight*0.5))
//.setRange(0, 179)
.setSliderMode(Slider.FLEXIBLE);
println("Created new Stepper: "+stepperName+ " ID: "+ID);
motorID++;
}
void setRange(float min, float max){
println("object: "+cp5.getController(getStepperName()).getValue());
cp5.getController(getStepperName()).setRange(min, max);
}
...
}
Questions like these are best answered by consulting the API.
The getController() method returns a Controller. The Controller class does not have a setRange() function. That instance happens to be an instance of Slider, which is a subclass of Controller, but the compiler has no way of knowing that. That's what's causing your error.
You can tell the compiler that the instance is indeed a Slider by casting the returned value to a Slider, and then you can access the methods defined by the Slider class:
((Slider)cp5.getController(getStepperName())).setRange(min, max);
To make that easier to understand, here it is split up into two lines:
Slider s = (Slider)cp5.getController(getStepperName());
s.setRange(min, max);

Conditional get in Spring framework

I am trying to learn Scala using Spring framework. I have to implement conditional get logic in my code. I understand it could be done using etag or Last-Modified option.
Here is my piece of code:
var lastModifiedTime: Long = _;
#RequestMapping(value= Array("/users/{id}"),method=Array(RequestMethod.GET),headers = Array("Content-Type=application/json"))
#ResponseBody
def getmeth(request: User_details, web: WebRequest): User_details = {
if (web.checkNotModified(lastModifiedTime)) {
return null
} else {
lastModifiedTime = System.currentTimeMillis()
}
Could you please help me to fix this code?
Disclaimer: I don't know Spring Web.
But according to the documentation fist of all you should take action if request is modified so you should remove bang (!) from condition. Also lastModifiedTime should be computed from the outside of the getmeth method.
Notice that unlike in Java if statement is an expression and it returns value so you shouldn't use return statement.
As it was said in comment conditional code can be easy and safely done using Scala's Option. In Scala you should always avoid null, as it is hard to distinguish it from incorrect behavior of your code, and it is very easy to forget or don't know that it is required to write logic dealing with it - you must always read the javadoc (assuming it exists and it is up to date). When you use Option type compiler will force you to deal with "nullability".
def getmeth(request: User_details, web: WebRequest): Option[User_details] =
if (web.checkNotModified(lastModifiedTime)) {
None
} else {
val userDetails = yourLogic()
Some(userDetails)
}
Then you can perform an action when option is a Some instance. To do that you can use map method.
getmeth(req, web) map { userDetails =>
userDetails.getName
}
EDIT: #optimus Now when you gave wider scope I see that your method signature is forced by framework and yon can't wrap your value with Option. I think that your problem may be that you update lastModifiedTime on every request so it seems reasonable to me that checkNotModified is always false. I think that you should use that feature only on requests that not always update checkNotModified to current time. It becomes pointless otherwise.
Update lastModifiedTime once your resource has become outdated.
#ResponseStatus(HttpStatus.OK)
#RequestMapping(value = Array("/users/{user_id}"),method = Array(RequestMethod.GET))
def getUser(#PathVariable("user_id") user_id: String,
#Context req : Request ): Any = {
val u = hm.get(user_id).asInstanceOf[User]
val tag = u.hashCode().asInstanceOf[EntityTag]
if (req.getMethod().equals("GET")) {
val rb : Response.ResponseBuilder = req.evaluatePreconditions(tag);
if (rb != null)
{
rb
}
else
{
// val u = hm.get(user_id).asInstanceOf[User]
u
}
}

Key Input using GtkD

I'm a beginner of both gtk and GtkD.
Now, I'm trying to get input from keyboard with reference to this .
But, It seems that three years have made some changes in Toolkits.
I wrote code below. However, I got strange values of ev in callback function.
I could not see any prospect of resolution with going alone.
So, could you show me where to modify?
I appreciate you in advance, and also your patient with my poor English.
I'm using gtkD-2.1.1 and gtk+3.2.3.
this is the full code:
import std.stdio;
import gtkc.gdktypes;
import gtk.MainWindow;
import gtk.Widget;
import gdk.Event;
import gtk.Main;
class Window : MainWindow{
immutable width = 200;
immutable height = 200;
this(){
super("input test");
setDefaultSize(width,height);
setEvents(EventMask.KEY_PRESS_MASK); // Actually I don't know how this works
auto callback_func = cast(bool delegate(Event,Widget))&get_key; // I doubt this cast
this.addOnKeyPress(callback_func);
showAll();
}
bool get_key(GdkEventKey* ev, Widget widget){
writefln("sender %s", widget);
writefln("type %x",ev.type);
writefln("window* %x",ev.window);
writefln("send_event %x",ev.sendEvent);
writefln("time %x",ev.time);
writefln("state %x",ev.state);
writefln("keyval %x",ev.keyval);
writefln("length %x",ev.length);
writefln("gchar* %x",ev.string);
writefln("hardware_keycode %x",ev.hardwareKeycode);
writefln("group %x",ev.group);
writefln("is_modifier %x\n",ev.bitfield0);
return true;
}
}
void main(string[] args){
Main.init(args);
auto win = new Window();
Main.run();
}
Yes, that cast is wrong. I guess that Signature with GdkEventKey* is outdated. Change your get_key to take an Event and you should get proper results:
...
auto call = &get_key;
...
bool get_key(Event e, Widget widget){
GdkEventKey* ev = e.key();
...
I have never done anything with GtkD, and this is just the result of some glances over the docs. So, it's probably not best practice, but it should get you back on the road.

Resources