Using the following command:
java -jar target/spring-boot-config-0.0.1-SNAPSHOT.jar --spring.application.json='{"server":{"ip":"192.168.145.78"}}'
I get a org.springframework.boot.json.JsonParseException: Cannot parse JSON exception. I have no idea why, my command seems to be correct. Could anybody help me with this. My application is simple:
public class SpringBootConfigApplication {
private static Logger log = LoggerFactory.getLogger(SpringBootConfigApplication.class);
public static void main(String[] args) {
SpringApplication.run(SpringBootConfigApplication.class, args);
}
#Value("${server.ip}")
String serverIp;
#Bean
public CommandLineRunner values() {
return args -> {
log.info(" > The Server IP is: " + serverIp);
};
}
}
The full stacktrace is:
at org.springframework.boot.json.AbstractJsonParser.trimParse(AbstractJsonParser.java:48)
at org.springframework.boot.json.AbstractJsonParser.parseMap(AbstractJsonParser.java:36)
at org.springframework.boot.json.YamlJsonParser.parseMap(YamlJsonParser.java:46)
at org.springframework.boot.env.SpringApplicationJsonEnvironmentPostProcessor.processJson(SpringApplicationJsonEnvironmentPostProcessor.java:102)
at org.springframework.boot.env.SpringApplicationJsonEnvironmentPostProcessor.lambda$postProcessEnvironment$0(SpringApplicationJsonEnvironmentPostProcessor.java:97)
at java.base/java.util.Optional.ifPresent(Optional.java:176)
at org.springframework.boot.env.SpringApplicationJsonEnvironmentPostProcessor.postProcessEnvironment(SpringApplicationJsonEnvironmentPostProcessor.java:97)
at org.springframework.boot.env.EnvironmentPostProcessorApplicationListener.onApplicationEnvironmentPreparedEvent(EnvironmentPostProcessorApplicationListener.java:102)
at org.springframework.boot.env.EnvironmentPostProcessorApplicationListener.onApplicationEvent(EnvironmentPostProcessorApplicationListener.java:87)
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:176)
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:169)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:143)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:131)
at org.springframework.boot.context.event.EventPublishingRunListener.environmentPrepared(EventPublishingRunListener.java:82)
at org.springframework.boot.SpringApplicationRunListeners.lambda$environmentPrepared$2(SpringApplicationRunListeners.java:63)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1507)
at org.springframework.boot.SpringApplicationRunListeners.doWithListeners(SpringApplicationRunListeners.java:117)
at org.springframework.boot.SpringApplicationRunListeners.doWithListeners(SpringApplicationRunListeners.java:111)
at org.springframework.boot.SpringApplicationRunListeners.environmentPrepared(SpringApplicationRunListeners.java:62)
at org.springframework.boot.SpringApplication.prepareEnvironment(SpringApplication.java:374)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:332)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1343)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1332)
at be.brzyktom.springbootconfig.SpringBootConfigApplication.main(SpringBootConfigApplication.java:16)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
Use double quotations in outer string and escape them when defining keys and values
java -jar target/spring-boot-config-0.0.1-SNAPSHOT.jar --spring.application.json="{\"server\":{\"ip\":\"192.168.145.78\"}}"
Related
# Junit not working giving error #
Tried testing basic add operation using Junit its showing this error on my mac
# AddTest.java #
import static org.junit.Assert.*;
import org.junit.Test;
public class AddTest {
#Test
public void Addtest() {
MyJUnitClass junit = new MyJUnitClass();
int result = junit.add(100, 200);
assertEquals(300, result);
}
}
# MyJunitClass #
public class MyJUnitClass {
public int add(int a, int b) {
return a+b;
}
public String conCat(String a, String b) {
return a+b;
}
}
java.lang.NoClassDefFoundError: org/junit/runner/manipulation/Filter
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:332)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.loadTestLoaderClass(RemoteTestRunner.java:380)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.createRawTestLoader(RemoteTestRunner.java:370)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.createLoader(RemoteTestRunner.java:365)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.defaultInit(RemoteTestRunner.java:309)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.init(RemoteTestRunner.java:224)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:208)
Caused by: java.lang.ClassNotFoundException: org.junit.runner.manipulation.Filter
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
... 8 more
This is the error I am getting while running I have placed the JUnit 4.jar file libraries in buildpath. My I am able to access all the functions from JUnit jar file but when I run the JUnit test I get Failure error and this message in console.
You should try "add library", and then choosing JUnit, not adding a jar directly !
Good luck :)
In a command line Java application you can get arguments through the args parameter:
public static void main(String[] args) {
How can I do something similar in Ceylon? I tried copying the Java style:
shared void run(String[] args) {
but got an error since that is not allowed:
ceylon run: Cannot run toplevel method 'test.project.run':
it should have no parameters or they should all have default values.
I've been reading the ceylon-lang.org tour but I haven't found the answer.
Use the top-level process object in the language module.
String[] arguments = process.arguments;
String? argument = process.namedArgumentValue("name");
if (process.namedArgumentPresent("name")) {
// ...
}
I have Dropwizard application and I am writing unit tests for it. I am following Dropwizard's documentation to do so : http://dropwizard.readthedocs.org/en/latest/manual/testing.html
What I am missing is how can I add parameter to my test which invokes GET method?
Here in the documentation :
assertThat(resources.client().resource("/person/blah").get(Person.class))
.isEqualTo(person);
What if my get method has a parameter?
In Jersey's WebResource there are:
#Override
public <T> T get(Class<T> c) throws UniformInterfaceException, ClientHandlerException {
return handle(c, build("GET"));
}
#Override
public <T> T get(GenericType<T> gt) throws UniformInterfaceException, ClientHandlerException {
return handle(gt, build("GET"));
}
Query parameters are part of the resource URI. You can embed them in the string:
assertThat(resources.client().resource("/person/blah?a=b").get(Person.class)).isEqualTo(person);
Or you can build the URI dynamically:
URI resourceUri = UriBuilder.fromPath("/person/blah").queryParam("a", "b").build();
assertThat(resources.client().resource(resourceUri).get(Person.class)).isEqualTo(person);
I don't understand why I have this error.
When I use newRequest, I have a RuntimeException when calling the
makeRequest(request); method.
The exception message is : "play.mvc.results.NotFound : POST /"
But what is odd, is that in the .url, I specify "/dashboard", not
"/" (and of course, the url is well indicated in the routes file for POST requests!)
Thanks for your help.
Here is my test class :
public class DashboardTest extends FunctionalTest {
protected Request ajaxRequest;
#Before
public void _setUp() {
Fixtures.deleteDatabase();
Fixtures.loadModels("fixtures/accounts.yml");
ajaxRequest = newRequest();
//ajaxRequest.headers.put("X-Requested-With", new Header("X-
Requested-With", "XMLHttpRequest"));
ajaxRequest.method = "POST";
ajaxRequest.url = "/dashboard";
}
#Test
public void testAuthenticateWithValidDataAjax() {
ajaxRequest.params.put("email", "john.sm...#gmail.com");
Response response = makeRequest(ajaxRequest);
assertIsOk(response);
assertContentType("application/json", response);
}
}
Looking at the API documentation, the .url specifies that it needs the Full URL. What I would suggest you do instead, is to use the .action instead.
The Javadoc for the this is
Full action (ex: Application.index)
or specify the full URL, which would include
http://localhost:9000/dashboard
Your final option, if you are still having problems, is to use the createRequest method on the Http.Request object, which gives you complete control over the Request object you are creating. The signature looks like this
createRequest
public static Http.Request createRequest(java.lang.String _remoteAddress,
java.lang.String _method,
java.lang.String _path,
java.lang.String _querystring,
java.lang.String _contentType,
java.io.InputStream _body,
java.lang.String _url,
java.lang.String _host,
boolean _isLoopback,
int _port,
java.lang.String _domain,
boolean _secure,
java.util.Map<java.lang.String,Http.Header> _headers,
java.util.Map<java.lang.String,Http.Cookie> _cookies)
To tell you first, i have tried and tried it again and now i need some help
Heres my code
package staticPkg;
public class Static {
public static final String staticMethod() {
System.out.println("Static method called");
return "Static called";
}
}
package staticPkg;
public class TargetClass {
Static staticClass;
public String callHere() {
return Static.staticMethod();
}
}
package staticPkg;
import org.easymock.EasyMock;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.testng.IObjectFactory;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.ObjectFactory;
import org.testng.annotations.Test;
#PrepareForTest({Static.class})
public class TestClass {
Static staticClass = null;
#ObjectFactory
public IObjectFactory getObjectFactory() {
System.out.println("got object factory");
return new org.powermock.modules.testng.PowerMockObjectFactory();
}
#BeforeMethod
public void setup() {
System.out.println("print me");
PowerMock.mockStatic(Static.class);
staticClass = PowerMock.createMock(Static.class);
}
#Test
public void testMe() {
EasyMock.expect(Static.staticMethod()).andReturn("Mock called").anyTimes();
PowerMock.replay(Static.class,staticClass);
TargetClass tc = new TargetClass();
String output = tc.callHere();
PowerMock.verify(Static.class,staticClass);
System.out.println(output);
}
}
And heres the log
[Parser] Running:
C:\MockWorkspace\Mock\temp-testng-customsuite.xml
got object factory
print me
Static method called
FAILED: testMe
java.lang.IllegalStateException: no last call on a mock available
at org.easymock.EasyMock.getControlForLastCall(EasyMock.java:521)
at org.easymock.EasyMock.expect(EasyMock.java:499)
at staticPkg.TestClass.testMe(TestClass.java:46)
... Removed 22 stack frames
===============================================
staticPkg.TestClass
Tests run: 1, Failures: 1, Skips: 0
===============================================
===============================================
Mock
Total tests run: 1, Failures: 1, Skips: 0
===============================================
Help please, i have tried a variety of solutions, can't get it done.
Please can anyone try this code and correct it for success?
I get error in EasyMock.expect ...............
Got a work around at http://blogs.bytecode.com.au/glen/2006/10/12/doing-bytecode-kungfu-with-javassist.html
And it works
But wait..........I am stuck again
My testcase works fine when runs alone, but when run with Ant, it gives problem. Might be other test cases of different files are interfering.
I got the same error, when my individual test case was using #PrepareTest & easymock/powermock
[testng] ====================STATIC CALLED===========================
[testng] javassist.CannotCompileException: by java.lang.LinkageError: loader (instance of sun/misc/Launcher$AppClass
Loader): attempted duplicate class definition for name: "com/symantec/mobius/aggregator/submission/SubmissionFactory"
[testng] at javassist.ClassPool.toClass(ClassPool.java:1085)
[testng] at javassist.ClassPool.toClass(ClassPool.java:1028)
[testng] at javassist.ClassPool.toClass(ClassPool.java:986)
[testng] at javassist.CtClass.toClass(CtClass.java:1110)
Try extending from PowerMockTestCase. The TestNG support will also be updated in next version of PowerMock (1.4.9).
I faced this same issue, and struggled a lot. Finally, found the following solution:
Another alternative is to set the object-factory to org.powermock.modules.testng.PowerMockObjectFactory in the TestNG suite.xml. Here is a sample suite file:
<suite name="dgf" verbose="10" object-factory="org.powermock.modules.testng.PowerMockObjectFactory">
<test name="dgf">
<classes>
<class name="com.example.ClientTest"/>
</classes>
</test>
</suite>
Of course, you can also extend your test case from PowerMockTestCase as told by Johan.
Mock all the static methods in static class before proceeding to mock the static method. Try with this:
#Test
public void testMe() {
PowerMock.mockStatic(Static.class);
EasyMock.expect(Static.staticMethod()).andReturn("Mock called").anyTimes();
PowerMock.replay(Static.class,staticClass);
TargetClass tc = new TargetClass();
String output = tc.callHere();
PowerMock.verify(Static.class,staticClass);
System.out.println(output);
}