How to use KoinTestRule without getting "A KoinContext is already started"? - koin

I am trying to use Koin's test rule to start and stop Koin with test modules, however every time I try use this rule or startKoin() I get "A KoinContext is already started". I initially start Koin in the application class, which may have something to do with the issue, but I'm not sure myself how to get around this. Any help on this matter would be appreciated.
Application:
override fun onCreate() {
super.onCreate()
startKoin {
androidContext(this#Application)
modules(repositoryModule, daoModule, viewModelModule, wrapperModule)
}
}
Test:
#get:Rule
val koinTestRule = KoinTestRule.create {
modules(repositoryTestModule)
}
Repository Test Module:
val repositoryTestModule = module {
single<JournalRepository> { FakeJournalRepository() }
}

I managed to fix this issue by creating a custom test application and overriding the onCreate and onTerminate methods, starting and stopping Koin respectively. By not loading any modules in the Application I can load the modules needed by each class.
If there is a better solution I would love to hear it. Thanks

Related

Rendering GORM classes from Spring Boot

I'm trying to write a simple Spring Boot controller that renders a GORM instance and failing.
Here's a shortened version of my code:
#RestController
#RequestMapping("/user")
class UserController {
#RequestMapping(value='/test', method=GET)
User test() {
return new User(username: 'my test username')
}
}
I get the following error message:
Could not write JSON: No serializer found for class org.springframework.validation.DefaultMessageCodesResolver and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: users.domain.User["errors"]->grails.validation.ValidationErrors["messageCodesResolver"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.springframework.validation.DefaultMessageCodesResolver and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: users.domain.User["errors"]->grails.validation.ValidationErrors["messageCodesResolver"])
The error seems to be caused by extra properties injected by GORM. What is the proposed solution for this? Will this eventually be solved in gorm-hibernate4-spring-boot? Should I simply disable SerializationFeature.FAIL_ON_EMPTY_BEANS (I don't have a lot of experience with Jackson so I'm not entirely sure what side effects this may have)? Should I use Jackson's annotations to solve the problem? Any other options?
I've found a way to get rid of the error using this code:
#Component
class ObjectMapperConfiguration implements InitializingBean {
#Autowired
ObjectMapper objectMapper
#Override
void afterPropertiesSet() {
def validationErrorsModule = new SimpleModule()
validationErrorsModule.addSerializer(ValidationErrors, new ErrorsSerializer())
objectMapper.registerModule(validationErrorsModule)
}
}
class ErrorsSerializer extends JsonSerializer<ValidationErrors> {
#Override
void serialize(ValidationErrors errors, JsonGenerator jgen, SerializerProvider provider) {
jgen.writeStartObject()
jgen.writeEndObject()
}
}
Obviously this solution is far from perfect as it simply nukes all validation errors but right now it is good enough for me. I am pretty sure the Spring Boot team will have to address this issue eventually as the GORM objects are also being serialized with some internal Hibernate properties like attached. I'm not accepting this answer as it is not an acceptable solution for most scenarios, it basically just squelches the exception.
This did not work for me.
So I used this instead and the error disappeared.
#JsonIgnoreProperties(["errors"])
I'm using springBootVersion '1.4.1.RELEASE' with gorm & hibernate5:
compile("org.grails:gorm-hibernate5-spring-boot:6.0.3.RELEASE")
I am having to include the following at the top of each domain class in order to use them in a client response (i.e. json serialization using jackson):
#JsonIgnoreProperties(["errors", "metaClass", "dirty", "attached", "dirtyPropertyNames"])
When using springBootVersion '1.3.5.RELEASE' I was able to get away with:
#JsonIgnoreProperties(["errors"])
This is trending in the wrong direction :)

How to make a Thread pause in Spring mvc project?

I am using a Thread in Spring mvc project to do some background working.
What I have done is
I write a class which extends Thread. and I added init() method to start this class.
Whole ThreadTest.java is Below.
package org.owls.thread.vo;
public class ThreadTest extends Thread {
public void init(){
this.start();
}
public void pause(){
this.interrupt();
}
#Override
public void run() {
for(int i = 0; i < 100; i++){
try{
Thread.sleep(3000);
System.out.println("Thread is running : " + i);
} catch(Exception e){e.printStackTrace();}
}
}
};
edit root-context.xml intent to start this Thread as soon as possible when the server started.
<bean id="threadTest" class="org.owls.thread.vo.ThreadTest" init-method="init"/>
Now is the problem. I want to make a toggle button(pause/resume) in my home.jsp and When I click the button it works. But I do not know how can I access to the Thread, which already registered and run.
please, show me the way~>0<
P.S
additional question about java Thread.
What method exactly means pause and resume. I thought stop is the one similar to pause, but it is deprecated.
And start() is somehow feels like 'new()' not resume.
Thanks
I figured out how to control a thread.
if I want to pause(not stop), code should be like below.
thread.suspend();
And want to resume this from where it paused, like below.
thread.resume();
even though those methods are both deprecated.
(if somebody knows some replacement of these, reply please)
If you do not want to yellow warning in your spring project,
you can remove warning by simply add an annotation on that method.
annotation is #SuppressWarnings("deprecated").
=========================================================
From here, additional solutions based on my experience.
To make automatic executing Spring mvc Thread,
I did following steps.
make a simple Class which extends Thread class.
inside that class, make a method. this will be calles by
config files. in this method. I wrote code like "this.start();".
Let Spring knows we have a Thread class that should run independently
with Web activities. To do this, we have to edit root-context.xml.
Add a bean like this.
<bean id="threadTest" class="org.owls.thread.vo.ThreadTest" init-method="init"/>
init is the method name which generated by user in step 2.
Now we run this project Automatically Thread runs.
Controlling Thread is not relavent with Spring, I guess.
It is basically belongs to java rules.
I hope this TIP(?) will be helpful to people who just entered world of programming :-)

Multiple Threads in Xpages

I have a problem and hoped somone could help me
I'm trying to start multiple threads from an XAgent (not rendered XPage)
public class ImportThread extends NotesThread {
Session currentSession;
public ImportThread(String maildb, String Server)
{
try{
currentSession =DominoAccess.getCurrentSession();
this.maildb = currentSession.getDatabase(Server, maildb);
}catch (Exception e) {
e.printStackTrace();
}
}
public void runNotes()
{
View v = maildb.getView("$Calendar");
}
in this version I could not access the View I only get "null" back
Ive tryed a version with Java Threads not realy better.
thean i've found something on Openntf
http://www.openntf.org/internal/home.nsf/project.xsp?action=openDocument&name=Threads%20and%20Jobs
but there I got an "AccessControl Exception"
I have no more ideas, I hope that someone has an idea how to create
an XAgent with multiple thread
As Egor wrote you need the change the Java policy file if you run the Java code from an NSF. You don't have to do this if you deploy your Java code as OSGi plugin. See the documentation of that OpenNTF project.
Afaik NotesObjects should not be shared between threads. So instead of using Database mailDB you should use String mailDBName and instantiate all NotesObjects inside their own thread. You also need to watch run time: if your XAgent waits for the treads to conclude, you should be fine, but if it is a 'fire-and-forget' approach you need to start it from something more persistent like a managed bean in the session scope.
Hope that helps

JBehave - all steps marked pending?

I'm trying to create and run a simple JUnitStory to run a .story file.
I have this:
class Scenario1 extends JUnitStory {
#Delegate MySteps steps = new MySteps()
#Override
public Configuration configuration() {
return new MostUsefulConfiguration()
.useStoryLoader(new LoadFromRelativeFile(new File('src/test/groovy').toURL()))
.useStoryReporterBuilder(
new StoryReporterBuilder()
.withDefaultFormats()
.withFormats(Format.HTML, Format.CONSOLE, Format.TXT)
);
}
#Override
public List candidateSteps() {
final candidateSteps = new InstanceStepsFactory(configuration(), this).createCandidateSteps()
return candidateSteps;
}
}
With or without the delegate (copying and pasting in all the annotated methods of MySteps), whenever I run JBehave, I get the following output:
somePattern(){
// PENDING
}
It's like the individual stories don't pick up the steps.
When I create a "Stories" class and pull all the story files in with storyPaths, the individual steps are defined. Using a debugger, I see that candidateSteps is being hit, but it's not pulling in the data it needs to.
What could possibly be going on here?
You don't need to delegate to the Steps. And also you should not override candidateSteps, but rather stepsFactory. In later versions of JBehave, candidateSteps is deprecated, to make that preference for the factory method more prominent ( http://jbehave.org/reference/stable/javadoc/core/org/jbehave/core/ConfigurableEmbedder.html#candidateSteps() )
See this blog, where I explained how the basic JBehave configuration works in more detail:
http://blog.codecentric.de/en/2012/06/jbehave-configuration-tutorial/
Andreas
Here is your answer buddy:
The package of format has Changed.
This is the deprecated
import static org.jbehave.core.reporters.StoryReporterBuilder.Format.HTML;
This is the new one :)
import static org.jbehave.core.reporters.Format.HTML;
Took a while to find the answer, but was hidden on the jbehave documentation
Hope it helps!
Cheers!
You shouldn't need to use the #Delegate - your JUnitStory is not your Steps class. Can you try passing in steps where you have this?
When you pass in a class that has been bytecode manipulated for Steps classes, JBehave may not see the jbehave annotations anymore.
JBehave is old, underdeveloped technology. Don't use it.

Jmeter BSF using Groovy, Import one script's function to another

I use groovy in my Jmeter BSF, and sometimes I have functions that are used frequently enough to be moved to some script which I than can use as a library.
My approach was to create a file, say "library.groovy", and add there some function
public void function()
{
println("hello!");
}
and then use the following code in my BSF script
import library.groovy;
function();
Both files lie in the same dir, but script refuses to locate library. I also tried to explicitly wrap this function into class but I took no effect as well.
Can anyone suggest a solution for this?
Update:
I tried almost all possible solutions described in the internet. And everything that works in groovy console or Eclipse does not in Jmeter. Probably that is because of BSF. Anyone knows some workarounds?
I just had this problem, and solved it in a way that seems, to me, nicer-looking. It is basically winstaan74's answer, but with the extra bits needed to make it work.
You have your function's groovy file, named say: MyJmeterFunctions.groovy:
package My.JmeterFunctions
public class MyHelloClass {
public void hello() {
println("Hello!");
}
}
Then you compile this from the terminal:
$groovyc -d myJmeterFunctions myJmeterFunctions.groovy
and turn it into a .jar inside the /lib folder of your jmeter install, with all the other .jar files that came with jmeter
$jar cvf /<>/apache-jmeter-2.8/lib/myJmeterFunctions.jar -C myJmeterFunctions .
Now, restart jmeter. It won't know about your new .jar until you do.
Lastly you have the script that you want to run the hello() function from, which your jmeter BSF assertion/listener/ whatever points to:
import My.JmeterFunctions.*
def my_hello_class_instance = new MyHelloClass();
my_hello_class_instance.hello();
And this is what worked for me. If you'd rather organize you .jar into a different folder than jmeter's /lib, I believe you can run jmeter using (from here):
$jmeter -Jsearch_paths=/path/to/yourfunction.jar
But I haven't tried that myself.
I ended up having 2 files like below:
"MyHelloClass.groovy"
public class MyHelloClass {
public void hello() {
println("Hello!");
}
}
And "HelloScript.groovy"
try {
ClassLoader parent = getClass().getClassLoader();
GroovyClassLoader loader = new GroovyClassLoader(parent);
Class groovyClass = loader.parseClass(new File("../GroovyScripts/MyHelloClass.groovy"));
GroovyObject helloClass = (GroovyObject) groovyClass.newInstance();
helloClass.hello();
}
catch (Throwable e) {
println(e.toString());
}
Then I can run "HelloScript.groovy" in BSF from Jmeter.
I think you'll need to wrap your helper methods in a class, and then import that class. So, your helper methods file should contain..
package library
class UsefulFunctions {
static function() {
println 'hello'
}
}
And then in your test script, say
import static library.UsefulFunctions.*
function()
Now, this is just scratching the surface, but I hope it'd be enough to get you started.

Resources