I have a very simple generic for loop that is causing problems when I attempt to build the project using gradle:
for(TaskAttribute taskAttribute:task.getAttributes())
{
...
}
Task.java
protected final Set<TaskAttribute> attributes = new HashSet<TaskAttribute>();
public Set<TaskAttribute> getAttributes(){return(attributes);}
The error I am getting is that the for loop is getting Object, but requries TaskAttribute. I have my sourceCompatibility set to 1.6. Am I missing something else?
In groovy you can do for loops one of two ways.
task forLoopTest {
// print numbers 8 to 19 inclusive
for (x in 8..19) {
println 'this is run '+x
}
// print numbers 0 to 4
println 'now some groovy'
for(int i = 0;i<5;i++) {
println i
}
}
Run on CLI:
$ gradle forLoopTest
This should out put.
this is run 8
this is run 9
this is run 10
this is run 11
this is run 12
this is run 13
this is run 14
this is run 15
this is run 16
this is run 17
this is run 18
this is run 19
0
1
2
3
4
The basic set up for the enhanced for loop is :
for(<Object_Type> <Object_Name> : <Collection_Name>)
I am not sure what task.getAttributes() returns or what task is, but if you have a Collection( a Set) called attributes you should just change your loop to this:
for(TaskAttribute taskAttribute : attributes)
{
...
}
Note: Since this is a private Set you may be trying to use this from another class, so getAttributes() might be returning a reference to the Set object. In which case my answer may not be useful.
Your code looks fine. Make sure you clean the project and rerun.
What is likely happening is that the type of task is a raw type, of a class that is generic (i.e. it can be parameterized but you didn't parameterize it). If this is the case, I know that logically it shouldn't make a difference on the result of the getAttributes() method; but using raw types "turns off" generics and so it says getAttributes() returns just Set, without its parameter, which causes things you get out of it to be Object.
Related
What am I doing?
I am writing a data analysis program in Java which relies on R´s arulesViz library to mine association rules.
What do I want?
My purpose is to store the rules in a String variable in Java so that I can process them later.
How does it work?
The code works using a combination of String.format and eval Java and RJava instructions respectively, being its behavior summarized as:
Given properly formatted Java data structures, creates a data frame in R.
Formats the recently created data frame into a transaction list using the arules library.
Runs the apriori algorithm with the transaction list and some necessary values passed as parameter.
Reorders the generated association rules.
Given that the association rules cannot be printed, they are written to the standard output with R´s write method, capture the output and store it in a variable. We have converted the association rules into a string variable.
We return the string.
The code is the following:
// Step 1
Rutils.rengine.eval("dataFrame <- data.frame(as.factor(c(\"Red\", \"Blue\", \"Yellow\", \"Blue\", \"Yellow\")), as.factor(c(\"Big\", \"Small\", \"Small\", \"Big\", \"Tiny\")), as.factor(c(\"Heavy\", \"Light\", \"Light\", \"Heavy\", \"Heavy\")))");
//Step 2
Rutils.rengine.eval("transList <- as(dataFrame, 'transactions')");
//Step 3
Rutils.rengine.eval(String.format("info <- apriori(transList, parameter = list(supp = %f, conf = %f, maxlen = 2))", supportThreshold, confidenceThreshold));
// Step 4
Rutils.rengine.eval("orderedRules <- sort(info, by = c('count', 'lift'), order = FALSE)");
// Step 5
REXP res = Rutils.rengine.eval("rulesAsString <- paste(capture.output(write(orderedRules, file = stdout(), sep = ',', quote = TRUE, row.names = FALSE, col.names = FALSE)), collapse='\n')");
// Step 6
return res.asString().replaceAll("'", "");
What´s wrong?
Running the code in Linux Will work perfectly, but when I try to run it in Windows, I get the following error referring to the return line:
Exception in thread "main" java.lang.NullPointerException
This is a common error I have whenever the R code generates a null result and passes it to Java. There´s no way to syntax check the R code inside Java, so whenever it´s wrong, this error message appears.
However, when I run the R code in brackets in the R command line in Windows, it works flawlessly, so both the syntax and the data flow are OK.
Technical information
In Linux, I am using R with OpenJDK 10.
In Windows, I am currently using Oracle´s latest JDK release, but trying to run the program with OpenJDK 12 for Windows does not solve anything.
Everything is 64 bits.
The IDE used in both operating systems is IntelliJ IDEA 2019.
Screenshots
Linux run configuration:
Windows run configuration:
When I call eval (in strict mode) on a nashorn engine with the following script I get an exception:
var yfunc = function () {
(null).apply(null, arguments);
};
yfunc();
I've truncated my personal situation heavily. The "(null)" on line 2 can be replaced with anything between parenthesis or a local variable, either way just something that shouldn't throw a compile error, and it will yield the same result.
The issue seems to be explicitly that "arguments" is passed directly as the second argument of calling a method called "apply". Any of the following changes will undo the thrown exception:
Putting "arguments" in a variable first (but simply wrapping it in parenthesis doesn't work!)
Calling something other than apply
Passing "arguments" in a different argument slot when calling apply
Calling print() (with or without passing any arguments) as a preceding line of code inside yfunc() (weird huh?)
Defining more than 0 parameters for yfunc()
Binding yfunc first and then calling the bound method
Calling yfunc via Function.apply (not so much with Function.call!)
The Exception thrown is this:
Exception in thread "main" java.lang.ClassCastException: Cannot cast jdk.nashorn.internal.runtime.Undefined to jdk.nashorn.internal.runtime.ScriptFunction
at java.lang.invoke.MethodHandleImpl.newClassCastException(MethodHandleImpl.java:361)
at java.lang.invoke.MethodHandleImpl.castReference(MethodHandleImpl.java:356)
at jdk.nashorn.internal.scripts.Script$\^eval\_.:program(<eval>:4)
at jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:637)
at jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:494)
at jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:393)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:449)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:406)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:402)
at jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:155)
at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264)
When I call this method with an owner, the exception thrown changes. Example code:
var yfunc = {
method: function () {
(null).apply(null, arguments);
}
};
var x = yfunc.method();
Then the thrown exception looks like this:
Exception in thread "main" java.lang.ClassCastException: Cannot cast jdk.nashorn.internal.scripts.JO4 to jdk.nashorn.internal.runtime.ScriptFunction
at java.lang.invoke.MethodHandleImpl.newClassCastException(MethodHandleImpl.java:361)
at java.lang.invoke.MethodHandleImpl.castReference(MethodHandleImpl.java:356)
at jdk.nashorn.internal.scripts.Script$\^eval\_.:program(<eval>:5)
at jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:637)
at jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:494)
at jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:393)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:449)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:406)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:402)
at jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:155)
at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264)
I've reproduced the issue so far on specifically these environments:
windows 7 64bit -> jdk 1.8.0_60 64bit
windows 8 64bit -> jdk 1.8.0_131 64bit
I can't seem to find anything on the internet about similar issues. Do I need to report this to Oracle/OpenJDK?
Minor update
Added items 6 and 7 to list of "following changes will undo the thrown exception".
Final update
Bug filed: JDK-8184720
Yes, it appears to be a bug. Please file a bug.
With reference to my previous question,
Executing a lisp function from Java
I was able to call lisp code from Java using ABCL.
But the problem is, the already existing lisp code uses CL-PPCRE package.
I can not compile the code as it says 'CL-PPCRE not found'.
I have tried different approaches to add that package,
including
1) how does one compile a clisp program which uses cl-ppcre?
2)https://groups.google.com/forum/#!topic/cl-ppcre/juSfOhEDa1k
Doesnot work!
Other thing is, that executing (compile-file aima.asd) works perfectly fine although it does also require cl-pprce
(defpackage #:aima-asd
(:use :cl :asdf))
(in-package :aima-asd)
(defsystem aima
:name "aima"
:version "0.1"
:components ((:file "defpackage")
(:file "main" :depends-on ("defpackage")))
:depends-on (:cl-ppcre))
The final java code is
interpreter.eval("(load \"aima/asdf.lisp\")");
interpreter.eval("(compile-file \"aima/aima.asd\")");
interpreter.eval("(compile-file \"aima/defpackage.lisp\")");
interpreter.eval("(in-package :aima)");
interpreter.eval("(load \"aima/aima.lisp\")");
interpreter.eval("(aima-load 'all)");
The error message is
Error loading C:/Users/Administrator.NUIG-1Z7HN12/workspace/aima/probability/domains/edit-nets.lisp at line 376 (offset 16389)
#<THREAD "main" {3A188AF2}>: Debugger invoked on condition of type READER-ERROR
The package "CL-PPCRE" can't be found.
[1] AIMA(1):
Can anyone help me?
You need to load cl-ppcre before you can use it. You can do that by using (asdf:load-system :aima), provided that you put both aima and cl-ppcre into locations that your ASDF searches.
I used QuickLisp to add cl-ppcre (because nothing else worked for me).
Here is what I did
(load \"~/QuickLisp.lisp\")")
(quicklisp-quickstart:install)
(load "~/quicklisp/setup.lisp")
(ql:quickload :cl-ppcre)
First 2 lines are only a one time things. Once quickLisp is installed you can start from line 3.
I'm trying to track down the source of an EOFException in some client/server code, but many of the classes used only have methods which say that they throw an IOException, not specifically an EOFException. Normally I'd just look at the stack trace but I don't have it and can't reproduce it. So, it would be helpful to have a list of every class which has methods which throw EOFException specifically, but I don't know how to find out this information.
Is there a source of information on every (standard) Java class (in SE 7, in my case) which has methods which throw EOFException? I have tried reading the Javadocs on EOFException to no avail.
(I have found, at least, that DataInput does mentionEOFException. But are there any more?)
Afterword: Since it seems the only way to find out is to inspect the source code, here is the result of me searching for "EOFException" in the extracted source code (1.7.0_45).
EDIT: Added results for 7.51, for all source code in the JDK, at the bottom.
In Java 6.17, here are all classes that explicitly throw java.io.EOFException. Specifically, it is the number of times new\s+EOFException was found in each source-code file.
java.io.DataInputStream.java: 8
java.io.ObjectInputStream.java: 6
java.io.RandomAccessFile.java: 8
java.util.zip.GZIPInputStream.java: 2
java.util.zip.InflaterInputStream.java: 1
java.util.zip.ZipFile.java: 1
java.util.zip.ZipInputStream.java: 1
Here is another bit of information: All source-code files containing catch\s*\(\s*EOFException:
java.io.ObjectInputStream.java: 1
java.util.zip.ZipInputStream.java: 1
Note that there are no standard java.* Exception classes that extend EOFException (there are no occurances of
extends\s+([a-z]+\.)*EOFException
anywhere in the java.* source-code).
This is a limited but valuable starting point. As mentioned by others, there may be situations that this misses--when all you have is the source-code to work from, it will be time-consuming to find them. Hopefully this information will set you down the right path.
Here are the results for Java 7.51, for all source-code provided with the JDK:
extends\s+([a-z]+\.)*EOFException
none
catch\s*\(\s*EOFException
com.sun.imageio.plugins.gif.GIFImageReader: 1
com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl: 1
com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl: 4
com.sun.org.apache.xerces.internal.impl.XMLVersionDetector: 1
com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDLoader: 2
java.io.ObjectInputStream: 1
java.util.zip.ZipInputStream: 1
new\s+EOFException
com.sun.corba.se.impl.io.IIOPInputStream: 1
com.sun.imageio.plugins.png.PNGImageReader: 1
com.sun.org.apache.xerces.internal.impl.XMLDTDScannerImpl: 1
com.sun.org.apache.xerces.internal.impl.XMLEntityManager: 1
com.sun.org.apache.xerces.internal.impl.XMLEntityScanner: 1
java.io.DataInputStream: 8
java.io.ObjectInputStream: 6
java.io.RandomAccessFile: 8
java.util.zip.GZIPInputStream: 2
java.util.zip.InflaterInputStream: 1
java.util.zip.ZipFile: 1
java.util.zip.ZipInputStream: 1
javax.imageio.stream.ImageInputStreamImpl: 8
You can find that out only under the assumption that the code creates and immediately throws an EOFException. But the follwoing could also throw an EOFException:
class Foo {
...
public void iAmHarmless(Exception x) { if (x != null) throw x; }
...
}
Or how about the follwoing, to defeat aliteralminds method:
class XYException extends EOFException { ... }
class Foo {
public void surprise() { throw new XYException().super(); }
}
Joking aside - methods from many classes may throw EOFException simply because of inheritance. A grep for "EOFException" gives only the very base classes. But you must consider all subclasses thereof. Example: java.util.jar.JarInputStream
I'm implementing a Web-based Groovy code editor and need to check the code for syntax errors. The Java implementation below works OK but the resulting message contains some undesired elements (in bold). I'm looking for a way to list warnings and errors individually.
I'm using this maven dependency: groovy-all 2.1.1
try {
new GroovyShell().parse(groovyCode);
} catch(CompilationFailedException cfe) {
System.out.println(cfe.getMessage());
}
Output:
startup failed:
Script1.groovy: 1: unexpected token: n # line 1, column 19.
def factorial(n) n == 1 ? 1 : n * factorial(n - 1) }
^
1 error
Would not make much sense to parse the error message. Try to look into
CompilationFailedException.getUnit()
ProcessingUnit.getErrorCollector()
ErrorCollector.getWarnings() & getErrors()
EDIT
Ok, looks like unit is null on the CompilationFailedException. Try catching MultipleCompilationErrorsException instead:
try {
new GroovyShell().parse(groovyCode);
} catch(MultipleCompilationErrorsException cfe) {
ErrorCollector errorCollector = cfe.getErrorCollector();
System.out.println("Errors: "+errorCollector.getErrorCount());
}
Btw, take a look at the ErrorCollector sources, you might find write method useful to output the info about compilation errors.