Passing function as argument in JDK 8 - java

I am trying to refactor the below code
class FileDownloadResource{
#Inject
private FileDownload fileDownload;
#Path(/abc)
public Response downloadFileABC(){
try{
fileDownload.downloadABC();
}catch(IOException e){
}
//Some code here that is common to the second method as well
}
#Path(/xyz)
public Response downloadFileXYZ(){
try{
fileDownload.downloadXYZ();
}catch(IOException e){
//handle exception
}
//Some code here that is common to the first method as well
}
}
The class is a JAX-RS rest resource. As you can see in the above code, everything except what is in the try block is the same for two method. Can we use any of the new JDK 8
features to pass fileDownload.downloadABC() as an argument to a private method ?
Basically, I am looking for some way to pass a function
as an argument and let the other part of the code be same.

Sure you can. You need either to use existing functional interface or create the new one. As you expect checked IOException, it's better to create the new one (you could also use Callable<Void>, but it's less convenient):
#FunctionalInterface
interface IORunnable {
void run() throws IOException;
}
Now you can create generic request handler private method:
public Response handleRequest(IORunnable r){
try {
r.run();
} catch(IOException e){
// handle exception
}
//Common code follows
}
And use it like this:
#Path("/abc")
public Response downloadFileABC(){
return handleRequest(fileDownload::downloadABC);
}
Or with lambda:
#Path("/abc")
public Response downloadFileABC(){
return handleRequest(() -> fileDownload.downloadABC());
}

You can do this, as long as the downloadABC() and downloadXYZ() methods have the same parameters and return value as the download() method of the Download interface.
Name of interface and interface method can be anything you choose.
#FunctionalInterface
interface DownloadMethod {
public void doDownload() throws IOException;
}
class FileDownload {
public void downloadABC() throws IOException {}
public void downloadXYZ() throws IOException {}
}
class FileDownloadResource{
#Inject
private FileDownload fileDownload;
#Path("/abc")
public Response downloadFileABC(){
return download(fileDownload::downloadABC);
}
#Path("/xyz")
public Response downloadFileXYZ() {
return download(fileDownload::downloadXYZ);
}
private Response download(DownloadMethod method){
try{
method.doDownload();
}catch(IOException e){
//handle exception
}
//Some code here that is common to both methods
}
}

Related

How to new an InvocationException in Java?

How could I new an InvocationException in Java ?
InvocationException needs an ObjectReference in its constructor, I don't know how to create one.
Do you mean InvocationTargetException?
From the API: Is a checked exception that wraps an exception thrown by an invoked method or constructor.
Not sure what you try to achieve, maybe share some code and describe your intentions, however if you want to extend this exception then:
package .....;
import java.lang.reflect.InvocationTargetException;
public class SampleException extends InvocationTargetException {
protected SampleException() {
super();
}
public SampleException(Throwable target) {
super(target);
}
public SampleException(Throwable target, String s) {
super(target, s);
}
#Override
public Throwable getTargetException() {
return super.getTargetException();
}
#Override
public Throwable getCause() {
return super.getCause();
}
}
Maybe you want to override getTargetException with something specific to your requirement to catch InvocationTargetException and rethrow with your specific exception?
try{
.....
}catch(InvocationTargetException e){
//Do something with e?
throw new SampleException(); //Rethrow?
}
As I said not much information given.

Java language best solution for Exception implementation

I need to extend Exception class in my application and i ran into a situation.
My Parent Exception class with a httpCode setter/getter to translate the exception to http error code:
abstract class ParentException
{
private int httpCode;
protected ParentException()
{
this("");
}
public ParentException(String message)
{
super(message);
}
protected ParentException(Exception e)
{
super(e);
}
public int getHttpCode()
{
return httpCode;
}
public void setHttpCode(int httpCode)
{
this.httpCode = httpCode;
}
}
Sub class:
public class AccessDeniedException extends ParentException
{
public AccessDeniedException()
{
this("");
}
public AccessDeniedException(String message)
{
super(message);
setHttpCode(HttpCodes.HTTP_CODE_403_FORBIDDEN_UNAUTHORIZED);
}
public AccessDeniedException(Exception e)
{
super(message);
setHttpCode(HttpCodes.HTTP_CODE_403_FORBIDDEN_UNAUTHORIZED);
}
}
Similarly i have bunch of other exception implementations for various relevant http codes. What I do not like is that setHttpCode() method is in two places. I want this to be called just from one constructor.
I could have just one constructor in all classes as following (ofcourse I need to fix parent class similarly):
public class AccessDeniedException extends ParentException
{
public AccessDeniedException()
{
this("");
}
public AccessDeniedException(String message)
{
this(message, null);
}
public AccessDeniedException(Exception e)
{
this("", e);
}
public AccessDeniedException(String message,Exception e)
{
super(message, e);
setHttpCode(HttpCodes.HTTP_CODE_403_FORBIDDEN_UNAUTHORIZED);
}
}
But I am worried that if a constructor with just message or exception is called, root Exception or Throwable classes may not get instantiated properly. Do you see any issue with this approach? If not, what is the better way of doing this.
One way would be to have in the base class:
protected abstract int getHttpCode();
And then every child class would need a:
#Override
protected getHttpCode() {
return HttpCodes.HTTP_CODE_403_FORBIDDEN_UNAUTHORIZED;
}
If you do it the second way you should probably pass in null as the message for the empty and Exception constructors.
The second approach will work OK, but you might see slightly different output compared to the first, as some Throwable constructors fill the detailMessage differently.
The same issue as described here was is seen in Exception's extension of Throwable. They solve it in the same way as your first example.
Of the two, I'd recommended using your first example as it follows the established convention and is more robust design if the superclass behavior changed.
Edit - M. Prokhorov noted that there should be an abstract getter method, this approach would work and is better design. Further along those lines I would suggest including the httpCode as part of the constructors of Parent.
e.g.
protected ParentException(int httpCode)
{
super();
this.httpCode = httpCode;
}
public AccessDeniedException()
{
super(HttpCodes.HTTP_CODE_403_FORBIDDEN_UNAUTHORIZED);
}
You could also extract the code to a constant (static final) variable.

Java: Is it possible to always execute a certain function before other functions are called? (Like #Before in JUnit)

Is there a way to always execute a function before any other function of a class is called?
I have a class where I need to refresh some fields always before any function is called:
public class Example {
private int data;
public void function1(){
}
public void function2(){
}
//#BeforeOtherFunction
private void refresh(){
// refresh data
}
}
Because it seems to be bad programming, I don't want to call refresh at the beginning of every other function. Since other persons are going to work on this project as well, there would be the danger, that somebody extends the calls and doesn't call refresh.
JUnit has a solution for this with the #Before-Annotation. Is there a way to do this in other classes as well?
And by the way: If you know a programming pattern wich solves this problem in another way than executing a function everytime any function is called, that would be very helpful, too!
Use a dynamic proxy in which you can filter to those methods before which your specific "before" method should be called. And call it in those cases before dispatching the call. Please see the answer from How do I intercept a method invocation with standard java features (no AspectJ etc)?
UPDATE:
An interface is needed to be separated for the proxy. The refresh() method cannot remain private. It must be public and part of the interface (which is not nice here) to be able to be called from the proxy.
package CallBefore;
public interface ExampleInterface {
void function1();
void function2();
void otherFunction();
void refresh();
}
Your class implements that interface:
package CallBefore;
public class Example implements ExampleInterface {
#Override
public void function1() {
System.out.println("function1() has been called");
}
#Override
public void function2() {
System.out.println("function2() has been called");
}
#Override
public void otherFunction() {
System.out.println("otherFunction() has been called");
}
#Override
public void refresh() {
System.out.println("refresh() has been called");
}
}
The proxy which does the trick. It filters the needed methods and calls refresh().
package CallBefore;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ExampleProxy implements InvocationHandler {
private ExampleInterface obj;
public static ExampleInterface newInstance(ExampleInterface obj) {
return (ExampleInterface) java.lang.reflect.Proxy.newProxyInstance(obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(), new ExampleProxy(obj));
}
private ExampleProxy(ExampleInterface obj) {
this.obj = obj;
}
#Override
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
Object result;
try {
if (m.getName().startsWith("function")) {
obj.refresh();
}
result = m.invoke(obj, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
} catch (Exception e) {
throw new RuntimeException("unexpected invocation exception: " + e.getMessage());
}
return result;
}
}
The usage:
package CallBefore;
public class Main {
public static void main(String[] args) {
ExampleInterface proxy = ExampleProxy.newInstance(new Example());
proxy.function1();
proxy.function2();
proxy.otherFunction();
proxy.refresh();
}
}
Output:
refresh() has been called
function1() has been called
refresh() has been called
function2() has been called
otherFunction() has been called
refresh() has been called
This may not solve your exact problem but at least could be a starting point if you are allowed considering a re-design. Below is a simple implementation but with some small touches I believe you can achieve a more elegant solution. BTW, this is called Dynamic Proxy Pattern.
First thing you need is an interface for your class.
public interface Interface {
void hello(String name);
void bye(String name);
}
public class Implementation implements Interface {
#Override
public void hello(String name) {
System.out.println("Hello " + name);
}
#Override
public void bye(String name) {
System.out.println("Bye " + name);
}
}
Then java.lang.reflect.Proxy class comes to help. This class is able to create an instance for a given interface at runtime. It also accepts an InvocationHandler which helps you to capture method calls and looks like this.
public class InvocationHandlerImpl implements InvocationHandler {
private final Object instance;
public InvocationHandlerImpl(Object instance) {
this.instance = instance;
}
#Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result;
try {
System.out.println("Before");
result = method.invoke(instance, args);
System.out.println("After");
} catch (Exception e){
e.printStackTrace();
throw e;
} finally {
System.out.println("finally");
}
return result;
}
}
After all your client code will look like this.
Interface instance = new Implementation();
Interface proxy = (Interface)Proxy.newProxyInstance(
Interface.class.getClassLoader(),
new Class[] { Interface.class },
new InvocationHandlerImpl(instance));
proxy.hello("Mehmet");
proxy.bye("Mehmet");
Output for this code is
Before
Hello Mehmet
After
finally
Before
Bye Mehmet
After
finally
I would define getters for every field and do the refreshment inside the getter. If you want to avoid unrefreshed access to your private fields at all, put them in a superclass (together with the getters which call refresh).
Depending on your project structure, it may be also sensible to introduce a separate class for all data that is regularly refreshed. It can offer getters and avoid that anyone accesses the non-refreshed fields.
Not in Java SE, but if you are using Java EE, you could use interceptors.
For standalone applications, you could consider using a bytecode manipulation framework, like javassist.
You can have a protected getter method for data. Access getData method instead of using data field. Child classes will see only getData and will have updated data every time.
public class Example {
private int data;
public void function1(){
}
public void function2(){
}
protected int getData(){
refresh();
return data;
}
//#BeforeOtherFunction
private void refresh(){
// refresh data
}
}
It is better to write another method which will be made protected(accessible to the child classes) which will call first the refresh method and then call the function.
This way the data would be refreshed before the function is called everytime(As per your requirement).
eg:
protected void callFunction1(){
refresh();
function();
}
Thanks,
Rajesh
You should use Decorator in this case. Decorator is a good choice for something like interceptor. Example here: https://msdn.microsoft.com/en-us/library/dn178467(v=pandp.30).aspx

Having generic AsyncTask handle any Exception

I have created an generic AsyncTask class, so that I can catch all Exceptions thrown when task method is executed:
public abstract class Poc<ParamType, ReturnType>
extends AsyncTask<ParamType, String, ReturnType> {
abstract ReturnType task(ParamType... param);
#Override
protected ReturnType doInBackground(ParamType... param) {
try {
return task(param);
} catch (Exception e) {
// Make some Toast display the exception.
}
return null;
}
}
I try to implement the above class by doing some thing like:
public class Use {
public static void runIt() {
new Poc<String, Boolean>() {
#Override
Boolean task(String... param) {
return SomeObject.someMethodThatCanThrowAnException(param);
}
}.execute("Some String");
}
}
However, it keeps complaining about wanting me to add try/catch statements. Even when I know that task will only be called from doInBackground which wraps it.
Can I somehow suppress this? Or what is the proper approach without having to add try/catch to every single class that subclasses Poc?
As the compiler is trying to tell you, you need to declare your function as being able to throw things using throws Exception.
In this case, you would want the abstract method to be able to throw.

Partial mock of template methods with EasyMock

I have a couple of classes following the "Template Method" pattern. Abstract class A, and concrete extensions, B and C. Like this:
public abstract class A
{
protected abstract String getData() throws SomeException;
public void doWork() throws OtherException
{
try
{
// business logic ...
String data = this.getData();
// more business logic ...
}
catch(SomeException e)
{
log("...", e);
throw new OtherException("...", e);
}
}
}
public Class B extends A
{
protected String getData() throws SomeException
{
// complicated logic relying on lots of dependencies
}
}
public Class C extends A
{
protected String getData() throws SomeException
{
// different but equally complicated logic relying on lots of dependencies
}
}
I want to write a test to verify when getData() throws SomeException that OtherException is thrown. I really want to avoid mocking up all of the complicated dependencies that would be required to force getData() to throw. I don't care how getData() throws, I just want it to throw. So I think a partial mock is what I want. This is what I have:
import static org.easymock.EasyMock.*;
....
#Test(expected = OtherException.class)
public void testSomethingOrAnother() throws Exception
{
B target = createMockBuilder(B.class).addMockedMethod("getData").createMock();
expect(target.getData()).andThrow(SomeException.class).once();
replay(target)
try
{
target.doWork(); // expect this to throw OtherException;
}
finally
{
verify(target);
}
}
The test looks good to me, but when I run it I get this:
java.lang.Exception: Unexpected exception, expected<OtherException> but was<java.lang.RuntimeException>
... deleted for brevity ...
Caused by: java.lang.RuntimeException: Ambiguous name: More than one method are named getData
at org.easymock.internal.ReflectionUtils.findMethod(ReflectionUtils.java:96)
at org.easymock.internal.ReflectionUtils.findMethod(ReflectionUtils.java:64)
at org.easymock.internal.MockBuilder.addMockedMethod(MockBuilder.java:73)
at org.easymock.internal.MockBuilder.addMockedMethods(MockBuilder.java:92)
at com.mycompany.more.packages.BTest(BTest.java:83)
... deleted for brevity ...
... 16 more
To be clear: There is NOT an overload of the getData() method anywhere in the hierarchy.
Is EasyMock able to do what I'm trying to do here? What am I missing?
relevant versions numbers:
EasyMock 3.0
JUnit 4.4
Java 1.6
I think your problem may be the use of the addMockedMethod(String). Not sure why EasyMock is complaining about an ambiguous method name if there are no overloads. But the following worked for me:
#Test
public void testSomethingOrAnother() {
B target = null;
try {
target = EasyMock.createMockBuilder(B.class).addMockedMethod(B.class.getDeclaredMethod("getData")).createMock();
EasyMock.expect(target.getData()).andThrow(new SomeException());
EasyMock.replay(target);
} catch (NoSuchMethodException e) {
fail(e.getMessage());
} catch (SomeException e) {
fail(e.getMessage());
}
try {
target.doWork();
fail("doWork should have thrown an exception");
} catch (OtherException e) {
//pass
}
}
With Easymock:3.2 you are able to specify types of the parameters of the method. Take a look IMockBuilder#addMockedMethod(String methodName,Class<?>... parameterTypes)
Thanks.

Categories

Resources