Can not remove the modifier of final class - junit

I want to remove final key word of 1 class. I'm writting Junit for this class and I call spy of Mockito to mock a method to return an expect values to cover all cases.
After using:
CtClass ctClazz = ClassPool.getDefault().get(Livre.class.getName());
ctClazz.setModifiers(ctClazz.getModifiers() & ~Modifier.FINAL);
ctClazz.writeFile();
The modifier of this class is 17 but I think it should be 1 (public).
And I got the error:
Caused by: java.lang.IllegalArgumentException: Cannot subclass final class class mediatheque.document.Livre
at net.sf.cglib.proxy.Enhancer.generateClass(Enhancer.java:446)
at net.sf.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
at net.sf.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216)
at net.sf.cglib.proxy.Enhancer.createHelper(Enhancer.java:377)
at net.sf.cglib.proxy.Enhancer.createClass(Enhancer.java:317)
at org.powermock.api.easymock.internal.signedsupport.SignedSupportingClassProxyFactory.createProxy(SignedSupportingClassProxyFactory.java:147)
at org.easymock.internal.MocksControl.createMock(MocksControl.java:40)
at org.easymock.classextension.internal.MocksClassControl.createMock(MocksClassControl.java:43)
at org.powermock.api.easymock.PowerMock.doMock(PowerMock.java:2076)
at org.powermock.api.easymock.PowerMock.createMock(PowerMock.java:79)
at org.powermock.api.easymock.PowerMock.createPartialMock(PowerMock.java:765)
at test.mediatheque.document.TestDocument.testRestituer_With_Exception3(TestDocument.java:379)
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.internal.runners.TestMethod.invoke(TestMethod.java:68)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$2.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:217)
... 19 more
This final class extends from an abstract class.
Thanks for any help.

You cannot extend (subclass) a final class. If you really need to do so (whether for testing or because you really need to override a method in someone else's library), you'll have to 'fork' the class. Copy its contents into a new class (updating package declaration and class references), and remove the final designation there. Then, you can extend it to your heart's content. I've used this approach quite effectively recently with respect to Spring Security.

Related

Prevent Jackson from setting links field null when the client sends "_links" : null (links inherited from spring-hateoas RepresentationModel class)

I have Spring Boot API that uses spring-hateoas.
I have a domain class that is used for request and response in my controller. The domain class inherits from spring-hateoas class RepresentationModel, therefore it contains a "links" field.
For some reason (that I cannot control) a client is sending "_links": null in the request which is forcing links field to be null, after it had been properly initialized with an empty List. See RepresentationModel.java
Null links field in the request is causing issues in my application:
Caused by: java.lang.IllegalArgumentException: Links must not be null!
at org.springframework.util.Assert.notNull(Assert.java:201) ~[spring-core-5.3.8.jar:5.3.8]
at org.springframework.hateoas.Links.<init>(Links.java:54) ~[spring-hateoas-1.2.6.jar:1.2.6]
at org.springframework.hateoas.Links.of(Links.java.79) ~[spring-hateoas-1.2.6.jar:1.2.6]
at org.springframework.hateoas.RepresentationModel.getLinks(RepresentationModel.java:210) ~[spring-hateoas-1.2.6.jar:1.2.6]
at sun.reflect.GeneratedMethodAccesor158.invoke(Unknown Source) ~[na:na]
at sun.reflect.DelegatingMethodAccesorImpl.invoke(DelegatingMethodAccesorImpl.java:43) ~[na:1.8.0_292]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_292]
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:689) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter.serializeAsField(SimpleBeanPropertyFilter.java:208) ~[jackson-databind-2.11.4.jar:2.11.4]
One thing I tried was configuring Jackson to ignore links field on marshalling (#JsonIgonoreProperties) but this is also affecting my response by removing HATEOAS links from it (this Jackson configuration is application wide)
Looking at RepresentationModel class from spring-hateoas, seems like links field is designed not to be handled directly. It is updated only through the corresponding methods in RepresentationModel after it was initialized.
I was able to reinitialize links field through reflection.
try {
Field field = obj.getClass().getSuperClass().getDeclaredField("links");
field.setAccessible(true);
field.set(obj, new ArrayList<>());
field.setAccessible(false);
} catch (Exception e) {
e.printStackTrace(e);
}
Is there a better way to reinitialize HATEOAS links field in a RepresenationModel object which already has null links?
Is there a better approach to prevent the client request from affecting the incoming object this way?

How to avoid WARN messages about ReflectionsException

how can I avoid WARN messages to be displayed in logs (without putting the log4j level to ERROR) when I launch Confluent ?
I have set up my plugin.path variable in the properties file with value ${CONFLUENT_HOME}/share/java/kafka-connect-jdbc (with final comma).
I tried to put in the classpath the kafka-connect-jdbc repository, without success.
The following is just an example a small part of the log file:
[2018-07-10 15:40:30,168] INFO Reflections took 1 ms to scan 1 urls, producing 5 keys and 6 values [using 1 cores] (org.reflection
s.Reflections)
[2018-07-10 15:40:30,170] WARN could not get type for name org.jmock.Mockery from any class loader (org.reflections.Reflections)
org.reflections.ReflectionsException: could not get type for name org.jmock.Mockery
at org.reflections.ReflectionUtils.forName(ReflectionUtils.java:390)
at org.reflections.Reflections.expandSuperTypes(Reflections.java:381)
at org.reflections.Reflections.<init>(Reflections.java:126)
at org.apache.kafka.connect.runtime.isolation.DelegatingClassLoader$InternalReflections.<init>(DelegatingClassLoader.java:
365)
at org.apache.kafka.connect.runtime.isolation.DelegatingClassLoader.scanPluginPath(DelegatingClassLoader.java:277)
at org.apache.kafka.connect.runtime.isolation.DelegatingClassLoader.scanUrlsAndAddPlugins(DelegatingClassLoader.java:216)
at org.apache.kafka.connect.runtime.isolation.DelegatingClassLoader.registerPlugin(DelegatingClassLoader.java:208)
at org.apache.kafka.connect.runtime.isolation.DelegatingClassLoader.initPluginLoader(DelegatingClassLoader.java:177)
at org.apache.kafka.connect.runtime.isolation.DelegatingClassLoader.initLoaders(DelegatingClassLoader.java:154)
at org.apache.kafka.connect.runtime.isolation.Plugins.<init>(Plugins.java:56)
at org.apache.kafka.connect.cli.ConnectStandalone.main(ConnectStandalone.java:77)
Caused by: java.lang.ClassNotFoundException: org.jmock.Mockery
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at org.reflections.ReflectionUtils.forName(ReflectionUtils.java:388)
... 10 more
That does not seem causing any issues, but can be confusing to read about it.
Have you got any suggestions about that ?
Thanks in advance,
Diego
You can set log level for particular package in log4j config file:
log4j.logger.org.reflections=ERROR
This helped me

JUnit testing using ContainsAll-assertion

I'm testing a search function in the booking system I recently coded for my first semester project. My idea to test this was: I let the original search method return an arraylist of customers found in the search, fetch the list of all customers, and if the list of all customers contains the arraylist of customers found in the search, I assert that this works.
Note: I am prior creating a specific entry which I know I will find (hopefully, right?).
My problem is that when I call -
assertTrue(allCustomers.containsAll(searchResults));
- I get an error:
junit.framework.AssertionFailedError
at TestPackages.newBookingControllerTest.testOnEnter(newBookingControllerTest.java:98)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:86)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:74)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:211)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:67)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Can anyone elaborate on why this happens? I can edit some source code in if you need. Thanks!
AssertEquals takes two parameter, so you may see compilation error.
You should be using
assertTrue(allCustomers.contains(searchResults));//meaning allCustomers indeed contains searchResults
OR
assertEquals(allCustomers.contains(searchResults), true);//Meaning boolean returned by contains api is going to be compared with true

When use composite component Myfaces throws exception "Cannot cast UIpanel to panelGroup"

I made some research and i found a guy who have the same problem below(Its is in portugueshttps://groups.google.com/forum/#!topic/javasf/OBPyBP6Sfjs) but the site that he gave dont exist anymore and he don't answer my email for 2 days so...
Problem is: whenever i use an composite component i got that exception (even if they are empty just for test):
javax.servlet.ServletException: javax.faces.component.UIPanel cannot
be cast to javax.faces.component.html.HtmlPanelGroup
javax.faces.webapp.FacesServlet.service(FacesServlet.java:606)
org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:147)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
root cause
java.lang.ClassCastException: javax.faces.component.UIPanel cannot be
cast to javax.faces.component.html.HtmlPanelGroup
org.apache.myfaces.shared.renderkit.html.HtmlGroupRendererBase.encodeEnd(HtmlGroupRendererBase.java:65)
javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
javax.faces.component.UIComponent.encodeAll(UIComponent.java:1786)
org.apache.myfaces.renderkit.html.HtmlCompositeComponentRenderer.encodeEnd(HtmlCompositeComponentRenderer.java:71)
javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
javax.faces.component.UIComponent.encodeAll(UIComponent.java:1786)
javax.faces.component.UIComponent.encodeAll(UIComponent.java:1782)
javax.faces.component.UIComponent.encodeAll(UIComponent.java:1782)
com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:402)
org.apache.myfaces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:285)
com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:147)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
For me look likes that when you use an composite, myfaces try to generate an panel and for some reason the exception is throwed, and just to remember that i made this test with the body having only the composite and composite itself is empty(with interface and implementation sections).
I am using Myfaces 2.1.11, tomcat 7(pluging for maven), jsf 2.0, hibernate.

drools persistence with mysql, can't get process instance

I'm stumped. I'm trying to implement persistence with Drools-flow, and I'd like to grab the value of a property on a workitem / processinstance, but everytime I try to get the workitem or process instance I end up with the stack trace below.
I'm walking through the source and from what I can tell, this happens anytime I try and grab a property that is annotated with #Lob in an entity class.
My environment is hibernate/mysql/JPA persistence using BTM as a transaction manager.
I'm calling getProcessInstance as follows:
ksession = JPAKnowledgeService.loadStatefulKnowledgeSession(ksession.getId(), m_kbase, null, m_environment);
m_pi = ksession.getProcessInstance(m_pi.getId());
What am I doing wrong?
java.lang.NullPointerException
at java.io.ByteArrayInputStream.(ByteArrayInputStream.java:89)
at org.drools.persistence.processinstance.ProcessInstanceInfo.getProcessInstance(ProcessInstanceInfo.java:135)
at org.drools.persistence.processinstance.JPAProcessInstanceManager.getProcessInstance(JPAProcessInstanceManager.java:62)
at org.drools.common.AbstractWorkingMemory.getProcessInstance(AbstractWorkingMemory.java:1793)
at org.drools.impl.StatefulKnowledgeSessionImpl.getProcessInstance(StatefulKnowledgeSessionImpl.java:261)Hibernate: select at org.drools.command.runtime.process.GetProcessInstanceCommand.execute(GetProcessInstanceCommand.java:29)
at org.drools.command.runtime.process.GetProcessInstanceCommand.execute(GetProcessInstanceCommand.java:12)
at org.drools.persistence.session.SingleSessionCommandService.execute(SingleSessionCommandService.java:254)
at org.drools.command.impl.CommandBasedStatefulKnowledgeSession.getProcessInstance(CommandBasedStatefulKnowledgeSession.java:95)
at com.thoughtvine.tracks.workflow.TracksFlow.getParameterFromWorkItem(TracksFlow.java:182)
at com.thoughtvine.tracks.workflow.test.TestTracksFlow.testGetWorkItem(TestTracksFlow.java:118)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
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.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:73)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:46)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:180)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:41)
at org.junit.runners.ParentRunner$1.evaluate(ParentRunner.java:173)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.junit.runners.ParentRunner.run(ParentRunner.java:220)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:46)
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)
I'm not an expert on these things... but often LOBs are treated quite differently, is it possible your LOB's actual retrieval is being deferred and thus you are getting a null point when trying to read from it (With the ByteArrayInputStream)?
Might be a setting in the JPA config... As I said, this is a theoretical possibilty