I have created a REST API at URL: http://localhost:8888/rest/contacts with this JSON output:
{
"contact": {
"address": [
{
"city":"Shanghai",
"street":"Long Hua Street"
},
{
"city":"Shanghai",
"street":"Dong Quan Street"
}
],
"id": "huangyim",
"name": "Huang Yi Ming"
}
}
I want to print only the id value in a smartGWT ListGrid.
public class ExampleEntry implements EntryPoint {
#Override
public void onModuleLoad() {
DataSource dataSource = new DataSource();
dataSource.setDataFormat(DSDataFormat.JSON);
dataSource.setDataURL("http://localhost:8888/rest/contacts");
dataSource.setRecordXPath("/contact");
DataSourceTextField field = new DataSourceTextField("id", "id");
dataSource.addField(field);
final ListGrid grid = new ListGrid();
grid.setDataSource(dataSource);
grid.setAutoFetchData(true);
grid.draw();
}
}
But it is throwing the following exception:
15:33:12.766 [ERROR] [jerseyexample] 15:33:12.747:XRP2:WARN:RPCManager:xmlHttpRequest.getAllResponseHeaders() returned null
com.smartgwt.client.core.JsObject$SGWT_WARN: 15:33:12.747:XRP2:WARN:RPCManager:xmlHttpRequest.getAllResponseHeaders() returned null
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:105)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessages(BrowserChannelServer.java:293)
at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:547)
at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:364)
at java.lang.Thread.run(Unknown Source)
I tried searching google to find a fix but that did not help. Please let me know if anyone knows a solution for this issue.
You just need to change the data url, instead of using an absolute path use a relative one.
change
dataSource.setDataURL("http://localhost:8888/rest/contacts");
to
dataSource.setDataURL("rest/contacts");
This is also neccesary when you'll have to deploy it to a remote server.
I recommend you use a RestDataSource instead of a plain DataSource, it has been designed specificaly for REST services, as you've said you use.
Using a RestDataSource is as simple as using DataSource.
#Override
public void onModuleLoad() {
RestDataSource dataSource = new RestDataSource();
dataSource.setDataFormat(DSDataFormat.JSON);
dataSource.setDataURL("rest/contacts");
dataSource.setRecordXPath("/contact");
DataSourceTextField field = new DataSourceTextField("id", "id");
dataSource.addField(field);
OperationBinding get=new OperationBinding();
get.setOperationType(DSOperationType.FETCH);
dataSource.setOperationBindings(get);
final ListGrid grid = new ListGrid();
grid.setDataSource(dataSource);
grid.setAutoFetchData(true);
grid.draw();
}
You can map each OperationBinding with each http method (GET, POST PUT, DELETE) or whatever suits your REST API.
Cheers!
You can put directly Xpath in the field you want to map
RecordXPath can be specified directly on the DataSource for a simple read-only DataSource only capable of "fetch" operations.
field.setRecordXPath("contact")
Related
im trying to read from my json file, i had it in root, but when i package to jar, the file dont come with. Now i put the json file in "resource" folder.
My code:
#Component
class DefaultData {
#Autowired
private lateinit var gameOfThronesService: GameOfThronesService
#PostConstruct
fun initializeDefault() {
val reader = JsonReader(FileReader("game-of-thrones.json"))
val gameofthronesCharacters: List<GameOfThronesDto> = Gson().fromJson(reader, object : TypeToken<List<GameOfThronesDto>>() {}.type)
println("-----> JSON Data <-----")
gameofthronesCharacters.forEach{ println(it) }
gameOfThronesService.createCharactersFromJson(gameofthronesCharacters)
}
}
This worked when i had the json file in root, but it cant find it in "resource" folder, how to solve this?
I also tried: How to read a text file from resources in Kotlin?
Then i get this following error:
(File name too long)
at java.io.FileInputStream.open0(Native Method) ~[na:1.8.0_181]
at java.io.FileInputStream.open(FileInputStream.java:195) ~[na:1.8.0_181]
at java.io.FileInputStream.<init>(FileInputStream.java:138) ~[na:1.8.0_181]
at java.io.FileInputStream.<init>(FileInputStream.java:93) ~[na:1.8.0_181]
at java.io.FileReader.<init>(FileReader.java:58) ~[na:1.8.0_181]
at com.ahmmud16.gameofthrones.util.DefaultData.initializeDefault(DefaultData.kt:24) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_181]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_181]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_181]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_181]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:366) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:309) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:136) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
... 18 common frames omitted
To read a file from the resources folder, you should be following this answer here. You tried it, but not in the correct way.
When doing this:
val fileContent = this::class.java.classLoader.getResource("game-of-thrones.json").readText(), you are reading the contents of the file. You are then passing the whole file content to FileReader as if it was the file name (that's why you're getting a File name too long error).
From what I'm seeing in the Gson documentation, you can skip the creating of a JsonReader completely, and pass a String to fromJson().
Can you try the following:
#Component
class DefaultData {
#Autowired
private lateinit var gameOfThronesService: GameOfThronesService
#PostConstruct
fun initializeDefault() {
val fileContent = this::class.java.classLoader.getResource("game-of-thrones.json").readText()
val gameofthronesCharacters: List<GameOfThronesDto> = Gson().fromJson(fileContent, object : TypeToken<List<GameOfThronesDto>>() {}.type)
println("-----> JSON Data <-----")
gameofthronesCharacters.forEach{ println(it) }
gameOfThronesService.createCharactersFromJson(gameofthronesCharacters)
}
}
Can someone please let me know how to configure the maxFileSize for fileUploads in Jodd, when using Joy?
I've tried in joy.props, even under [joy.madvoc] section with the earlier working:
madvocConfig.fileUploadFactory.maxFileSize=-1
But have no luck :(
Another question is how to force it, to report error, as without it, got:
java.lang.NullPointerException
com.mycircle.action.CircleAction.add(CircleAction.java:78)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
jodd.madvoc.ActionRequest.invokeActionMethod(ActionRequest.java:256)
jodd.madvoc.ActionRequest.lambda$createExecutionArray$1(ActionRequest.java:226)
jodd.madvoc.ActionRequest.invoke(ActionRequest.java:240)
jodd.madvoc.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:79)
jodd.madvoc.interceptor.ActionInterceptor.apply(ActionInterceptor.java:38)
jodd.madvoc.ActionRequest.invoke(ActionRequest.java:240)
jodd.joy.i18n.I18nInterceptor.intercept(I18nInterceptor.java:46)
jodd.madvoc.interceptor.ActionInterceptor.apply(ActionInterceptor.java:38)
jodd.madvoc.ActionRequest.invoke(ActionRequest.java:240)
jodd.madvoc.ActionRequest.lambda$createExecutionArray$0(ActionRequest.java:209)
jodd.madvoc.ActionRequest.invoke(ActionRequest.java:240)
jodd.madvoc.component.MadvocController.invoke(MadvocController.java:163)
jodd.madvoc.MadvocServletFilter.doFilter(MadvocServletFilter.java:109)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
jodd.decora.DecoraServletFilter.doFilter(DecoraServletFilter.java:144)
After debugging, I figured out that is due to file size limitation 100240 bytes defined in FileUploadFactory and AdaptiveFileUploadFactory as well.
I have a #In FileUpload image; in CircleAction and it become null due to this.
Here is how to do so:
from Joy get to the Madvoc
in Madvoc get the FileUploader component - it's a new one that simply holds a FileUploadFactory instance.
Use it:)
Something like this:
public class MyWebApplication extends JoyContextListener {
#Override
protected JoddJoy createJoy() {
final JoddJoy joy = super.createJoy();
joy.withWebApp(webApp -> {
webApp.withRegisteredComponent(FileUploader.class, fileUploader -> {
AdaptiveFileUploadFactory adaptiveFileUploadFactory =
(AdaptiveFileUploadFactory) fileUploader.get();
adaptiveFileUploadFactory.setMaxFileSize(10000000);
});
});
return joy;
}
}
The seccond way is to use registerComponent and simply pass your implementation of FileUploader.
Atm, it is not possible to set this value from the madvoc config, but I will fix that soon. There is no more madvocConfig - instead you can set each component. So you will be able to do so like this: fileUploader.maxFileSize (after the fix:).
I am using Easymock with Powermock. When I try to test, this is the error I get.
java.lang.RuntimeException: Invoking the beforeTestMethod method on PowerMock test listener org.powermock.api.extension.listener.AnnotationEnabler#959a1da3 failed.
at org.powermock.tests.utils.impl.PowerMockTestNotifierImpl.notifyBeforeTestMethod(PowerMockTestNotifierImpl.java:95)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:298)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:131)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.access$100(PowerMockJUnit47RunnerDelegateImpl.java:59)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner$TestExecutorStatement.evaluate(PowerMockJUnit47RunnerDelegateImpl.java:147)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.evaluateStatement(PowerMockJUnit47RunnerDelegateImpl.java:107)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:288)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:208)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:147)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:121)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:123)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:121)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.IllegalArgumentException: Cannot subclass final class class java.lang.String
at org.easymock.cglib.proxy.Enhancer.generateClass(Enhancer.java:446)
at org.easymock.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
at org.easymock.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216)
at org.easymock.cglib.proxy.Enhancer.createHelper(Enhancer.java:377)
at org.easymock.cglib.proxy.Enhancer.createClass(Enhancer.java:317)
at org.easymock.internal.ClassProxyFactory.createProxy(ClassProxyFactory.java:175)
at org.easymock.internal.MocksControl.createMock(MocksControl.java:113)
at org.easymock.internal.MocksControl.createMock(MocksControl.java:98)
at org.easymock.EasyMock.mock(EasyMock.java:128)
at org.easymock.EasyMock.createMock(EasyMock.java:259)
at org.easymock.internal.Injector.createMocksForAnnotations(Injector.java:130)
at org.easymock.internal.Injector.injectMocks(Injector.java:66)
at org.easymock.EasyMockSupport.injectMocks(EasyMockSupport.java:528)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:95)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:56)
at java.lang.reflect.Method.invoke(Method.java:620)
at org.powermock.reflect.internal.WhiteboxImpl.performMethodInvocation(WhiteboxImpl.java:1899)
at org.powermock.reflect.internal.WhiteboxImpl.doInvokeMethod(WhiteboxImpl.java:801)
at org.powermock.reflect.internal.WhiteboxImpl.invokeMethod(WhiteboxImpl.java:781)
at org.powermock.reflect.Whitebox.invokeMethod(Whitebox.java:466)
at org.powermock.api.extension.listener.AnnotationEnabler.beforeTestMethod(AnnotationEnabler.java:71)
at org.powermock.tests.utils.impl.PowerMockTestNotifierImpl.notifyBeforeTestMethod(PowerMockTestNotifierImpl.java:93)
... 24 more
And my class looks like this.
public String renameOrDeleteDirectory(String Directory, String dirExtn, (short) x){
File workDir = new File(Directory);
String OrigDir = null;
File origDir =null;
boolean renamed = false;
try {
if (null != Directory && Directory.length() > 0 ) {
if(new File(Directory).list().length == 0){
new File(Directory).delete();
}
My test case is like this...
#RunWith(PowerMockRunner.class)
#PrepareForTest(value={Utilities.class, File.class})
public class dirTest1 {
#Test
public void testRenameOrDeleteDirectory1() throws Exception {
mockStatic(File.class);
expectNew(File.class, "C:\\Users\\Desktop\\Docs\\Docs2017_03_07_14_docready").andReturn(workDir);
expect(workDir.list().length == 0).andReturn(true);
expect(workDir.delete()).andReturn(true);
// expect(null != Directory && Directory.length() > 0).andReturn(true);
// expect(new File(Directory).list().length == 0).andReturn(true);
// expect(new File(Directory).delete()).andReturn(true);
PowerMock.replay(File.class, workDir);
Utilities utilities = new Utilities();
utilities.renameOrDeleteDirectory("C:\\Users\\Desktop\\Docs\\Docs2017_03_07_14_docready", "_Ready", (short) 0);
PowerMock.verify(File.class, workDir);
}
}
Hint: your real problem is that you are using new all over the place within your production code. That simply creates hard to test code. And thus you end up looking for PowerMock.
Alternatively, you could create a simple
class FileFactory {
File getFileFor(String fileName) { ...
and use that as field within your class. Now, when you need a File for a certain string, you use that FileFactory instance.
The really nice thing here: that FileFactory can be mocked easily.
So instead of needing PowerMock and all its quirks, you could
improve your design
do full unit-testing ... just with frameworks like EasyMock or Mockito
I solved this error.
It was caused because I was mocking a string along with other mocks.
I have an Spring MVC4 web application:
It has one controller class as follows -
#Controller
public class SeleniumController
{
#Autowired
SeleniumService seleniumService;
#RequestMapping(value={"/service/echo"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
#ResponseBody
public String echo() {
System.out.println("Inside Echo .. ");
return "echo";
}
#RequestMapping(value={"/service/changeAddress"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
#ResponseBody
public AddressChangeRequest changeAddress(#RequestBody AddressChangeRequest req) {
System.out.println("Inside AddressChange .. ");
try
{
this.seleniumService.openOipaAddressScreenRemote(req.getPolicyNumber(), req.getCaseId(), req.getTaskId(), req.getAssignedTo());
}
catch (MalformedURLException e) {
e.printStackTrace();
return req;
}
return req;
}
}
And a service class -
#Service("oipaService")
public class SeleniumService {
private static final String HUB_URL = "http://10.227.181.36:4444/wd/hub";
public void openOipaAddressScreenRemote(String policyNumber, String caseID, String taskID, String assignedTo) throws MalformedURLException {
System.out.println("Policy number input : " + policyNumber);
String oipaURL = "https://myDom.com/PASJava_Term";
DesiredCapabilities caps = DesiredCapabilities.internetExplorer();
caps.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
WebDriver driver = new RemoteWebDriver(new URL(HUB_URL), caps);
WebDriverWait wait = new WebDriverWait(driver, 60);
Actions oAction = new Actions(driver);
driver.get(oipaURL);
}
}
Selenium related jars used in service class are as follows -
I have selenium hub set up at 10.227.181.36:4444
and a node in client system. jars used to set up selenium hub and node is-
selenium-server-standalone-2.53.1.jar
My goal is to post json data to REST controller from client and initiate selenium test in client browser.
And it works fine when the spring application is hosted in apache-tomcat-7(windows) and hub is set up in windows machine (jdk1.7.0_55) and node in windows machine (jdk1.7.0_55 or greater).
But When I am hosting the app in weblogic 12C(unix) and setting up hub in unix system (jdk1.7.0_55) and node in windows(jdk1.7.0_55 or greater), I get following error after posting a json to my rest service-
java.lang.NoSuchMethodError: com.google.common.collect.Multimaps.transformValues(Lcom/google/common/collect/ListMultimap;Lcom/google/common/base/Function;)Lcom/google/common/collect/ListMultimap;
at com.google.common.net.MediaType.toString(MediaType.java:708)
at org.openqa.selenium.remote.http.JsonHttpCommandCodec.encode(JsonHttpCommandCodec.java:197)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:130)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:572)
at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:240)
at org.openqa.selenium.remote.RemoteWebDriver.(RemoteWebDriver.java:126)
at org.openqa.selenium.remote.RemoteWebDriver.(RemoteWebDriver.java:153)
at com.cts.bpaas.service.SeleniumService.openOipaAddressScreenRemote(SeleniumService.java:229)
at com.cts.bpaas.soe.controller.SeleniumController.changeAddress(SeleniumController.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:855)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:751)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:844)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:280)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:254)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:136)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:341)
at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:25)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:79)
at com.cts.bpaas.soe.filter.SoECORSFilter.doFilter(SoECORSFilter.java:32)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:79)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3367)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3333)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:57)
at weblogic.servlet.internal.WebAppServletContext.doSecuredExecute(WebAppServletContext.java:2220)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2146)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2124)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1564)
at weblogic.servlet.provider.ContainerSupportProviderImpl$WlsRequestExecutor.run(ContainerSupportProviderImpl.java:254)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:295)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:254)</font>
The GET method on /service/echo is working for both set up, but POST method on /service/changeAddress is not working for unix set up.
What am I missing?
Figured it wasn't a issue with selenium. Problem was deploying the application in weblogic 12c. guava.jar was present in both my application and weblogic, I just had to made a little change in weblogic.xml to tell weblogic to take my jar, not weblogic's.
<?xml version="1.0" encoding="UTF-8"?>
<wls:weblogic-web-app xmlns:wls="http://xmlns.oracle.com/weblogic/weblogic-web-app" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd
http://xmlns.oracle.com/weblogic/weblogic-web-app
http://xmlns.oracle.com/weblogic/weblogic-web-app/1.4/weblogic-web-app.xsd">
<wls:context-root>/csoe_rest</wls:context-root>
<wls:container-descriptor>
<wls:prefer-application-packages>
<wls:package-name>com.google.common.*</wls:package-name>
</wls:prefer-application-packages>
</wls:container-descriptor>
</wls:weblogic-web-app>
It worked like a charm
I am new to mockito and i want to make a unit test for user validation. Please find below the method i want to perform the unit test:
#RequestMapping(method = RequestMethod.POST, value = "/login")
public ModelAndView validateViewLogin(#ModelAttribute Person person,
BindingResult result, HttpServletRequest request) {
ModelAndView mav = new ModelAndView();
String userName = person.getFirstName();
String password = person.getPassword();
boolean isUserValid = false;
if (userName != null && password != null) {
isUserValid = userManagerService.validateUserLogin(userName,
password);
}
if (!isUserValid) {
mav.setViewName("home");
return mav;
}
mav.addObject("isUserValid", isUserValid);
mav.setViewName("login");
return mav;
}
As you can see above isUserValid method returns a boolean and my method i want to test returns a ModelAndView.
Please see my unit test below:
`#Test public void testValidateOk() {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
Person person = new Person();
ModelAndView mav = new ModelAndView();
mav.setViewName("login");
person.setFirstName("John");
person.setPassword("123");
LogInController controller = new LogInController();
UserManagerServiceImpl mockpdao = mock(UserManagerServiceImpl.class);
ReflectionTestUtils.setField(controller, "userManagerService", mockpdao);
// given
given(controller.validateViewLogin(person, result, request)).willReturn(mav);
// when
ModelAndView validateViewLogin=
controller.validateViewLogin(person, result, request);
// then
assertEquals("home", validateViewLogin.getViewName());
}`
when i run my unit test i get the following error:
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
ModelAndView cannot be returned by validateUserLogin()
validateUserLogin() should return boolean
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. This exception might occur in wrongly written multi-threaded tests.
Please refer to Mockito FAQ on limitations of concurrency testing.
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies -
- with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.
at com.gemstone.presentation.LogInControllerTest.testValidateOk(LogInControllerTest.java:49)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Any ideas how i can resolve this issue please?
I'm not familiar with BDD style Mockito, but I'm guessing that the line
given(controller.validateViewLogin(person, result, request)).willReturn(mav);
means that you are asking the controller to return the given model and view whenever the validateViewLogin method is called with the specified person, result and request. However the controller is not a mock, so this may be what is causing your error. What you should be doing instead is specifying the behaviour of how your mock user manager service should behave.
I notice that you are creating a mock of the UserManagerServiceImpl class. Given that it ends with 'Impl' I am guessing that there is a correspondng UserManagerService interface that you could mock instead. Mocktio can mock concrete classes, but it can not do this as easily as mocking an interface. Therefore if there is indeed an interface then I would mock that instead just to be safe.
You are injecting your mock using ReflectionTestUtils. This probably isn't the cause of your error, but if it is possible for you to do so then I'd recommend adding a public setter to your controller to inject it more safely and easily.
Taking the above points, I would write your test like the following:
#Test public void validateViewLogin_validLogin_returnsHomePage() {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
Person person = new Person();
person.setFirstName("John");
person.setPassword("123");
LogInController controller = new LogInController();
UserManagerService mockUserService = mock(UserManagerService.class);
// Configure mock user service to accept the person
when(mockUserService.validateUserLogin("John", "123")).thenReturn(true);
// Inject mock user service into controller
controller.setUserManagerService(mockUserService);
// Attempt the validation
ModelAndView mav =
controller.validateViewLogin(person, result, request);
// Check the result
assertEquals("home", mav.getViewName());
}
Since I'm not familiar with the BDD syntax I have configured the mock using the line
when(mockUserService.validateUserLogin("John", "123")).thenReturn(true);
but I assume that this is equivalent to
given(mockUserService.validateUserLogin("John", "123")).willReturn(true);