Java <-> Scala convertion - "value is not a member of" - java

I have a problem with Scala code with Java methods.
It is calling:
value getDepth is not a member of amqpManagment.utils.data.ChessObject
var depth: Int = chessObjects.getDepth()
^
However i use getDepth in many other places in Java code and it works fine.
Also after put that code it was working in InteliJ by few hours which is weird but maybe project didnt rebuild itself after that change...
However InteliJ shows code is okay, but during compiling it shows that error. Rebuilding by InteliJ or terminal doesnt help.
Scala code:
import amqpManagment.utils.data.ChessObject
object ChessScheduler {
// DEPTH GAME
def startGameWithDepthRule(chessObject: ChessObject) : Integer =
{
...
val depth: Int = chessObjects.getDepth()
...
}
}
Java Code:
#Getter
#Setter
public class ChessObject {
private Integer depth;
...
}
build.sbt
import sbt.Keys._
import sbt.Level
name := "ChessEngineModuler"
logLevel := Level.Warn
version := "1.0"
scalaVersion := "2.12.2"
Thank you for your help.

Hello #Chenna Reddy :)
Thank you for your post, It seems it was problem with Lombok indeed. However after your answer i realised it was a problem because Scala code was compiled before Java one.
I check three solutions cause i had added dependency and Annotation Processor On.
First solution is just adding Getters and Setters to Java class not by the Lombok, however it is ugly solution
Second Solution is just adding in Files -> Settings -> Build, Execution, Deployment -> Compiler -> Scala Compiler -> Compile Order -> Java then Scala.
Third one is set in build.sbt -> compileOrder := CompileOrder.JavaThenScala
I think 3rd is the best one if we want deploy that code somewhere :)

Looks like you are using lombok for auto generation of getters. Please add lombok dependency.
libraryDependencies += "org.projectlombok" % "lombok" % "1.16.16"
Above step is not required if you are building Java project seperately and that project has lombok as a compile time dependency. Then generated jar file must have all the getters already.
Regarding why Intellij shows error sometimes, its possible that you didn't enable annotation processing from Files -> Settings -> Build, Execution, Deployment -> Compiler -> Annotation Processors.

Related

Standard Method TEXT is undefined when compiling jasper report

When I package my stand-alone-java-application, that compiles, renders and prints Jasper-Reports, in a fat jar with all dependencies, I get the error that the function TEXT – a function used in the report and defined in the net.sf.jasperreports-functions-library is not found.
The method TEXT(Integer, String) is undefined for the type [...]
value = IF(LEN(TEXT(((java.lang.Integer)parameter_X.getValue()),"#"))==2,"***",REPT("*",6-LEN(TEXT(((java.lang.Integer)parameter_X.getValue()),"#")))) //$JR_EXPR_ID=58$
Other functions from the same library work. When I run the application with gradle run, the function is found and the report can be printed. The library is on my classpath.
There are several similar questions on this site and Stackoverflow, but neither provided answers, that worked for me. In the following, I will explain what I tried:
In my build.gradle-File I defined dependencies to the following libraries:
implementation('net.sf.jasperreports:jasperreports:6.18.1')
implementation('net.sf.jasperreports:jasperreports-functions:6.18.1')
In my java-Files, I created a DesignFile and statically imported the functions into it. I tried two methods:
Method 1 as given in an answer in this thread: Unresolved symbols when compiling jasper report
/*…*/
designFile = JRXmlLoader.load(sourceFile.getAbsolutePath());
designFile.addImport("static net.sf.jasperreports.functions.standard.TextFunctions.*");
designFile.addImport("static net.sf.jasperreports.functions.standard.MathFunctions.*");
designFile.addImport("static net.sf.jasperreports.functions.standard.DateTimeFunctions.*");
designFile.addImport("static net.sf.jasperreports.functions.standard.LogicalFunctions.*");
JasperReport compiledReport = JasperCompileManager.getInstance(ctx).compile(designFile);
/*…*/
Method 2: importing each function on its own
public static String[] textFunctions(){
return new String[]{"BASE", "CHAR", "CLEAN", "CODE", "CONCATENATE", "DOUBLE_VALUE",
"EXACT", "FIND", /*"FIXED", */"FLOAT_VALUE", "INTEGER_VALUE", "LEFT", "LEN", "LONG_VALUE",
"LOWER", "LTRIM", "MID", "PROPER", "REPLACE", "REPT", "RIGHT", "RTRIM", "SEARCH", "SUBSTITUTE",
"T", /*"TEXT",*/ "TRIM", "UPPER"};
}}
/*…*/
designFile = JRXmlLoader.load(sourceFile.getAbsolutePath());
for (String textFunction : textFunctions()){
designFile.addImport("static net.sf.jasperreports.functions.standard.TextFunctions." + textFunction);
}/* similarly for logical functions, numeric functions and datetime functions*/
}
JasperReport compiledReport = JasperCompileManager.getInstance(ctx).compile(designFile);
/*…*/
As you can see, the function TEXT is commented out. That’s because the program fails at runtime when run with “gradle run”, when I comment it in:
net.sf.jasperreports.engine.JRException: Errors were encountered when compiling report expressions class file:
1. The import net.sf.jasperreports.functions.standard.TextFunctions.TEXT cannot be resolved
import static net.sf.jasperreports.functions.standard.TextFunctions.TEXT;
The same thing is true with most datetime-functions, in fact, only TIME can be imported to the DesignObject without error at runtime
In addition to that, when I type net.sf.jasperreports.functions.standard.TextFunctions. in my IDE, the content-assist shows a list of available functions, yet TEXT is missing.
I suspected, that the function is simply missing in the library, but it is there. In the .gradle/cache/modules-2/files-2.1/… directory, there is the jar with the TextFunctions.java, that contains the function TEXT:
When building the FatJar with dependencies, I have a TextFunctions.class-File in it, that contains the TEXT-Function as well.
In my jar, there are two jasperreports_extension.properties on the root level:
with the smaller one (from the jasperreport-functions-dependency) containing the following lines:
net.sf.jasperreports.extension.registry.factory.functions=net.sf.jasperreports.functions.FunctionsRegistryFactory
net.sf.jasperreports.extension.functions.datetime=net.sf.jasperreports.functions.standard.DateTimeFunctions
net.sf.jasperreports.extension.functions.math=net.sf.jasperreports.functions.standard.MathFunctions, net.sf.jasperreports.functions.standard.LogicalFunctions
net.sf.jasperreports.extension.functions.text=net.sf.jasperreports.functions.standard.TextFunctions
net.sf.jasperreports.extension.functions.report=net.sf.jasperreports.functions.standard.ReportFunctions
Funnily enough, commenting out TEXT, running it locally with gradle run, it works without problems. But packaging it and running it with java -jar it fails to find this function. And statically importing this function leads to gradle run failing as well.
What is happening and how can I fix this? I want to distribute my FatJar on a server and run it, but this problems makes it impossible for me.

Gradle: how to declare a dependency to a specific configuration of a project programatically in java

Following the setup described in Simple sharing of artifacts between projects, we are in the special case where we have a multi module gradle build that produce different types of jars and we would like to declare a dependency to those jar in a configuration.
dependencies {
instrumentedClasspath(project(path: ":producer", configuration: 'instrumentedJars'))
}
from the docs works great.
In the project dependency-tests I have a project that reproduce the setup (with different names, but the idea is the same).
But I am doing this in a Gradle-plugin and I would like to have the same declaration in java.
DependencyHandler dependencyHandler = project.getDependencies();
// this adds a dependency to the main jar of the 'producer' project:
dependencyHandler.add("instrumentedClasspath", project.getRootProject().findProject(":producer"));
// this is not working:
dependencyHandler.add("instrumentedClasspath", project.getRootProject().findProject(":producer").getConfigurations().getByName("instrumentedJars"));
Failing with:
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':printConf'.
> Could not resolve all dependencies for configuration ':instrumentedJars'.
> Cannot convert the provided notation to an object of type Dependency: configuration ':producer:instrumentedJars' artifacts.
The following types/formats are supported:
- Instances of Dependency.
- String or CharSequence values, for example 'org.gradle:gradle-core:1.0'.
- Maps, for example [group: 'org.gradle', name: 'gradle-core', version: '1.0'].
- FileCollections, for example files('some.jar', 'someOther.jar').
- Projects, for example project(':some:project:path').
- ClassPathNotation, for example gradleApi().
Comprehensive documentation on dependency notations is available in DSL reference for DependencyHandler type.
* Try:
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
project(...)
inside the dependencies block comes from the DependencyHandler, and
path: ":producer", configuration: 'instrumentedJars'
is actually a map {"path"=":producer", "configuration"="instrumentedJars"}.
So something like that should work in Java:
Map<String, String> map = new HashMap<>();
map.put("path", ":producer");
map.put("configuration", "instrumentedJars");
dependencyHandler.add("instrumentedClasspath", dependencyHandler.project(map));
Note: When using Kotlin build script you can easily see types and declarations of functions and might be easier for discovering API. So in Kotlin project(...) in the dependencies block is an extension method defined as:
fun DependencyHandler.project(
path: String,
configuration: String? = null
): ProjectDependency =
uncheckedCast(
project(
if (configuration != null) mapOf("path" to path, "configuration" to configuration)
else mapOf("path" to path)
)
)

Sonar Lint issue when walking a directory

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());

Puppet "require" not working as expected

I have the following two manifests:
class profile::maven inherits profile::base {
# Hiera
$version = hiera('profile::maven::version', '3.2.1')
$settings = hiera_hash('profile::maven::settings', undef)
$environments = hiera_hash('profile::maven::environments', undef)
# Dependencies
require '::profile::java'
# Modules
class { '::maven::maven':
version => $version,
}
if ($settings) {
create_resources('::maven::settings', $settings)
}
if ($environments) {
create_resources('::maven::environments', $environments)
}
}
and
class profile::java inherits profile::base {
# Hiera
$distribution = hiera('profile::java::distribution', 'jdk')
$version = hiera('profile::java::version', 'present')
# Modules
class { '::java':
distribution => $distribution,
version => $version,
}
# Parameters
$java_home = $::java::java_home
file { 'profile-script:java.sh':
ensure => present,
path => '/etc/profile.d/java.sh',
content => template('profile/java.sh.erb'),
}
}
I want that profile::java has completely finished before profile::maven is executed.
The site.pplooks as follows and should not be modified in order to comply with puppet's role-profile approach later (work in progress):
node 'gamma.localdomain' {
include 'profile::java'
include 'profile::maven'
}
After compilation the scripts starts with downloading the maven archive. Why does
require '::profile::java'
not ensure the execution order? Has someone an idea how to achieve the desired behavior?
I believe that the problem here is that the require profile::java is scoped to the profile::maven class, so all resources declared in the latter class depend on profile::java. However, this will not propagate to classes that profile::maven declares, such as maven::maven.
To achieve that, you can establish a dependency among those classes
include profile::java
include maven::maven
Class[profile::java] -> Class[maven::maven]
This can incur substantial complexity in the dependency graph, so be wary of that. This can be avoided using the Anchor Pattern.
Note that use of the require function is discouraged due to possible dependency cycle issues.
Since at least Puppet 3.5 you can use "contain" to ensure that everything inside profile::java completes before profile::maven. The following addition to profile::java would be required:
class profile::java inherits profile::base {
...
contain '::maven::maven'
...
}
Answering this old, answered question as it comes up first when googling "puppet require does not work"

buildr: package dependencies into a single jar

I have a java project that is built with buildr and that has some external dependencies:
repositories.remote << "http://www.ibiblio.org/maven2"
repositories.remote << "http://packages.example/"
define "myproject" do
compile.options.target = '1.5'
project.version = "1.0.0"
compile.with 'dependency:dependency-xy:jar:1.2.3'
compile.with 'dependency2:dependency2:jar:4.5.6'
package(:jar)
end
I want this to build a single standalone jar file that includes all these dependencies.
How do I do that?
(there's a logical followup question: How can I strip all the unused code from the included dependencies and only package the classes I actually use?)
This is what I'm doing right now. This uses autojar to pull only the necessary dependencies:
def add_dependencies(pkg)
tempfile = pkg.to_s.sub(/.jar$/, "-without-dependencies.jar")
mv pkg.to_s, tempfile
dependencies = compile.dependencies.map { |d| "-c #{d}"}.join(" ")
sh "java -jar tools/autojar.jar -baev -o #{pkg} #{dependencies} #{tempfile}"
end
and later:
package(:jar)
package(:jar).enhance { |pkg| pkg.enhance { |pkg| add_dependencies(pkg) }}
(caveat: I know little about buildr, this could be totally the wrong approach. It works for me, though)
I'm also learning Buildr and currently I'm packing Scala runtime with my application this way:
package(:jar).with(:manifest => _('src/MANIFEST.MF')).exclude('.scala-deps')
.merge('/var/local/scala/lib/scala-library.jar')
No idea if this is inferior to autojar (comments are welcome), but seems to work with a simple example. Takes 4.5 minutes to package that scala-library.jar thought.
I'm going to use Cascading for my example:
cascading_dev_jars = Dir[_("#{ENV["CASCADING_HOME"]}/build/cascading-{core,xml}-*.jar")]
#...
package(:jar).include cascading_dev_jars, :path => "lib"
Here is how I create an Uberjar with Buildr, this customization of what is put into the Jar and how the Manifest is created:
assembly_dir = 'target/assembly'
main_class = 'com.something.something.Blah'
artifacts = compile.dependencies
artifacts.each do |artifact|
Unzip.new( _(assembly_dir) => artifact ).extract
end
# remove dirs from assembly that should not be in uberjar
FileUtils.rm_rf( "#{_(assembly_dir)}/example/package" )
FileUtils.rm_rf( "#{_(assembly_dir)}/example/dir" )
# create manifest file
File.open( _("#{assembly_dir}/META-INF/MANIFEST.MF"), 'w') do |f|
f.write("Implementation-Title: Uberjar Example\n")
f.write("Implementation-Version: #{project_version}\n")
f.write("Main-Class: #{main_class}\n")
f.write("Created-By: Buildr\n")
end
present_dir = Dir.pwd
Dir.chdir _(assembly_dir)
puts "Creating #{_("target/#{project.name}-#{project.version}.jar")}"
`jar -cfm #{_("target/#{project.name}-#{project.version}.jar")} #{_(assembly_dir)}/META-INF/MANIFEST.MF .`
Dir.chdir present_dir
There is also a version that supports Spring, by concatenating all the spring.schemas

Categories

Resources