I am using the below code to walk a directory and fetch the first file . I am not able to fix the two sonar lint issues . Please help.
List<String> result = walk.filter(Files::isRegularFile).map(x -> x.toString()).collect(Collectors.toList());
Please make this change:
List<String> result = walk.filter(p -> p.toFile().isFile()).map(Path::toString).collect(Collectors.toList());
SonarLint also state the reason for the suggestion.
Lambdas should be replaced with method references
Java 8's "Files.exists" should not be used
Look at the 3725 Sonar rule :
The Files.exists method has noticeably poor performance in JDK 8, and
can slow an application significantly when used to check files that
don't actually exist.
The same goes for Files.notExists, Files.isDirectory and
Files.isRegularFile.
Note that this rule is automatically disabled when the project's
sonar.java.source is not 8.
Your project very probably relies on JDK/JRE 8.
If you dig into the OpenJDK issues you could see that on Linux the issue was partially solved but not on Windows.
About the second issue :
map(x -> x.toString())
Just replace it by a method reference :
map(Path::toString)
So finally to be compliant with Sonar, it gives :
//FIXME use Files::isRegularFile when update with Java>8
List<String> result = walk.filter(p -> p.toFile().exists())
.map(Path::toString)
.collect(Collectors.toList());
Related
I have below code in old version. Now I have upgraded the axis2 version from 1.1.1 to 1.6.2. It then have compile problem as indicated below. I find in the web with link: https://issues.apache.org/jira/browse/AXIS2-4363
But I do not understand it. First of all Do I need to amend code? If yes, is there any example for me to follow?
if (reader.getEventType() == javax.xml.stream.XMLStreamConstants.START_ELEMENT && reader.getName().equals(new javax.xml.namespace.QName(org.apache.axiom.om.impl.MTOMConstants.XOP_NAMESPACE_URI, org.apache.axiom.om.impl.MTOMConstants.XOP_INCLUDE)))
{
java.lang.String id = org.apache.axiom.om.util.ElementHelper.getContentID(reader, "UTF-8");
object.set_return(((org.apache.axiom.soap.impl.builder.MTOMStAXSOAPModelBuilder)
((org.apache.axiom.om.impl.llom.OMStAXWrapper)
reader).getBuilder()).getDataHandler(id));
<--- highlight this The type org.apache.axiom.om.impl.llom.OMStAXWrapper is not visible
reader.next();
reader.next();
}
This appears to be generated code. If you upgrade from Axis2 1.1.1 to 1.6.2, then you need to regenerate that code. Note that the usual best practice applies here: generated code should always be generated during the build, not checked into the source control system.
I am new to apache spark and trying to run the wordcount example . But intellij editor gives me the error at line 47 Cannot resolve method 'flatMap()' error.
Edit :
This is the line where I am getting the error
JavaRDD<String> words = lines.flatMap(s -> Arrays.asList(SPACE.split(s)).iterator());
It looks like you're using an older version of Spark that expects Iterable rather than Iterator from the flatMap() function. Try this:
JavaRDD<String> words = lines.flatMap(s -> Arrays.asList(SPACE.split(s)));
See also Spark 2.0.0 Arrays.asList not working - incompatible types
Stream#flatMap is used for combining multiple streams into one, so the supplier method you provided must return a Stream result.
you can try like this:
lines.stream().flatMap(line -> Stream.of(SPACE.split(line)))
.map(word -> // map to JavaRDD)
flatMap method take a FlatMapFunctionas parameter which is not annotated with #FunctionalInterface. So indeed you can not use it as a lambda.
Just build a real FlatMapFunctionobject as parameter and you will be sure of it.
flatMap() is Java 8 Stream API. I think you should check the IDEA compile java version.
compile java version
I am using OpenCV 3.0 (the latest version) in Java, but when I use SURF algorithm or SIFT algorithm it doesn't work and throws Exception which says: OpenCV Error: Bad argument (Specified feature detector type is not supported.) in cv::javaFeatureDetector::create
I have googled, but the answers which was given to this kind of questions did not solve my problem. If anyone knows about this problem please let me know.
Thanks in advance!
Update: The code below in third line throws exception.
Mat img_object = Imgcodecs.imread("data/img_object.jpg");
Mat img_scene = Imgcodecs.imread("data/img_scene.jpg");
FeatureDetector detector = FeatureDetector.create(FeatureDetector.SURF);
MatOfKeyPoint keypoints_object = new MatOfKeyPoint();
MatOfKeyPoint keypoints_scene = new MatOfKeyPoint();
detector.detect(img_object, keypoints_object);
detector.detect(img_scene, keypoints_scene);
If you compile OpenCV from source, you can fix the missing bindings by editing opencv/modules/features2d/misc/java/src/cpp/features2d_manual.hpp yourself.
I fixed it by making the following changes:
(line 6)
#ifdef HAVE_OPENCV_FEATURES2D
#include "opencv2/features2d.hpp"
#include "opencv2/xfeatures2d.hpp"
#include "features2d_converters.hpp"
...(line 121)
case SIFT:
fd = xfeatures2d::SIFT::create();
break;
case SURF:
fd = xfeatures2d::SURF::create();
break;
...(line 353)
case SIFT:
de = xfeatures2d::SIFT::create();
break;
case SURF:
de = xfeatures2d::SURF::create();
break;
The only requirement is that you build opencv_contrib optional module along with your sources (you can download the git project from https://github.com/Itseez/opencv_contrib and just set its local path on opencv's ccmake settings.
Oh, and keep in mind that SIFT and SURF are non-free software ^^;
That is because they are not free in newer versions of OpenCV (3+). I faced that problem some time ago. You have to:
Download OpenCV (if you have not)
Download the nonfree part from opencv github repo
Generate the makefiles with cmake -DBUILD_SHARED_LIBS=OFF specifying the nonfree part with DOPENCV_EXTRA_MODULES_PATH=../opencv_contrib/modules option and build with make -j8 (or whatever Java version you use)
Edit features2d_manual.hpp file, including opencv2/xfeatures2d.hpp and including the necessary code for SIFT and SURF case, which are commented and not defined:
fd=xfeatures2d::SIFT::create(); for SIFT descriptor and de = xfeatures2d::SIFT::create(); for SIFT extractor. Do the same for SURF if you want to use it too.
I wrote this post explaining step by step how to compile the non-free OpenCV part in order to use privative tools like SIFT or SURF.
Compile OpenCV non-free part.
I believe changing features2d module (FeatureDetector class or any other classes from features2d_manual.hpp) to enable methods from OpenCV contrib modules is less attractive approach because it leads to circular dependency between the "core" OpenCV and extensions (which can be non-free or experimental).
There is another way to fix this issue without affecting feature2d classes. Making changes in xfeatures2d CMakeLists.txt as described here leads to generation of java wrappers for SIFT and SURF - opencv-310.jar has org.opencv.xfeatures2d package now. Some fix was required in /opencv/modules/java/generator/gen_java.py. Namely inserted 2 lines as shown below:
def addImports(self, ctype):
if ctype.startswith('vector_vector'):
self.imports.add("org.opencv.core.Mat")
self.imports.add("org.opencv.utils.Converters")
self.imports.add("java.util.List")
self.imports.add("java.util.ArrayList")
self.addImports(ctype.replace('vector_vector', 'vector'))
elif ctype.startswith('Feature2D'): #added
self.imports.add("org.opencv.features2d.Feature2D") #added
elif ctype.startswith('vector'):
self.imports.add("org.opencv.core.Mat")
self.imports.add('java.util.ArrayList')
if type_dict[ctype]['j_type'].startswith('MatOf'):
self.imports.add("org.opencv.core." + type_dict[ctype]['j_type'])
else:
self.imports.add("java.util.List")
self.imports.add("org.opencv.utils.Converters")
self.addImports(ctype.replace('vector_', ''))
After these changes wrappers are generated successfully. However the main problem still remains, how to use these wrappers from Java )). For example SIFT.create() gives the pointer to a new SIFT class but calling any class method (for instance detect()) crashes Java. I also noticed that using MSER.create() directly from Java leads to the same crash.
So it looks like the problem is isolated to the way how Feature2D.create() methods are wrapped in Java. The solution seems to be the following (again, changing /opencv/modules/java/generator/gen_java.py):
Find the string:
ret = "%(ctype)s* curval = new %(ctype)s(_retval_);return (jlong)curval->get();" % { 'ctype':fi.ctype }
Replace it with the following:
ret = "%(ctype)s* curval = new %(ctype)s(_retval_);return (jlong)curval;" % { 'ctype':fi.ctype }
Rebuild the opencv. That is it, all create() methods will start working properly for all children of Feature2D class including experimental and non-free methods. FeatureDescriptor/DescriptorExtractor wrappers can be deprecated I think as Feature2D is much easier to use.
BUT! I'm not sure if the suggested fix is safe for other OpenCV modules. Is there a scenario when (jlong)curval needs to be dereferenced? It looks like the same fix was suggested already here.
I have found a source of Java compiler written in Ocaml which should work.
But when I do make, it finished with an error:
unzip.o: In function `camlUnzip__59':
(.data+0x540): undefined reference to `camlzip_deflateEnd'
unzip.o: In function `camlUnzip__59':
(.data+0x544): undefined reference to `camlzip_deflate'
unzip.o: In function `camlUnzip__59':
(.data+0x548): undefined reference to `camlzip_deflateInit'
collect2: ld returned 1 exit status
File "caml_startup", line 1, characters 0-1:
Error: Error during linking
make: *** [javacx] Error 2
It is odd that the file "caml_startup" even does not exist in the folder. Could anyone help? Thank you very much.
caml_startup is part of the OCaml runtime.
The project's website mentions that it works with OCaml 3.09, which is quite old. It worked for me with 3.10 (which is still quite old; latest release is 3.12) - maybe it just doesn't work with more recent versions.
However, as a first guess, I would try simply deleting these definitions from unzip.ml - they are never called, and declare external routines which are not actually implemented (whereas other external routines in unzip.ml are implemented in zlib.c):
external deflate_init: int -> bool -> stream = "camlzip_deflateInit"
external deflate:
stream -> string -> int -> int -> string -> int -> int -> flush_command
-> bool * int * int
= "camlzip_deflate_bytecode" "camlzip_deflate"
external deflate_end: stream -> unit = "camlzip_deflateEnd"
Before anyone screams about EOL'ed JDK, I'd like to point out that my question is not about how to compile the following. There is a real question here and it's not about JDK 1.5 being EOL'ed...
The following under JDK 1.5, up to 1.5.0_22 (the last one I could find) produces on my system a compiler error:
private Object[] boozinga() {
boolean b = Math.abs(42) > 0;
Object[] res = new Object[1];
res[0] = b ? new int[1] : new String[1];
return res;
}
Changing the Math.abs(42) > 0 to true allows compilation.
Changing the ternary "assignment" to an if/else allows compilation.
Using JDK 1.6 allows compilation.
So I was wondering: is there something not legal in the above code under Java 1.5 and that is allowed under Java 1.6?
Does it crash for those of you that are under Java 1.5 too?
The crash says something like this:
An exception has occured in the
compiler (1.5.0_22). Please file a bug
at the Java Developer Connection
(http://java.sun.com/webapps/bugreport)
after checking the Bug Parade for
duplicates. Include your program and
the following diagnostic in your
report. Thank you.
I take it filling a bug report for an EOL'ed JDK is an exercice in futility but still, I'd still like to know if the above is valid Java 1.5 code or not.
I think it is legal. The evidence is that JDK 1.6.0_21 compiles it with options -source 1.5 -target 1.5. Can't you use JDK 1.6 with these options to compile and JRE 1.5 to run?
It crashes for me, too (JDK 1.5.0_12). It crashes for me even with:
public Object boozinga() {
boolean b = true;
Object res = b ? new int[1] : new String[1];
return res;
}
The difficulty for the compiler is that the type of b ? new int[1] : new String[1] is java.lang.Object & java.io.Serializable & java.lang.Cloneable.
The problem here is that the compiler has trouble to decide the type of the expression b ? new int[1] : new String[1]. I had something like this before (with 1.1.8 or 1.2, I think - but with a real error message, not a compiler crash), and then simply used a cast to help the compiler here.
res[0] = b ? (Object)new int[1] : new String[1];
I didn't look what the language specification says about this - but the compiler should never crash with an exception, it should give a real error message.