Spring Tool Suite 3.7.0 not reading #ConfigurationProperties for content assist in YML - spring

Hi I have move on to spring tool suite 3.7.0 with the highly anticipated feature of YAML editor as described here https://spring.io/blog/2015/06/30/spring-tool-suite-3-7-0-released specially the content assist that it provides .
The issue I am having is that my properties class as below
#ConfigurationProperties(prefix="datasource.ucp")
#Data
public Class DumbProperties{
private String url;
private String user;
...
}
does work but when I open my application.yml I still have to provide these manually the content assist doesnt work .ALso STS givem me a warning that the property doesnt exists .Screen shot below
ALso the maven entry for the same to find #ConfigurationProperties are added as below
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
anything I am missing here!!

Two things have to be in place for the configuration properties in your own source-code to work.
The "spring-boot-configuration-processor" must be on the classpath
The project must be confgure properly so that Eclipse JDT Annotation Processing is enabled to run the spring-boot-configuration-processor as part of an eclipse workspace build.
It sounds like you have 1. so probably its number 2. that's missing.
Normally, 2. should be configured automatically by STS, but it does this as part of m2e project configuration. If you just added the configuration-processor by pasting the xml into your pom, then its likely the project-configurator has not yet been executed. So try forcing it by selecting "Update Project" from the "Maven" context menu (accessed by right click on your project).
If that doesn't help, we'll have to troubleshoot a bit more as I don't know what's missing from your project's setup.

Related

TDengine database 3.0.1.7 jdbc connect error [duplicate]

I'm getting a NoSuchMethodError error when running my Java program. What's wrong and how do I fix it?
Without any more information it is difficult to pinpoint the problem, but the root cause is that you most likely have compiled a class against a different version of the class that is missing a method, than the one you are using when running it.
Look at the stack trace ... If the exception appears when calling a method on an object in a library, you are most likely using separate versions of the library when compiling and running. Make sure you have the right version both places.
If the exception appears when calling a method on objects instantiated by classes you made, then your build process seems to be faulty. Make sure the class files that you are actually running are updated when you compile.
I was having your problem, and this is how I fixed it. The following steps are a working way to add a library. I had done the first two steps right, but I hadn't done the last one by dragging the ".jar" file direct from the file system into the "lib" folder on my eclipse project. Additionally, I had to remove the previous version of the library from both the build path and the "lib" folder.
Step 1 - Add .jar to build path
Step 2 - Associate sources and javadocs (optional)
Step 3 - Actually drag .jar file into "lib" folder (not optional)
Note that in the case of reflection, you get an NoSuchMethodException, while with non-reflective code, you get NoSuchMethodError. I tend to go looking in very different places when confronted with one versus the other.
If you have access to change the JVM parameters, adding verbose output should allow you to see what classes are being loaded from which JAR files.
java -verbose:class <other args>
When your program is run, the JVM should dump to standard out information such as:
...
[Loaded junit.framework.Assert from file:/C:/Program%20Files/junit3.8.2/junit.jar]
...
If using Maven or another framework, and you get this error almost randomly, try a clean install like...
clean install
This is especially likely to work if you wrote the object and you know it has the method.
This is usually caused when using a build system like Apache Ant that only compiles java files when the java file is newer than the class file. If a method signature changes and classes were using the old version things may not be compiled correctly. The usual fix is to do a full rebuild (usually "ant clean" then "ant").
Sometimes this can also be caused when compiling against one version of a library but running against a different version.
I had the same error:
Exception in thread "main" java.lang.NoSuchMethodError: com.fasterxml.jackson.core.JsonGenerator.writeStartObject(Ljava/lang/Object;)V
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:151)
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:292)
at com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:3681)
at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:3057)
To solve it I checked, firstly, Module Dependency Diagram (click in your POM the combination -> Ctrl+Alt+Shift+U or right click in your POM -> Maven -> Show dependencies) to understand where exactly was the conflict between libraries (Intelij IDEA). In my particular case, I had different versions of Jackson dependencies.
1) So, I added directly in my POM of the project explicitly the highest version - 2.8.7 of these two.
In properties:
<jackson.version>2.8.7</jackson.version>
And as dependency:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
2) But also it can be solved using Dependency Exclusions.
By the same principle as below in example:
<dependency>
<groupId>group-a</groupId>
<artifactId>artifact-a</artifactId>
<version>1.0</version>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</exclusion>
</exclusions>
</dependency>
Dependency with unwanted version will be excluded from your project.
This can also be the result of using reflection. If you have code that reflects on a class and extracts a method by name (eg: with Class.getDeclaredMethod("someMethodName", .....)) then any time that method name changes, such as during a refactor, you will need to remember to update the parameters to the reflection method to match the new method signature, or the getDeclaredMethod call will throw a NoSuchMethodException.
If this is the reason, then the stack trace should show the point that the reflection method is invoked, and you'll just need to update the parameters to match the actual method signature.
In my experience, this comes up occasionally when unit testing private methods/fields, and using a TestUtilities class to extract fields for test verification. (Generally with legacy code that wasn't designed with unit testing in mind.)
If you are writing a webapp, ensure that you don't have conflicting versions of a jar in your container's global library directory and also in your app. You may not necessarily know which jar is being used by the classloader.
e.g.
tomcat/common/lib
mywebapp/WEB-INF/lib
For me it happened because I changed argument type in function, from Object a, to String a. I could resolve it with clean and build again
In my case I had a multi module project and scenario was like com.xyz.TestClass was in module A and as well as in module B and module A was dependent on module B. So while creating a assembly jar I think only one version of class was retained if that doesn't have the invoked method then I was getting NoSuchMethodError runtime exception, but compilation was fine.
Related : https://reflectoring.io/nosuchmethod/
Why anybody doesn't mention dependency conflicts? This common problem can be related to included dependency jars with different versions.
Detailed explanation and solution: https://dzone.com/articles/solving-dependency-conflicts-in-maven
Short answer;
Add this maven dependency;
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.0.0-M3</version>
<configuration>
<rules>
<dependencyConvergence />
</rules>
</configuration>
</plugin>
Then run this command;
mvn enforcer:enforce
Maybe this is the cause your the issue you faced.
It means the respective method is not present in the class:
If you are using jar then decompile and check if the respective version of jar have proper class.
Check if you have compiled proper class from your source.
I have just solved this error by restarting my Eclipse and run the applcation.
The reason for my case may because I replace my source files without closing my project or Eclipse.
Which caused different version of classes I was using.
Try this way: remove all .class files under your project directories (and, of course, all subdirectories). Rebuild.
Sometimes mvn clean (if you are using maven) does not clean .class files manually created by javac. And those old files contain old signatures, leading to NoSuchMethodError.
Just adding to existing answers. I was facing this issue with tomcat in eclipse. I had changed one class and did following steps,
Cleaned and built the project in eclpise
mvn clean install
Restarted tomcat
Still I was facing same error. Then I cleaned tomcat, cleaned tomcat working directory and restarted server and my issue is gone. Hope this helps someone
These problems are caused by the use of the same object at the same two classes.
Objects used does not contain new method has been added that the new object class contains.
ex:
filenotnull=/DayMoreConfig.conf
16-07-2015 05:02:10:ussdgw-1: Open TCP/IP connection to SMSC: 10.149.96.66 at 2775
16-07-2015 05:02:10:ussdgw-1: Bind request: (bindreq: (pdu: 0 9 0 [1]) 900 900 GEN 52 (addrrang: 0 0 2000) )
Exception in thread "main" java.lang.NoSuchMethodError: gateway.smpp.PDUEventListener.<init>(Lgateway/smpp/USSDClient;)V
at gateway.smpp.USSDClient.bind(USSDClient.java:139)
at gateway.USSDGW.initSmppConnection(USSDGW.java:274)
at gateway.USSDGW.<init>(USSDGW.java:184)
at com.vinaphone.app.ttn.USSDDayMore.main(USSDDayMore.java:40)
-bash-3.00$
These problems are caused by the concomitant 02 similar class (1 in src, 1 in jar file here is gateway.jar)
To answer the original question. According to java docs here:
"NoSuchMethodError" Thrown if an application tries to call a specified method of a class (either static or instance), and that class no longer has a definition of that method.
Normally, this error is caught by the compiler; this error can only occur at run time if the definition of a class has incompatibly changed.
If it happens in the run time, check the class containing the method is in class path.
Check if you have added new version of JAR and the method is compatible.
I fixed this problem in Eclipse by renaming a Junit test file.
In my Eclipse work space I have an App project and a Test project.
The Test project has the App project as a required project on the build path.
Started getting the NoSuchMethodError.
Then I realized the class in the Test project had the same name as the class in the App project.
App/
src/
com.example/
Projection.java
Test/
src/
com.example/
Projection.java
After renaming the Test to the correct name "ProjectionTest.java" the exception went away.
NoSuchMethodError : I have spend couple of hours fixing this issue, finally fixed it by just renaming package name , clean and build ... Try clean build first if it doesn't works try renaming the class name or package name and clean build...it should be fixed. Good luck.
I ran into a similar problem when I was changing method signatures in my application.
Cleaning and rebuilding my project resolved the "NoSuchMethodError".
Above answer explains very well ..just to add one thing
If you are using using eclipse use ctrl+shift+T and enter package structure of class (e.g. : gateway.smpp.PDUEventListener ), you will find all jars/projects where it's present. Remove unnecessary jars from classpath or add above in class path. Now it will pick up correct one.
I ran into similar issue.
Caused by: java.lang.NoSuchMethodError: com.abc.Employee.getEmpId()I
Finally I identified the root cause was changing the data type of variable.
Employee.java --> Contains the variable (EmpId) whose Data Type has been changed from int to String.
ReportGeneration.java --> Retrieves the value using the getter, getEmpId().
We are supposed to rebundle the jar by including only the modified classes. As there was no change in ReportGeneration.java I was only including the Employee.class in Jar file. I had to include the ReportGeneration.class file in the jar to solve the issue.
I've had the same problem. This is also caused when there is an ambiguity in classes. My program was trying to invoke a method which was present in two JAR files present in the same location / class path. Delete one JAR file or execute your code such that only one JAR file is used. Check that you are not using same JAR or different versions of the same JAR that contain the same class.
DISP_E_EXCEPTION [step] [] [Z-JAVA-105 Java exception java.lang.NoSuchMethodError(com.example.yourmethod)]
Most of the times java.lang.NoSuchMethodError is caught be compiler but sometimes it can occur at runtime. If this error occurs at runtime then the only reason could be the change in the class structure that made it incompatible.
Best Explanation: https://www.journaldev.com/14538/java-lang-nosuchmethoderror
I've encountered this error too.
My problem was that I've changed a method's signature, something like
void invest(Currency money){...}
into
void invest(Euro money){...}
This method was invoked from a context similar to
public static void main(String args[]) {
Bank myBank = new Bank();
Euro capital = new Euro();
myBank.invest(capital);
}
The compiler was silent with regard to warnings/ errors, as capital is both Currency as well as Euro.
The problem appeared due to the fact that I only compiled the class in which the method was defined - Bank, but not the class from which the method is being called from, which contains the main() method.
This issue is not something you might encounter too often, as most frequently the project is rebuilt mannually or a Build action is triggered automatically, instead of just compiling the one modified class.
My usecase was that I generated a .jar file which was to be used as a hotfix, that did not contain the App.class as this was not modified. It made sense to me not to include it as I kept the initial argument's base class trough inheritance.
The thing is, when you compile a class, the resulting bytecode is kind of static, in other words, it's a hard-reference.
The original disassembled bytecode (generated with the javap tool) looks like this:
#7 = Methodref #2.#22 // Bank.invest:(LCurrency;)V
After the ClassLoader loads the new compiled Bank.class, it will not find such a method, it appears as if it was removed and not changed, thus the named error.
Hope this helps.
The problem in my case was having two versions of the same library in the build path. The older version of the library didn't have the function, and newer one did.
I had a similar problem with my Gradle Project using Intelij.
I solved it by deleting the .gradle (see screenshot below) Package and rebuilding the Project.
.gradle Package
I had faced the same issue. I changed the return type of one method and ran the test code of that one class. That is when I faced this NoSuchMethodError. As a solution, I ran the maven builds on the entire repository once, before running the test code again. The issue got resolved in the next single test run.
One such instance where this error occurs:
I happened to make a silly mistake of accessing private static member variables in a non static method. Changing the method to static solved the problem.

How to push external xml file into spring boot embedded tomcat continer

i have created springboot project which gives fat-jar. i want to push external xml file in runtime into it.i want to place that xml file into spring-boot-tomcat container. tried many ways to do it (#import, --spring.config.location,etc) those ways didn't work out for me.
That xml file is ApplicationInsight.xml, which is used to post telemetry from our application to Azure portal.
Highly appreciate any help.
Based on the GitHJub issue, I think part of the problem is how you are passing JVM parameters, and how you are using "spring.config.location".
I am not familiar with Azure Insights really, but if I understand correctly, it is trying to load the ApplicationInsights.xml file to configure itself, and it's doing this automatically. So you really can't set it up in the WebConfigurerAdapter as I previously suggested because it has already initialized itself before that, correct? I left that part in anyways, but I get that it needs to be loaded sooner so I provided a few additional ways to add the file to the classpath ASAP.
New Stuff
First take a look at this line you had originally posted ala GitHub:
java -jar build/libs/file-gateway.jar --spring.config.location=classpath:/apps/conf/ApplicationInsight.xml
Instead the value should be just a folder path, without "classpath" of "file" prefix. Also, try using '-D' instead of '--'.
java -jar build/libs/file-gateway.jar -Dspring.config.location=/apps/conf/
The property is supposed to either refer to a directory containing auto configuration property files for Spring Boot. It can also work for referring to a specific "application.properties|yml" file.
With that, my previous suggestion may work for you.
Old Suggestion
If you require a unique way for loading resources, you can add a resource handler to your application.
#Configuration
#EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {
#Value("${telemetry.folder}")
private String telemetryFolder;
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceLocations(telemetryFolder);
}
}
And/or you could load it with apache IO:
#Value("${telemetry.file}")
private String telemetryFile;
#Autowired
private ResourceLoader resourceLoader;
public String telemtryXml(){
return org.apache.commons.io.IOUtils.toString(resourceLoader.getResource(telemtryFile).getInputStream());
}
But this will only work if the api you are using doesn't need to be initialized much earlier.
More New Stuff
In your last post on the GitHub issue, you tried this:
java -jar build/libs/file-gateway.jar -applicationinsights.configurationDirectory="/apps/conf/"
Instead, try adding the property as a jvm parameter like this:
java -jar build/libs/file-gateway.jar -Dapplicationinsights.configurationDirectory=/apps/conf/
Notice that I added a capital 'D' character after the, and I removed the quotes from the path.
Other ways to add the file to classpath are.
Add the directory to the JVM classpath.
java -cp "build/libs/file-gateway.jar:/apps/conf/*" your.package.MainSpringBootApplication
This requires that you specify the main class which is (commonly) annotated with '#SpringBootApplication' and contains the main method. You do not execute the jar like before, but you do still add it to the classpath.
Forget about SpringBoot, and go back to your roots as a JEE developer. Add a "context.xml" for your app under the "src/main/resources/META-INF" folder, or "src/main/webapp/META-INF". I prefer the later if I'm building an executable war file, and the former for jars.
Example context.xml:
<?xml version='1.0' encoding='utf-8'?>
<!-- path should be the context-path of you application.
<Context path="/">
<Resources className="org.apache.catalina.webresources.StandardRoot">
<PreResources base="/apps/conf"
className="org.apache.catalina.webresources.DirResourceSet"
internalPath="/"
webAppMount="/WEB-INF/classes"/>
</Resources>
</Context>
You can also use JVM parameters with EL.
So if you execute the jar with this:
java -jar build/libs/file-gateway.jar -Dapplicationinsights.configurationDirectory=/apps/conf/
You could set the resources base with this:
<!--snip -->
<PreResources base="${applicationinsights.configurationDirectory}"
<!--snip -->
Hope that helps:)

sonarqube + lombok = false positives

import lombok.Data;
#Data
public class Filter {
private Operator operator;
private Object value;
private String property;
private PropertyType propertyType;
}
For code above there are 4 squid:S1068 reports about unused private fields. (even they are used by lombok generated getters). I've seen that some fixes related to support of "lombok.Data" annotation have been pushed, but still having these annoying false positives.
Versions:
SonarQube 6.4.0.25310
SonarJava 4.13.0.11627
SonarQube scanner for Jenkins (2.6.1)
This case should be perfectly handled by SonarJava. Lombok annotations are taken into account at least since version 3.14 (SONARJAVA-1642). The issues you are getting are resulting from a misconfiguration of your Java project. No need to write any custom rules to handle this, this is natively supported by the analyzer.
SonarJava reads bytecode to know which annotation are used. Consequently, if you are not providing bytecode from your dependencies, on top of bytecode from your own code, the analyzer will behave erratically.
In particular, setting property sonar.java.libraries should solve your issue. Note that this property is normally automatically set when using SonarQube maven or gradle scanners.
Please have a look at documentation in order to correctly configure your project: https://docs.sonarqube.org/display/PLUG/Java+Plugin+and+Bytecode
I added following property to Sonar analysis properties file. And it works for me.
sonar.java.libraries=${env.HOME}/.m2/repository/org/projectlombok/lombok/**/*.jar
lombok v1.16.20 is lombok version on my project.
I'm using sonar-maven-plugin 3.4.0.905, lombok 1.16.18, with SonarQube CE Server v8.3.1.
I resolved the issue by adding
<sonar.java.libraries>target/classes</sonar.java.libraries> to the POM properties.
The answer suggested by Wohops and Barış Özdemir worked for me. Posting this answer because in my scenario, it took some time to figure out how to implement it because my CI builds are running in Travis and we don't know the path where the lombok-x.x.x.jar file will be downloaded because there is no much control we have on travis environment where the build runs.
I used my build tool (Gradle) to implement it. Following configuration in build.gradle ensured that as part of building of the project, all the jar dependencies get copied to ${buildDir}/output/libs
task copyToLib(type: Copy) {
into "${buildDir}/output/libs"
from configurations.runtime
}
build.dependsOn(copyToLib)
And then as mentioned in the previous answers, I configured the property in the sonar-project.properties file to this libs directory.
sonar.java.libraries=/home/travis/build/xxxxxx/build/output/libs/lombok-1.16.20.jar
Hope this helps.
Cheers.
You can configure the ignore issue rules:
sonar.issue.ignore.multicriteria=e1
sonar.issue.ignore.multicriteria.e1.ruleKey=java:S1068

spring boot 1.3.1 devtools hot reload not work if your project name is spring-boot

Spring boot 1.3.1.RELEASE, used devtools.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
Now I add some code in controller method, e.g.
logger.info("delete {} ", name);
but in eclipse console, nothing output, and access this url , the new add logger did not output. So why is so? why hot reload not work?
I found something could explain this phenomenon. Because my project name is spring-boot, and run Application class in eclispe you could see:
you could see after Application name appended (1)
I don't know what's this mean.
After rename project name to anything else(e.g. spring-boot-reservation), now I found devtools could work normally.
And this time the number after Application name is changed to 2,

Is it possible to access Maven project information from a custom plugin?

I'm writing a custom plugin in Maven and would like to access information about the project. As a simple example, within my Java code, I'd like to get the project's build directory. I know that I can get it using a parameter annotation like so:
#Mojo( name="myplugin" )
public class MyPluginMojo extends AbstractMojo {
// DOES work. The project.build.directory prop is resolved.
#Parameter( property="myplugin.buildDir", defaultValue="${project.build.directory}", required=true )
private File buildDir;
public void execute () throws MojoExecutionException
{
System.out.println(buildDir.getPath());
// DOES NOT work, prints the literal string.
System.out.println("${project.build.directory}");
}
}
That feels like a hack. To start with, I have no need to expose this parameter to the pom.xml. I'm only doing it this way because within the annotation, the property gets resolved.
I'd also like access to other properties, namely the project's dependencies.
I've been googling for hours without luck. The closest thing I've found is the MavenProject plugin but I can't get it to work either and it hasn't been updated since 2009 from the looks of it.
Gradle provides the "project" variable for this when writing plugins. Does Maven simply not allow this?
--- Update ---
Thanks to Robert's link to the documentation, I got this working. One thing that was a surprise to me was that the project.build.directory is not available through the injected project. According to the docs, you inject that separately. Here's what I added to my class to get both the project object and the build directory:
#Parameter( defaultValue="${project}", readonly=true, required=true )
MavenProject project;
#Parameter( defaultValue = "${project.build.directory}", readonly=true, required=true )
private File target;
And a dependency to my pom:
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-project</artifactId>
<version>3.0-alpha-2</version>
</dependency>
You're on the right path, it not a hack. But if you don't want to expose it as a parameter, then you should also add readonly=true. Maven also has the project variable, see http://maven.apache.org/plugin-tools/maven-plugin-tools-annotations/ for all common objects you can use within your project.
The only way to get current Maven project inside a Maven plugin is to inject it. See this question for more info.
See also the Mojo Cookbook that describe how to inject the current Maven project.

Resources