What does OrientDB OCommandRequest.execute() return? - orientdb

I'm working on some Java code to interact with OrientDB graphs. Currently I'm looking at the interface for OCommandRequest. The method execute() can return something different based on the query that we run... but I'm not sure what is possible from it.
I have looked at the code, but I'm somehwhat new to Java. So far I see that OCommandRequest is an interface but that's about as far as I've gone pulling the thread in the code.
I haven't found a lot in the OrientDB Documentation that has helped me to know what return types are possible and what the values mean when they get returned.
I played with some examples on my end based on some of the examples I found at massapi. Sometimes it returns an Integer, other times a Boolean, and yet other times I've gotten back an Iterable.
My question is: Is there some documentation available that characterizes what OCommandRequest.execute() returns and why? Ideally some formatted docs are nice, but pointers into the code to find where the interface is being implemented would also be helpful and allow me to pull the thread a little bit more.
For now, I'm emulating one of the examples from the massapi site I linked earlier (but I'm not sure if this is really considered the blessed way to handle responses from queries):
OCommandRequest command = graph.command(new OCommandSQL(query));
Object result = command.execute();
if( result instanceof Integer ) {
// do stuff if an integer was returned
} else if( result instanceof Boolean ) {
// do stuff if a boolean was returned
} else if( result instanceof Iterable<OrientVertex> ) {
// do stuff if an iterable list of vertices was returned
} else {
// any other types?
}
Any pointers that someone can give are definitely useful.
Thanks!

There is no documentation about that, it depends on SQL command you execute.
To know the return type you have to refer directly to their own class. For eg. DROP CLASS returns Boolean, and so on.
Anyway you can use this code to see the return type:
OCommandRequest command = g.command(new OCommandSQL(q));
Object result = command.execute();
System.out.println(q+"\n"+result.getClass().toString()+"\n");

Related

Swift - understanding return types in recursion: when should return the function vs. just return on its own

This may be a little too general for this forum, but hoping someone can explain this in a way that makes sense to my brain. I've tried reading and researching and have found lots of examples - but I still don't understand the "why" which means that I am not understanding exactly how a program comes back from a function return.
Here is a very simple function I wrote that solves a puzzle using backwards recursion. It works well.
func solver(grid: [[Int]])->[[Int]] {
var returnGrid = constraintPropogation(grid: grid)
if contradictionCheck(grid: returnGrid) == false {
return returnGrid
} else {
if returnGrid.flatMap({$0}).filter({$0 == 3}).count == 0 {
print("SOLVED**********")
gridPrint(grid: returnGrid)
print()
stopFlag = true
stopAnswer = returnGrid
return returnGrid
} else {
let randStart = getRandomStart(grid: returnGrid)
returnGrid[randStart.x][randStart.y] = 0
solver(grid: returnGrid)
returnGrid[randStart.x][randStart.y] = 1
solver(grid: returnGrid)
}
}
if stopFlag == true {return stopAnswer}
return solver(grid: returnGrid)
}
My issue is understanding the returns. In the third line of the function if a contradiction check fails this means that we've gone down a path that would not be possible. Therefore we return. That makes sense. The second return in the middle of the function occurs when the puzzle is solved, so it makes sense to return there. But the last one at the end "return solver(grid: returnGrid)" is challenging to my understanding. Here we are returning but also calling this same function again. This is not going deeper into the potential solution path (that happens in the "else" section where the function is called). Why do we need to call the function again rather than just returning? What is happening under the hood? Does the return happen first where we "pop back up a level" and then we are calling the function again effectively one rung higher on the stack? When I write these words I realize that I have a vague understanding - but somehow it is not all clicking together for me.
Am at the point now that when I'm writing functions that involve recursion I just try both returning on own or returning and calling function again to see which one achieves what I want. But I'd really like to understand it rather than just guessing. If anyone had a simple explanation I would appreciate it.
Your function solver takes an array of arrays, and returns an array of arrays. Any call to return(something) returns that something to the caller.
Saying return(someArrayOfArrays) means you are done, and have a result.
Saying return(solver(someArrayOfArrays)) says "call this function again, passing in a new value. Return whatever the result is as the function result." The current call to solver() is done doing work, and passes its intermediate results to another call to the function. That's the recursion. You can think of this as nesting a function call inside a function call inside a function call, or stacking function calls on top of each other.
The call to solver(grid: returnGrid) does not make any sense. That is a recursive call, but you ignore the result. Thus, that call does nothing useful. If your remove that line, it won't make any difference to the outcome. That line is saying "Go do a bunch of work and find an answer for me, but I will throw away your answer". The compiler should give you a "function result ignored" warning at that line.
Beyond that, I can't tell what your code is doing. It appears to be modifying at least one global variable, "stopAnswer". That suggests it's not a pure recursive function.

Breaking when a method returns null in the Eclipse debugger

I'm working on an expression evaluator. There is an evaluate() function which is called many times depending on the complexity of the expression processed.
I need to break and investigate when this method returns null. There are many paths and return statements.
It is possible to break on exit method event but I can't find how to put a condition about the value returned.
I got stuck in that frustration too. One can inspect (and write conditions) on named variables, but not on something unnamed like a return value. Here are some ideas (for whoever might be interested):
One could include something like evaluate() == null in the breakpoint's condition. Tests performed (Eclipse 4.4) show that in such a case, the function will be performed again for the breakpoint purposes, but this time with the breakpoint disabled. So you will avoid a stack overflow situation, at least. Whether this would be useful, depends on the nature of the function under consideration - will it return the same value at breakpoint time as at run time? (Some s[a|i]mple code to test:)
class TestBreakpoint {
int counter = 0;
boolean eval() { /* <== breakpoint here, [x]on exit, [x]condition: eval()==false */
System.out.println("Iteration " + ++counter);
return true;
}
public static void main(String[] args) {
TestBreakpoint app = new TestBreakpoint();
System.out.println("STARTED");
app.eval();
System.out.println("STOPPED");
}
}
// RESULTS:
// Normal run: shows 1 iteration of eval()
// Debug run: shows 2 iterations of eval(), no stack overflow, no stop on breakpoint
Another way to make it easier (to potentially do debugging in future) would be to have coding conventions (or personal coding style) that require one to declare a local variable that is set inside the function, and returned only once at the end. E.g.:
public MyType evaluate() {
MyType result = null;
if (conditionA) result = new MyType('A');
else if (conditionB) result = new MyType ('B');
return result;
}
Then you can at least do an exit breakpoint with a condition like result == null. However, I agree that this is unnecessarily verbose for simple functions, is a bit contrary to flow that the language allows, and can only be enforced manually. (Personally, I do use this convention sometimes for more complex functions (the name result 'reserved' just for this use), where it may make things clearer, but not for simple functions. But it's difficult to draw the line; just this morning had to step through a simple function to see which of 3 possible cases was the one fired. For today's complex systems, one wants to avoid stepping.)
Barring the above, you would need to modify your code on a case by case basis as in the previous point for the single function to assign your return value to some variable, which you can test. If some work policy disallows you to make such non-functional changes, one is quite stuck... It is of course also possible that such a rewrite could result in a bug inadvertently being resolved, if the original code was a bit convoluted, so beware of reverting to the original after debugging, only to find that the bug is now back.
You didn't say what language you were working in. If it's Java or C++ you can set a condition on a Method (or Function) breakpoint using the breakpoint properties. Here are images showing both cases.
In the Java example you would unclik Entry and put a check in Exit.
Java Method Breakpoint Properties Dialog
!
C++ Function Breakpoint Properties Dialog
This is not yet supported by the Eclipse debugger and added as an enhancement request. I'd appreciate if you vote for it.
https://bugs.eclipse.org/bugs/show_bug.cgi?id=425744

Scala proper use of break to return

I have the following code:
private def hasRole(role: String): Boolean = {
var hasRole = false;
if(getUserDetails.isDefined){
// getAuthorities returns java.util.Collection<GrantedAuthority>
val authorities: util.Collection[_ <:GrantedAuthority] = getUserDetails.get.getAuthorities
// Wrap the collection is a Scala class
val authoritiesWrapper = JCollectionWrapper.apply(authorities);
for(authority <- authoritiesWrapper.iterator){
if(authority.getAuthority == role){
hasRole = true;
scala.util.control.Breaks.break
}
}
}
hasRole
}
The question is, is scala.util.control.Breaks.break the correct way toreturn when I've found the role? Doesn't look right to me.
If you want to use breakable, you need to do it like so:
import scala.util.control.Breaks._
breakable {
for (i <- 0 to 10000) { if (i>3) break }
}
But if you find yourself doing that often, you're probably not using the collections library to its full extent. Try instead
authoritiesWrapper.iterator.exists(_.getAuthority == role)
Also, in the example you gave, you could also
if (authority.getAuthority == role) return true
When to choose which? In general, you should use the control-flow options in the collections library if you can. They generally are the fastest and clearest. Wait, fastest--why is that? Both break and return (from within a for or other context that requires a closure--basically anything but if and while and match) actually throw a stackless exception which is caught; in the break case it's caught by breakable and in the return case it's caught by the method. Creating a stack trace is really slow, but even stackless exceptions are kind of slow.
So using the correct collections method--exists in this case--is the best solution.
The question is, is scala.util.control.Breaks.break the correct way
toreturn when I've found the role? Doesn't look right to me.
Since your just looking for the first instance of authority.getAuthority == role you can use find which does exactly that and is the idiomatic way to do this.
authoritiesWrapper.iterator.find(authority => authority.getAuthority == role)
or more concisely
authoritiesWrapper.iterator.find(_.getAuthority == role)
These return an Option type which you can get the value of authority from if it exists.
I can only offer you generalities, but I hope it's at least a little helpful...
Unfortunately, your sample code contains free identifiers, so it's not possible for me to understand what it does without guessing and assuming.
You're thinking about the problem wrong. What is it you're doing here? You're finding a element of a collection. Use the library! It has all manner of such things off-the-shelf.
When it comes to dealing with Option[Something] the preferred approach is to map over it. If it's a None, you get a None out. If it's Some(thing) then the function you pass to map will be applied to thing and the result will be Some(what-your-function-returned-for-thing).
Alternatively, and what newcomers to Scala often find more palatable, you can use pattern matching on an Option to effectively distinguish the None case from the Some(thing) case.
When it comes to dealing with Java libraries, it's best to push the conversions from and to the Java collections to the very periphery of your code and keep the bulk of your code idiomatic Scala using native Scala collections.
The same goes for nulls coming from Java. Turn them into Option at the earliest possible time. As a convenience, the Option(thing) factory will turn a thing that is null into a None and wrap a non-null thing in a Some
Addendum
The upshot is that you really should not be using these control flow mechanisms in this code. They're all based on exceptions (other than return) and are rather at odds with Scala's emphasis on using functional programming. The library supports a clean, succinct, efficient implementation of the essetial logic you're trying for. Don't go against the grain like this.
Why not just return true and return false replacing hasRole?
Thanks Everyone, based on #Rex Kerr answer I now have this:
private def hasRole(role: String): Boolean = {
var hasRole: Boolean = false;
if(getUserDetails.isDefined){
val authorities: util.Collection[_ <:GrantedAuthority] = getUserDetails.get.getAuthorities
val authoritiesWrapper = JCollectionWrapper.apply(authorities);
hasRole = authoritiesWrapper.iterator.exists(_.getAuthority == role)
}
hasRole
}
which seems to look and feel right. I'm using exists to see of the role exists in the collection and then returning that result. By default false is returned if the user is not defined (not logged in).
Please comment if this is still not perfect.

Scala, Specs2, Mockito and null return values

I'm trying to test-drive some Scala code using Specs2 and Mockito. I'm relatively new to all three, and having difficulty with the mocked methods returning null.
In the following (transcribed with some name changes)
"My Component's process(File)" should {
"pass file to Parser" in new modules {
val file = mock[File]
myComponent.process(file)
there was one(mockParser).parse(file)
}
"pass parse result to Translator" in new modules {
val file = mock[File]
val myType1 = mock[MyType1]
mockParser.parse(file) returns (Some(myType1))
myComponent.process(file)
there was one(mockTranslator).translate(myType1)
}
}
The "pass file to Parser" works until I add the translator call in the SUT, and then dies because the mockParser.parse method has returned a null, which the translator code can't take.
Similarly, the "pass parse result to Translator" passes until I try to use the translation result in the SUT.
The real code for both of these methods can never return null, but I don't know how to tell Mockito to make the expectations return usable results.
I can of course work around this by putting null checks in the SUT, but I'd rather not, as I'm making sure to never return nulls and instead using Option, None and Some.
Pointers to a good Scala/Specs2/Mockito tutorial would be wonderful, as would a simple example of how to change a line like
there was one(mockParser).parse(file)
to make it return something that allows continued execution in the SUT when it doesn't deal with nulls.
Flailing about trying to figure this out, I have tried changing that line to
there was one(mockParser).parse(file) returns myResult
with a value for myResult that is of the type I want returned. That gave me a compile error as it expects to find a MatchResult there rather than my return type.
If it matters, I'm using Scala 2.9.0.
If you don't have seen it, you can look the mock expectation page of the specs2 documentation.
In your code, the stub should be mockParser.parse(file) returns myResult
Edited after Don's edit:
There was a misunderstanding. The way you do it in your second example is the good one and you should do exactly the same in the first test:
val file = mock[File]
val myType1 = mock[MyType1]
mockParser.parse(file) returns (Some(myType1))
myComponent.process(file)
there was one(mockParser).parse(file)
The idea of unit testing with mock is always the same: explain how your mocks work (stubbing), execute, verify.
That should answer the question, now a personal advice:
Most of the time, except if you want to verify some algorithmic behavior (stop on first success, process a list in reverse order) you should not test expectation in your unit tests.
In your example, the process method should "translate things", thus your unit tests should focus on it: mock your parsers and translators, stub them and only check the result of the whole process. It's less fine grain but the goal of a unit test is not to check every step of a method. If you want to change the implementation, you should not have to modify a bunch of unit tests that verify each line of the method.
I have managed to solve this, though there may be a better solution, so I'm going to post my own answer, but not accept it immediately.
What I needed to do was supply a sensible default return value for the mock, in the form of an org.mockito.stubbing.Answer<T> with T being the return type.
I was able to do this with the following mock setup:
val defaultParseResult = new Answer[Option[MyType1]] {
def answer(p1: InvocationOnMock): Option[MyType1] = None
}
val mockParser = org.mockito.Mockito.mock(implicitly[ClassManifest[Parser]].erasure,
defaultParseResult).asInstanceOf[Parser]
after a bit of browsing of the source for the org.specs2.mock.Mockito trait and things it calls.
And now, instead of returning null, the parse returns None when not stubbed (including when it's expected as in the first test), which allows the test to pass with this value being used in the code under test.
I will likely make a test support method hiding the mess in the mockParser assignment, and letting me do the same for various return types, as I'm going to need the same capability with several return types just in this set of tests.
I couldn't locate support for a shorter way of doing this in org.specs2.mock.Mockito, but perhaps this will inspire Eric to add such. Nice to have the author in the conversation...
Edit
On further perusal of source, it occurred to me that I should be able to just call the method
def mock[T, A](implicit m: ClassManifest[T], a: org.mockito.stubbing.Answer[A]): T = org.mockito.Mockito.mock(implicitly[ClassManifest[T]].erasure, a).asInstanceOf[T]
defined in org.specs2.mock.MockitoMocker, which was in fact the inspiration for my solution above. But I can't figure out the call. mock is rather overloaded, and all my attempts seem to end up invoking a different version and not liking my parameters.
So it looks like Eric has already included support for this, but I don't understand how to get to it.
Update
I have defined a trait containing the following:
def mock[T, A](implicit m: ClassManifest[T], default: A): T = {
org.mockito.Mockito.mock(
implicitly[ClassManifest[T]].erasure,
new Answer[A] {
def answer(p1: InvocationOnMock): A = default
}).asInstanceOf[T]
}
and now by using that trait I can setup my mock as
implicit val defaultParseResult = None
val mockParser = mock[Parser,Option[MyType1]]
I don't after all need more usages of this in this particular test, as supplying a usable value for this makes all my tests work without null checks in the code under test. But it might be needed in other tests.
I'd still be interested in how to handle this issue without adding this trait.
Without the full it's difficult to say but can you please check that the method you're trying to mock is not a final method? Because in that case Mockito won't be able to mock it and will return null.
Another piece of advice, when something doesn't work, is to rewrite the code with Mockito in a standard JUnit test. Then, if it fails, your question might be best answered by someone on the Mockito mailing list.

scala 2.8 control Exception - what is the point?

In the upcoming scala 2.8, a util.control package has been added which includes a break library and a construct for handling exceptions so that code which looks like:
type NFE = NumberFormatException
val arg = "1"
val maybeInt = try { Some(arg.toInt) } catch { case e: NFE => None }
Can be replaced with code like:
import util.control.Exception._
val maybeInt = catching(classOf[NFE]) opt arg.toInt
My question is why? What does this add to the language other than providing another (and radically different) way to express the same thing? Is there anything which can be expressed using the new control but not via try-catch? Is it a DSL supposed to make exception-handling in Scala look like some other language (and if so, which one)?
There are two ways to think about exceptions. One way is to think of them as flow control: an exception changes the flow of execution of the program, making the execution jump from one place to another. A second way is to think of them as data: an exception is an information about the execution of the program, which can then be used as input to other parts of the program.
The try/catch paradigm used in C++ and Java is very much of the first kind(*).
If, however, if you prefer to deal with exceptions as data, then you'll have to resort to code such as the one shown. For the simple case, that's rather easy. However, when it comes to the functional style where composition is king, things start to get complicated. You either have to duplicate code all around, or you roll your own library to deal with it.
Therefore, in a language which purports to support both functional and OO style, one shouldn't be surprised to see library support for treating exceptions as data.
And note that there is oh-so-many other possibilities provided by Exception to handle things. You can, for instance, chain catch handlers, much in the way that Lift chain partial functions to make it easy to delegate responsibility over the handling of web page requests.
Here is one example of what can be done, since automatic resource management is in vogue these days:
def arm[T <: java.io.Closeable,R](resource: T)(body: T => R)(handlers: Catch[R]):R = (
handlers
andFinally (ignoring(classOf[Any]) { resource.close() })
apply body(resource)
)
Which gives you a safe closing of the resource (note the use of ignoring), and still applies any catching logic you may want to use.
(*) Curiously, Forth's exception control, catch&throw, is a mix of them. The flow jumps from throw to catch, but then that information is treated as data.
EDIT
Ok, ok, I yield. I'll give an example. ONE example, and that's it! I hope this isn't too contrived, but there's no way around it. This kind of thing would be most useful in large frameworks, not in small samples.
At any rate, let's first define something to do with the resource. I decided on printing lines and returning the number of lines printed, and here is the code:
def linePrinter(lnr: java.io.LineNumberReader) = arm(lnr) { lnr =>
var lineNumber = 0
var lineText = lnr.readLine()
while (null != lineText) {
lineNumber += 1
println("%4d: %s" format (lineNumber, lineText))
lineText = lnr.readLine()
}
lineNumber
} _
Here is the type of this function:
linePrinter: (lnr: java.io.LineNumberReader)(util.control.Exception.Catch[Int]) => Int
So, arm received a generic Closeable, but I need a LineNumberReader, so when I call this function I need to pass that. What I return, however, is a function Catch[Int] => Int, which means I need to pass two parameters to linePrinter to get it to work. Let's come up with a Reader, now:
val functionText = """def linePrinter(lnr: java.io.LineNumberReader) = arm(lnr) { lnr =>
var lineNumber = 1
var lineText = lnr.readLine()
while (null != lineText) {
println("%4d: %s" format (lineNumber, lineText))
lineNumber += 1
lineText = lnr.readLine()
}
lineNumber
} _"""
val reader = new java.io.LineNumberReader(new java.io.StringReader(functionText))
So, now, let's use it. First, a simple example:
scala> linePrinter(new java.io.LineNumberReader(reader))(noCatch)
1: def linePrinter(lnr: java.io.LineNumberReader) = arm(lnr) { lnr =>
2: var lineNumber = 1
3: var lineText = lnr.readLine()
4: while (null != lineText) {
5: println("%4d: %s" format (lineNumber, lineText))
6: lineNumber += 1
7: lineText = lnr.readLine()
8: }
9: lineNumber
10: } _
res6: Int = 10
And if I try it again, I get this:
scala> linePrinter(new java.io.LineNumberReader(reader))(noCatch)
java.io.IOException: Stream closed
Now suppose I want to return 0 if any exception happens. I can do it like this:
linePrinter(new java.io.LineNumberReader(reader))(allCatch withApply (_ => 0))
What's interesting here is that I completely decoupled the exception handling (the catch part of try/catch) from the closing of the resource, which is done through finally. Also, the error handling is a value I can pass on to the function. At the very least, it makes mocking of try/catch/finally statements much easier. :-)
Also, I can combine multiple Catch using the or method, so that different layers of my code might choose to add different handlers for different exceptions. Which really is my main point, but I couldn't find an exception-rich interface (in the brief time I looked :).
I'll finish with a remark about the definition of arm I gave. It is not a good one. Particularly, I can't use Catch methods such as toEither or toOption to change the result from R to something else, which seriously decreases the value of using Catch in it. I'm not sure how to go about changing that, though.
As the guy who wrote it, the reasons are composition and encapsulation. The scala compiler (and I am betting most decent sized source bases) is littered with places which swallow all exceptions -- you can see these with -Ywarn-catches -- because the programmer is too lazy to enumerate the relevant ones, which is understandable because it's annoying. By making it possible to define, re-use, and compose catch and finally blocks independently of the try logic, I hoped to lower the barrier to writing sensible blocks.
And, it's not exactly finished, and I'm working on a million other areas too. If you look through the actors code you can see examples of huge cut-and-pasted multiply-nested try/catch/finally blocks. I was/am unwilling to settle for try { catch { try { catch { try { catch ...
My eventual plan is to have catch take an actual PartialFunction rather than require a literal list of case statements, which presents a whole new level of opportunity, i.e. try foo() catch getPF()
I'd say it's foremost a matter of style of expression.
Beyond being shorter than its equivalent, the new catching() method offers a more functional way to express the same behavior. Try ... catch statements are generally considered imperative style and exceptions are considered side-effects. Catching() puts a blanket on this imperative code to hide it from view.
More importantly, now that we have a function then it can be more easily composed with other things; it can be passed to other higher-order functions to create more sophisticated behavior. (You cannot pass a try .. catch statement with a parametrized exception type directly).
Another way to look at this is if Scala didn't offer this catching() function. Then most likely people would 're-invent' it independently and that would cause code duplication, and lead to more non-standard code. So I think the Scala designers believe this function is common enough to warrant including it in the standard Scala library. (And I agree)
alex