eclipse class path issue with jackson lib gradle - java

My project opened once in eclipse oxygen and in mars, I was shown an fix to import jackson lib in eclipse oxygen (a eclipse suggestion) - I did that and it fixed the issue there - although I already had mentioned the same dependency in my gradle dependencies list of my project.
After that I opened the same project in eclipse mars and the dependency is shown in buildpath(eclipse list of deps), in my gradle deps list but eclipse mars still is showing an error on source code.
I cleaned the project and did ./gradlew eclipse as well - everything is successfully but eclipse mars fails to resolve the dependency - how should I resolve this issue.
my build.gradle is
/*
* This build file was generated by the Gradle 'init' task.
*
* This generated file contains a sample Java Library project to get you started.
* For more details take a look at the Java Libraries chapter in the Gradle
* user guide available at https://docs.gradle.org/3.5/userguide/java_library_plugin.html
*/
// Apply the java-library plugin to add support for Java Library
apply plugin: 'java-library'
apply plugin: 'eclipse'
// In this section you declare where to find the dependencies of your project
repositories {
// Use jcenter for resolving your dependencies.
// You can declare any Maven/Ivy/file repository here.
jcenter()
mavenCentral()
}
dependencies {
// This dependency is exported to consumers, that is to say found on their compile classpath.
api 'org.apache.commons:commons-math3:3.6.1'
// This dependency is used internally, and not exposed to consumers on their own compile classpath.
implementation 'com.google.guava:guava:21.0'
// Use JUnit test framework
testImplementation 'junit:junit:4.12'
// https://mvnrepository.com/artifact/org.jsoup/jsoup
compile group: 'org.jsoup', name: 'jsoup', version: '1.11.2'
// https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core
compile group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.9.3'
}
Here's my code for ref
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Iterator;
import java.util.Scanner;
import java.util.regex.Pattern;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
public class Main {
// public ObjectMapper mapper = new ObjectMapper();
public static void main(String[] args) {
// for (String html : args) {
// Main main = new Main();
// try {
// main.parseHtml(html);
// } catch (JsonProcessingException e) {
// e.printStackTrace();
// }
// }
Main main = new Main();
String html = main.getFile("appleInc.html");
try {
main.parseHtml(html);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String getFile(String fileName) {
StringBuilder result = new StringBuilder("");
//Get file from resources folder
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
result.append(line).append("\n");
}
scanner.close();
} catch (IOException e) {
e.printStackTrace();
}
return result.toString();
}
public void parseHtml(String html) throws JsonProcessingException {
Document document = Jsoup.parse(html);
// parse all the table required
// ArrayNode tableInfo = retrieveTableInfo(document);
// get the metadata from the html
ObjectNode metadataObject = retrieveMetadataInfo(document);
// tableInfo.add(metadataObject);
// System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(tableInfo));
}
#SuppressWarnings("unused")
private ObjectNode retrieveMetadataInfo(Document document) {
String type = document.getElementsByTag("type").text();
String companyName = findCompanyName(document);
String employerIdentificationNo = findEmployerIdentificationNumber(document);
return null;
}
private String findEmployerIdentificationNumber(Document document) {
String employerNo = "";
employerNo = document.getElementsContainingText("I.R.S. Employer").prev("div").text();
if (employerNo.isEmpty()) {
Iterator<Element> iterator = document.getElementsContainingText("Employer Identification").prev("tr")
.iterator();
while (iterator.hasNext()) {
Element element = (Element) iterator.next();
if (element.is("tr")) {
employerNo = element.getElementsMatchingText(getPattern()).text();
}
}
}
return null;
}
private Pattern getPattern() {
String re1 = "(\\d+)";
String re2 = "(-)";
String re3 = "(\\d+)";
return Pattern.compile(re1 + re2 + re3, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
}
private String findCompanyName(Document document) {
return document.getElementsContainingText("Exact name of Registrant").prev("div").text();
}
private ArrayNode retrieveTableInfo(Document document) {
Elements tables = document.getElementsByTag("table");
tables.forEach(table -> {
if (Validator.isTableUsefull(table))
return;
String tableTitle = getTableTitle(document, table);
});
return null;
}
private String getTableTitle(Document document, Element table) {
// TODO Auto-generated method stub
return null;
}
}

You're using classes that are not part of jackson core. As you can see by browsing the documentation, or simply by looking at the content of the jar file.
As you can see, the class JsonProcessingException from the package com.fasterxml.jackson.core, is found without problem. That's because it is part of jackson-core.
The classes that are missing are all in the package com.fasterxml.jackson.databind. To have them resolved, you need to add the needed library: com.fasterxml.jackson.core:jackson-databind.

Related

No query executer factory registered for the 'sql' language

The issue regarding the error: net.sf.jasperreports.engine.JRRuntimeException: No query executer factory registered for the 'sql' language
My issue is: whenever I try to run JasperReports from dev environment I can get the reports generated. But when I run jar file the error comes up.
Is there any workaround to set the enironment variable net.sf.jasperreports.query.executer.factory.sql ? I try to use Jasper 6.19.1 and 6.20.0 but the problem us the same.
The problem is related to this variable located in the file default.jasperreports.properties that's located in the JasperReports jar root.
I'm using IntelliJ Ide and gradle
I created a program to show the problem. There are only two files.
Main.java
package br.com.mawan.mawanReport;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.view.JasperViewer;
public class Main {
private static final String url = "jdbc:mysql://localhost:3306/wavecounter";
private static final String driver = "com.mysql.cj.jdbc.Driver";
private static final String login = "root";
private static final String pwd = "";
public Main() {}
public void print(String path ) throws JRException, SQLException, ClassNotFoundException {
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, login, pwd);
JasperReport report = JasperCompileManager.compileReport( path );
JasperPrint reportFill = JasperFillManager.fillReport( report , null, conn );
JasperViewer.viewReport( reportFill , true );
conn.close();
}
public static void main(String[] args) {
try {
new br.com.mawan.mawanReport.Main().print( "C:\\wavecounter\\reports\\Teste.jrxml" );
} catch (Exception e) {
e.printStackTrace();
}
}
}
build.gradle
plugins {
id 'java'
}
group 'br.com.mawan'
version '1.0.0'
repositories {
mavenCentral()
jcenter()
}
dependencies {
implementation("org.apache.poi:poi:5.2.2")
implementation("com.lowagie:itext:2.1.7")
implementation("org.olap4j:olap4j:1.2.0")
implementation("net.sf.jasperreports:jasperreports:5.6.1")
implementation("net.sf.jasperreports:jasperreports-fonts:5.6.1")
implementation("xerces:xercesImpl:2.10.0")
implementation("mysql:mysql-connector-java:8.0.29")
}
jar {
manifest { attributes "Main-Class": "br.com.mawan.mawanReport.Main" }
from { configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } }
exclude 'META-INF/*.RSA', 'META-INF/*.SF','META-INF/*.DSA'
}
To solve it I created a file concatenating both files and put it in the resource with the name new.jasperreports_extension.properties.
Inside the jar tag I inserted the file name in exclude command. After that a insert a command to rename new.jasperreports_extension.properties to jasperreports_extension.properties.
jar {
exclude 'META-INF/*.RSA', 'META-INF/*.SF','META-INF/*.DSA','jasperreports_extension.properties'
manifest { attributes "Main-Class": "br.com.mawan.mawanReport.Main" }
from { configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } }
rename('new.jasperreports_extension.properties', "jasperreports_extension.properties")
}
After that everything worked.
I would like to give credit to dada67.

Why FileUtils can not be used in a common gradle transform code?

I just write a class which extends Transform class like this:
package com.example.plugin;
import org.gradle.internal.impldep.org.apache.commons.io.FileUtils;
import ...;
public class MyTransform extends Transform{
...
#Override
public void transform(TransformInvocation transformInvocation) throws TransformException, InterruptedException, IOException {
Collection<TransformInput> inputs = transformInvocation.getInputs();
TransformOutputProvider outputProvider = transformInvocation.getOutputProvider();
inputs.forEach(transformInput -> {
transformInput.getJarInputs().forEach(jarInput -> {
File dest = outputProvider.getContentLocation(jarInput.getName(), jarInput.getContentTypes(), jarInput.getScopes(), Format.JAR);
try {
// System.out.println(jarInput.getName());
FileUtils.copyFile(jarInput.getFile(), dest);
} catch (IOException e) {
e.printStackTrace();
}
});
transformInput.getDirectoryInputs().forEach(directoryInput -> {
File dest = outputProvider.getContentLocation(directoryInput.getName(), directoryInput.getContentTypes(), directoryInput.getScopes(), Format.DIRECTORY);
try {
// System.out.println(directoryInput.getName());
FileUtils.copyDirectoryToDirectory(directoryInput.getFile(), dest);
} catch (IOException e) {
e.printStackTrace();
}
});
});
}
}
However, when I use it on other gradle application, it got error with gradle build:
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:transformClassesWithMr_Spade is coming.ForDebug'.
> org/gradle/internal/impldep/org/apache/commons/io/FileUtils
It seems that the class FileUtils has some problems, but I just don't know what's wrong.
Here is the build.gradle of plugin:
plugins {
// Apply the Java Gradle plugin development plugin to add support for developing Gradle plugins
id 'java-gradle-plugin'
id 'maven-publish'
}
dependencies {
implementation 'org.testng:testng:7.4.0'
// Use JUnit Jupiter for testing.
testImplementation 'org.junit.jupiter:junit-jupiter:5.8.1'
implementation 'com.android.tools.build:gradle:7.1.3'
implementation "androidx.navigation:navigation-safe-args-gradle-plugin:2.4.2"
// implementation 'org.ow2.asm:asm:9.2'
// implementation 'org.ow2.asm:asm-tree:9.2'
implementation 'org.apache.commons:commons-io:1.3.2'
}
gradlePlugin {
// Define the plugin
plugins {
greeting {
id = 'com.example.plugin.greeting'
implementationClass = 'com.example.plugin.Plugin_project_namePlugin'
}
}
}
publishing {
publications {
maven(MavenPublication) {
groupId = 'aaa.bbb'
artifactId = 'ccc.ddd'
version = '1.0'
from components.java
}
}
repositories {
maven {
// change to point to your repo, e.g. http://my.org/repo
url = layout.buildDirectory.dir('../../repo')
}
}
}
...
build.gradle of application:
plugins {
id 'com.android.application'
id 'com.example.plugin.greeting'
}
...
dependencies {
// implementation gradleApi() //gradle sdk
implementation 'androidx.appcompat:appcompat:1.3.0'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
// implementation 'org.apache.commons:commons-io:1.3.2'
...
}
By the way, since my plugin folder and app folder are in the same folder, so i will use command like "build"(for plugin)->"publish"(for plugin)->"build"(for app), and the fact is the first two step is success, but the last step is failed. Just like that the plugin itself do not have problem but occurs some problem when it work on the app :(

Jar file and resource file returning null

I have a simple program that reads a text file (test.txt) line by line and prints each line to the console. In intellij it works just fine.
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.File;
public class testing {
public static void main(String[] args) {
testing main= new testing();
main.handleData("test.txt");
// handleData();
//System.out.println("hello world");
}
public void handleData(String fileName) {
System.out.println("Testing");
File file= new File(getClass().getResource(fileName).getPath());
try {
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine()){
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
I am trying to build it with gradle and when i run the jar command java -jar out/artifacts/helloTestingWorld_jar/helloTestingWorld.jar I get an error saying the path is null
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.net.URL.getPath()" because the return value of "java.lang.Class.getResource(String)" is null
at testing.handleData(testing.java:22)
at testing.main(testing.java:12)
My build.gradle file looks like this
plugins {
id 'java'
}
group 'org.example'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
}
jar {
manifest {
attributes "Main-Class": "src.main.java.testing"
}
from {
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
}
}
test {
useJUnitPlatform()
}
My resource folder is marked as the resource root and my java folder that contains my main class is marked as the source root. I am thinking that I might have to add the text file as a dependency in the jar file?
I have had a look at all of the other suggestions on here and the all lead to the same result. I have tried rebuilding the project from scratch and still the same result.
I have also tried using InputStream instead of File
InputStream in = getClass().getResourceAsStream(fileName);
When I use InputStream I get this error
Exception in thread "main" java.lang.NullPointerException
at java.base/java.io.Reader.<init>(Reader.java:168)
at java.base/java.io.InputStreamReader.<init>(InputStreamReader.java:76)
at java.base/java.util.Scanner.<init>(Scanner.java:566)
at testing.handleData(test.java:23)
at testing.main(test.java:10)

gradle how get info about project (dependecies artifactID) on Java

In Gradle i can get project info (dependencies, artifact, and group id's) on Groovy like this:
class TestPlugin implements Plugin<Project> {
#Override
void apply(Project project) {
def example = project.tasks.create("example") << {
def dep = project.configurations.runtime.allDependencies
def info = project.configurations.runtime.getName()
def g = project.configurations.runtime.getAllArtifacts()
}
How can i get this on Java ?
You can add a task that will write whatever values you like out to a java Properties file, like so:
apply plugin: 'java'
apply plugin: 'application'
def generatedResourcesDir = new File(project.buildDir, 'generated-resources')
tasks.withType(Jar).all { Jar jar ->
jar.doFirst {
def props = new Properties()
props.foobar = 'baz'
generatedResourcesDir.mkdirs()
def writer = new FileWriter(new File(generatedResourcesDir, 'build.properties'))
try {
props.store(writer, 'build properties')
writer.flush()
} finally {
writer.close()
}
}
}
sourceSets {
main {
resources {
srcDir generatedResourcesDir
}
}
}
mainClassName = 'BuildProps'
Notice that a directory is created in the build output directory of the root project (called generated-resources, though you can call it whatever you want, within reason). The properties file is then written to this directory as a result of running the custom task before any jar task. Finally, the generated-resources directory is added to the resources source set. This means it will become a resource within the generated jar file and as such can be accessed like any other resource; for example:
import java.util.Properties;
import java.io.InputStream;
import java.io.IOException;
class BuildProps {
public static void main(String[] args) {
try (InputStream inputStream =
BuildProps.class.getClassLoader().getResourceAsStream("build.properties")) {
Properties props = new Properties();
props.load(inputStream);
System.out.println("Build properties:");
System.out.println("foobar=" + props.getProperty("foobar", ""));
} catch (IOException e) {
e.printStackTrace();
}
}
}
which will print:
Build properties:
foobar=baz
As for your specific desired properties, you could set them like this: replace the line props.foobar = 'baz' with the following
def dependenciesProp = ''
for (def dependency : project.configurations.runtime.allDependencies) {
dependenciesProp += dependency.toString() + ','
}
props.dependencies = dependenciesProp
props.runtimename = project.configurations.runtime.name
def artifactsProp = ''
for (def artifact : project.configurations.runtime.allArtifacts) {
artifactsProp += artifact.toString() + ','
}
props.artifacts = artifactsProp

How to get version attribute from a gradle build to be included in runtime Swing application

I have a simple parent project with modules/applications within it. My build tool of choice is gradle. The parent build.gradle is defined below.
apply plugin: 'groovy'
dependencies {
compile gradleApi()
compile localGroovy()
}
allprojects {
repositories {
mavenCentral()
}
version "0.1.0-SNAPSHOT"
}
What I would like to do is utilize the version attribute (0.1.0-SNAPSHOT) within my swing application. Specifically, I'd like it to display in the titlebar of the main JFrame. I expect to be able to do something like this.setTitle("My Application - v." + ???.version);
The application is a plain java project, but I'm not opposed to adding groovy support it it will help.
I like creating a properties file during the build. Here's a way to do that from Gradle directly:
task createProperties(dependsOn: processResources) {
doLast {
new File("$buildDir/resources/main/version.properties").withWriter { w ->
Properties p = new Properties()
p['version'] = project.version.toString()
p.store w, null
}
}
}
classes {
dependsOn createProperties
}
You can always use brute force as somebody suggested and generate properties file during build. More elegant answer, which works only partially would be to use
getClass().getPackage().getImplementationVersion()
Problem is that this will work only if you run your application from generated jar - if you run it directly from IDE/expanded classes, getPackage above will return null. It is good enough for many cases - just display 'DEVELOPMENT' if you run from IDE(geting null package) and will work for actual client deployments.
Better idea is to keep the project version in gradle.properties file. All the properties from this file will be automatically loaded and can be used in build.gradle script.
Then if you need the version in your swing application, add a version.properties file under src/main/resources folder and filter this file during application build, here is a post that shows how it should be done.
version.properties will be included in the final jar, hence can be read and via ClassLoader and properties from this file can be displayed in application.
Simpler and updated solution of #Craig Trader (ready for Gradle 4.0/5.0)
task createProperties {
doLast {
def version = project.version.toString()
def file = new File("$buildDir/resources/main/version.txt")
file.write(version)
}
}
war {
dependsOn createProperties
}
I used #Craig Trader's answer, but had to add quite some changes to make it work (it also adds git-details):
task createProperties() {
doLast {
def details = versionDetails()
new File("$buildDir/resources/main/version.properties").withWriter { w ->
Properties p = new Properties()
p['version'] = project.version.toString()
p['gitLastTag'] = details.lastTag
p['gitCommitDistance'] = details.commitDistance.toString()
p['gitHash'] = details.gitHash.toString()
p['gitHashFull'] = details.gitHashFull.toString() // full 40-character Git commit hash
p['gitBranchName'] = details.branchName // is null if the repository in detached HEAD mode
p['gitIsCleanTag'] = details.isCleanTag.toString()
p.store w, null
}
// copy needed, otherwise the bean VersionController can't load the file at startup when running complete-app tests.
copy {
from "$buildDir/resources/main/version.properties"
into "bin/main/"
}
}
}
classes {
dependsOn createProperties
}
And load it from the constructor of class: VersionController
import static net.logstash.logback.argument.StructuredArguments.v;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.info.BuildProperties;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
#RestController
public class VersionController {
final static Logger log = LoggerFactory.getLogger(AppInfoController.class);
private Properties versionProperties = new Properties();
private String gitLastTag;
private String gitHash;
private String gitBranchName;
private String gitIsCleanTag;
VersionController()
{
String AllGitVersionProperties = "";
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("classpath:/version.properties");
if(inputStream == null)
{
// When running unit tests, no jar is built, so we load a copy of the file that we saved during build.gradle.
// Possibly this also is the case during debugging, therefore we save in bin/main instead of bin/test.
try {
inputStream = new FileInputStream("bin/main/version.properties");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
versionProperties.load(inputStream);
} catch (IOException e) {
AllGitVersionProperties += e.getMessage()+":";
log.error("Could not load classpath:/version.properties",e);
}
gitLastTag = versionProperties.getProperty("gitLastTag","last-tag-not-found");
gitHash = versionProperties.getProperty("gitHash","git-hash-not-found");
gitBranchName = versionProperties.getProperty("gitBranchName","git-branch-name-not-found");
gitIsCleanTag = versionProperties.getProperty("gitIsCleanTag","git-isCleanTag-not-found");
Set<Map.Entry<Object, Object>> mainPropertiesSet = versionProperties.entrySet();
for(Map.Entry oneEntry : mainPropertiesSet){
AllGitVersionProperties += "+" + oneEntry.getKey()+":"+oneEntry.getValue();
}
log.info("All Git Version-Properties:",v("GitVersionProperties", AllGitVersionProperties));
}
}
Using #Craig Trader's solution to save the properties in a version.properties file. Add to build.gradle:
task createProperties() {
doLast {
def details = versionDetails()
new File("$buildDir/resources/main/version.properties").withWriter { w ->
Properties p = new Properties()
p['version'] = project.version.toString()
p['gitLastTag'] = details.lastTag
p['gitCommitDistance'] = details.commitDistance.toString()
p['gitHash'] = details.gitHash.toString()
p['gitHashFull'] = details.gitHashFull.toString() // full 40-character Git commit hash
p['gitBranchName'] = details.branchName // is null if the repository in detached HEAD mode
p['gitIsCleanTag'] = details.isCleanTag.toString()
p.store w, null
}
// copy needed, otherwise the bean VersionController can't load the file at startup when running complete-app tests.
copy {
from "$buildDir/resources/main/version.properties"
into "bin/main/"
}
}
}
classes {
dependsOn createProperties
}
To load the properties runtime in version.properties you need to annotate your class with #PropertySource({"classpath:version.properties"})
Then you can assign a property to a private variable with annotation like:
#Value("${gitLastTag}")
private String gitLastTag;
Full example:
package com.versioncontroller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import javax.annotation.PostConstruct;
import java.util.Properties;
#PropertySource({"classpath:version.properties"})
public class VersionController {
#Value("${gitLastTag}")
private String gitLastTag;
#Value("${gitHash}")
private String gitHash;
#Value("${gitBranchName}")
private String gitBranchName;
#Value("${gitIsCleanTag}")
private String gitIsCleanTag;
#PostConstruct // properties are only set after the constructor has run
private void logVersion(){
// when called during the constructor, all values are null.
System.out.println("All Git Version-Properties:");
System.out.println("gitLastTag: " + gitLastTag),
System.out.println("gitHash: " + gitHash),
System.out.println("gitBranchName: " + gitBranchName),
System.out.println("gitIsCleanTag: " + gitIsCleanTag));
}
}

Categories

Resources