I am trying to implement jms to my grails application.
I have several JMS consumer in a spring based enviroment listining
on an ActiveMQ broker. I wrote a simple test commandline client which creates
messages and receives them in an request response manner.
Here is the snippet that sends a MapMessage in Spring JMS way.
This works for me as long I am in my spring world.
final String corrID = UUID.randomUUID().toString();
asyncJmsTemplate.send("test.RequestQ", new MessageCreator()
{
public Message createMessage(Session session) throws JMSException {
try {
MapMessage msg = session.createMapMessage();
msg.setStringProperty("json", mapper.writeValueAsString(List<of some objects>));
msg.setJMSCorrelationID(corrID);
msg.setJMSReplyTo(session.createQueue("test.ReplyQ"));
return msg;
} catch (JsonGenerationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
});
BUT when I tried to implement this methods to my grails test app
I receive some METHOD_DEF exceptions. Sending simple TextMessages
via the jmsTemplate.convertAndSende(Queue, Message) provided by
the JMS Plugin works.
Can any one help me? Is this a common problem?
Cheers Hans
Not actually trying this out, I have to believe this is a syntax problem. What you're really doing with that anonymous class is passing a closure containing all the MessageCreator code into the constructor for the MessageCreator class. In Groovy, closures can be passed as the last argument to a function merely by placing it after the function name or the parenthesized first arguments.
SomeFunction( arg1, arg2) { some code }
is the same as
SomeFunction( arg1, arg2, { some code } )
What you really want is to convert the closure into an anonymous instance of a MessageCreator, which I believe you can accomplish by:
asyncJmsTemplate.send("test.RequestQ",
{ code in the anonymous block } as MessageCreator );
I found this on StackOverflow, actually, though it's a poorly created question. Read all the responses, and you should see something relevant: Best groovy closure idiom replacing java inner classes?
I have had the same problems and here is my working solution:
I have created a new class MyMessageCreator in the src folder which implements the origin JMS MessageCreator interface.
With this I can create a new MyMessageCreator object and can call the createMessage(Session session) function to generate a new message.
To get the session object I use the jmsTemplate.
public class MyMessageCreator implements MessageCreator {
#Override
public Message createMessage(Session session) throws JMSException {
return session.createMapMessage();
}
}
Here is the relevant groovy code:
Session session = jmsTemplate.getConnectionFactory().createConnection().createSession(false, Session.AUTO_ACKNOWLEDGE)
MapMessage msg = new MyMessageCreator().createMessage(session);
Hope this helps,
Mirko
Related
I'm using rxAndroid.
I've read many documents, but still not found the solution, and maybe I missed it,
so please give me a guide.
Here I created an observable that might throw an exception in subscribe method.
return Observable.create(new ObservableOnSubscribe<Project>() {
#Override
public void subscribe(#NonNull ObservableEmitter<Project> e) throws Exception {
e.onNext(projectRepository.readDetails(project.getId()));
e.onComplete();
}
});
I use repository pattern to get the project details,
but the problem is all of the repository methods might throw an exception,
projectRepository.readDetails(project.getId())
And I couldn't find anyway to handle the exception throwed in the method subscibe(), Observer's onError() will not get any notification of it.
Thanks.
When creating an observable manually, you have to catch any exception and pass them to the onError() manually:
return Observable.create(new ObservableOnSubscribe<Project>() {
#Override
public void subscribe(#NonNull ObservableEmitter<Project> e) throws Exception {
try {
e.onNext(projectRepository.readDetails(project.getId()));
e.onComplete();
}
catch (Exception ex) {
e.onError(ex);
}
}
});
Alternatively you should be able to use fromCallable() to avoid having to create the observable manually:
Observable.fromCallable(() -> projectRepository.readDetails(project.getId()));
This will signal onError() if the call should fail.
I have the following method:
public Object method(){
try
{
privatevoidmethod1();
privatevoidmethod2();
}
catch(Exception e)
{
Log.debug(e);
}
return object;
}
How do I force the exception so I can test the debug call?
Leaving aside how you'd test the debug call, you'd normally trigger an exception by providing suitable inputs such that an exception would be created/thrown. If that's not suitable, the alternative is to provide a substitute (mocked) component that has been configured/written to throw an exception e.g.
public MyClass(MyInjectedComponent component) {
this.component = component;
}
and you'd provide for your test an implementation of MyInjectedComponent that will throw an exception (for testing purposes). The approach of injecting components into other components is called dependency injection and worth investigating.
I'd normally use a mocking framework for this (e.g. Mockito or similar). However a trivial implementation of the above could be:
public class MyImplementationForTesting extends MyInjectedComponent {
public void method() throws Exception {
throw new Exception();
}
}
I have a method with a handled exception:
public boolean exampleMethod(){
try{
Integer temp=null;
temp.equals(null);
return
}catch(Exception e){
e.printStackTrace();
}
}
I want to test it
public void test_exampleMethod(){}
I have tried
#Rule
public ExpectedException expectedException=ExpectedException.none();
public void test_exampleMethod(){
expectedException.expect(JsonParseException.class);
exampleMethod();
}
but that doesnt work because the exception is handled inside.
I also tried
#Test(expected=JsonParseException.class)
but same issue...the exception is handled
I know that I can just do
assertTrue(if(exampleMethod()))
but it will still print the stack trace to the log. I would prefer clean logs...Any suggestions?
You cannot test what a method is doing internally. This is completely hidden (unless there are side effects, that are visible outside).
The test can check that for a specific input the method returns a expected output. But you can not check, how this is done. So you have no way to detect if there was a exception that you have handled.
So: either don't handle the exception (let the test catch the exception), or return a special value that tells you about the exception.
Anyway, I hope your real exception handling is more sensible than in your example.
If the method does not throw an exception you cannot expect to get one!
Below an example how write a Junit Test for a method that throws an Exception:
class Parser {
public void parseValue(String number) {
return Integer.parseInt(number);
}
}
Normal test case
public void testParseValueOK() {
Parser parser = new Parser();
assertTrue(23, parser.parseValue("23"));
}
Test case for exception
public void testParseValueException() {
Parser parser = new Parser();
try {
int value = parser.parseValue("notANumber");
fail("Expected a NumberFormatException");
} catch (NumberFormatException ex) {
// as expected got exception
}
}
Using Play Framework 2.1 with OpenID, if I cancel my authentication from the OpenID Provider, I get this exception :
[RuntimeException: play.api.libs.openid.Errors$AUTH_CANCEL$]
Here's my code :
Promise<UserInfo> userInfoPromise = OpenID.verifiedId();
UserInfo userInfo = userInfoPromise.get(); // Exception thrown here
But since it's a Runtime exception, I can't catch it with a try/catch so I'm stuck on how to avoid exception and returns something nicer than a server error to the client.
How can I do that?
A Promise is success biased, for all its operations, it assumes it actually contains a value and not an error.
You get the exception because you try to call get on a promise which contains an untransformed error.
What you want is to determine if the Promise is a success or an error, you can do that with pattern matching for instance.
try this code:
AsyncResult(
OpenID.verifiedId.extend1( _ match {
case Redeemed(info) => Ok(info.attributes.get("email").getOrElse("no email in valid response"))
case Thrown(throwable) => {
Logger.error("openid callback error",throwable)
Unauthorized
}
}
)
)
You may want to read more on future and promises, I recommend this excellent article :
http://danielwestheide.com/blog/2013/01/09/the-neophytes-guide-to-scala-part-8-welcome-to-the-future.html
edit :
checking the documentation (http://www.playframework.com/documentation/2.1.0/JavaOpenID) in java it seems you are supposed to catch and handle exceptions yourself.
In any case, you should catch exceptions and if one is thrown redirect
back the user to the login page with relevant information.
something like this should work :
public class Application extends Controller {
public static Result index() {
return ok("welcome");
}
public static Result auth() {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put("email", "http://schema.openid.net/contact/email");
final Promise<String> stringPromise = OpenID.redirectURL("https://www.google.com/accounts/o8/id", "http://localhost:9000/auth/callback",attributes);
return redirect(stringPromise.get());
}
public static Result callback() {
try{
Promise<UserInfo> userInfoPromise = OpenID.verifiedId();
final UserInfo userInfo = userInfoPromise.get();
System.out.println("id:"+userInfo.id);
System.out.println("email:"+userInfo.attributes.get("email"));
return ok(userInfo.attributes.toString());
} catch (Throwable e) {
System.out.println(e.getMessage());
e.printStackTrace();
return unauthorized();
}
}
}
I'm recently digging into the source code of JUnit-4.11, what confuse me is that the seemingly redundant Protectable interface. the declaration is as follows:
public interface Protectable {
public abstract void protect() throws Throwable;
}
In the TestResult class, there is a void run(final TestCase test) method, in which a anonymous Protectable instance is realized as follows:
protected void run(final TestCase test) {
startTest(test);
Protectable p = new Protectable() {
public void protect() throws Throwable {
test.runBare();
}
};
runProtected(test, p);
endTest(test);
}
runProtected method is as follows:
public void runProtected(final Test test, Protectable p) {
try {
p.protect();
} catch (AssertionFailedError e) {
addFailure(test, e);
} catch (ThreadDeath e) { // don't catch ThreadDeath by accident
throw e;
} catch (Throwable e) {
addError(test, e);
}
}
As we can see, what runProtected does is just executing test.runBare();, so is there any sense to the existence of Protectable interface? Why can't we just write code like below.
protected void run(final TestCase test) {
startTest(test);
test.runBare();
endTest(test);
}
To answer your final question first, you can't use
protected void run(final TestCase test) {
startTest(test);
test.runBare();
endTest(test);
}
because it won't do what you want. JUnit manages asserts using exceptions, specifically AssertionFailedError. So, Assert.assertEquals() throws an AssertionFailedError when the two values aren't equal. So, in the above method, the endTest(test) won't get called if there is an assertion failure, which means the correct events (failure/error of the test) won't get fired, and tearDown() won't get executed.
The Protectable interface is there to give a more generic interface to the runner, so that you don't have to hand a TestCase to the method, to allow different actions.
As an aside, this is part of the package junit.framework.*, which is JUnit 3. JUnit 4 is where it's at, and if you want to learn, look more in the org.junit.* packages.
It seems to handle thrown exceptions in specific way :
Call addFailure for assertion exception (your test failed), addError for other exception (your test is not well coded)
This interface is to protect the TestCase by adding Throwable.
so junit could run any testcase safely.
The Throwable class is the superclass of all errors and exceptions in the Java language.