Migrate builder to Spring hateoas 2.6.7 - java

I have this old code implemented in hateoas:1.0
public class StaticPathLinkBuilder extends LinkBuilderSupport<StaticPathLinkBuilder> {
#Override
protected StaticPathLinkBuilder createNewInstance(UriComponentsBuilder builder) {
return new StaticPathLinkBuilder(builder);
}
I updated my code to hateoas 2.6.7 but the code is changed this way:
public class StaticPathLinkBuilder extends LinkBuilderSupport<StaticPathLinkBuilder> {
#Override
protected StaticPathLinkBuilder createNewInstance(UriComponents components, List<Affordance> affordances) {
return null;
}
What is the proper way to implement this change? I tried this:
#Override
protected StaticPathLinkBuilder createNewInstance(UriComponents components, List<Affordance> affordances) {
return new StaticPathLinkBuilder(UriComponentsBuilder.newInstance().uriComponents(components));
}
But it's not clear how I have to implement the code that I can send affordances.
Can you advice what is the proper way to implement this?

As you can see in its source code LinkBuilderSupport already provides a constructor with the two required arguments, UriComponents and List<Affordance>.
In the own library codebase, different LinkBuilders implementations as BasicLinkBuilder or TemplateVariableAwareLinkBuilderSupport already takes advantage of this fact in their implementations.
In your use case, you could try something similar to this:
public class StaticPathLinkBuilder extends LinkBuilderSupport<StaticPathLinkBuilder> {
private StaticPathLinkBuilder(UriComponents components, List<Affordance> affordances) {
super(components, affordances);
}
#Override
protected StaticPathLinkBuilder createNewInstance(UriComponents components, List<Affordance> affordances) {
return new StaticPathLinkBuilder(components, affordances);
}
}

Related

How to specify multiple conditions using #Conditional annotation

I am doing a Spring project for the first time and am stuck with a problem.
I have a java class:
#Component
#Conditional(AppA.class)
public class AppDeploy {...}
Now I need to modify this like:
#Component
#Conditional(AppA.class or AppB.class)
public class AppDeploy {...}
Can someone help me with how to do this?
Thanks in anticipation.
You can create your own conditional annotation which enables you to provide parameters and then you can apply the tests conditions depending on the provided parameter value:
see this post for more details: http://www.javacodegeeks.com/2013/10/spring-4-conditional.html
It was very simple, Should have taken a little time before posting the question.
Here is how I did it.
Created a new Class:
public class AppAOrB implements Condition {
public AppAOrB() {
super();
}
#Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
Environment env = conditionContext.getEnvironment();
return env.containsProperty("APP_A")||env.containsProperty("APP_B");
}
}
Then used it like:
#Component
#Conditional(AppAOrB.class)
public class AppDeploy {...}
I have a slightly different approach.
From your code, I can conclude(Maybe I am wrong) that You have already implemented conditions AppA.class and AppB.class and You wonder how to implement the AppAOrB.class condition in an elegant way. When You take into account that AppA.class and AppB.class are just regular java classes, then implementation is obvious:
public class AppAOrB implements Condition {
#Override
public boolean matches(#NonNull ConditionContext context, #NonNull AnnotatedTypeMetadata metadata) {
return new AppA().matches(context, metadata) || new AppB().matches(context, metadata);
}
}
The pros of this approach is that it follows the DRY rule.

Framework for combining components

I'm trying to find a framework, or a nice way of implementing a way combining various components, similar to an electronics kit. This is so that it can be wired together using xml (e.g. Spring). I want the users to be able to string together different components without having to worry about Java.
The set up I'm thinking of would have something like the following:
public interface Input<T> {
public T getValue();
}
public interface Output<T> {
public void setValue(T value);
}
public class Wire<T> implements Input<T>, Output<T> {
private T value;
public T getValue() { return value; }
public void setValue(T value) { this.value = value ; };
}
And then components would be something like
public interface Component {
public void evaluate();
}
public class Multiplier implements Component {
private Input<Double> inA;
private Input<Double> inB;
private Output<Double> out;
public Multiplier(Input<Double> inA, Input<Double> inB, Output<Double> out) {
this.inA = inA;
this.inB = inB;
this.out = out;
}
public void evaluate() {
out.setValue(inA.getValue() * inB.getValue());
}
}
main() {
Wire inA = new Wire();
Wire squareOut = new Wire();
Component squarer = new Multiplier(inA, inA, output)
}
So you could tie outputs of one component into the input of another. I've toyed with the idea of the Wires knowing about what outputs they're connected to, so that they can call evaluate on their components... but I think it might be easier to keep a separate "clock" so that circular dependencies can be controlled.
It's not hard to implement, I'd just rather use a public library if there is one already out there. I've struggled to find one.
Any advice about implementing something similar, or what to do instead would be really helpful.
You are talking about Dependency Injection Framework.
Look at Spring, Google Guice or PicoContainer.

DRY: a case with AsyncTasks

I'm developing an Android app which has a lot of different requests for web services.
Every request is done in a subclass of AsyncTask in this manner:
(new AsyncTask<String, Void, Object1>() {
#Override
protected Object1 doInBackground(String... params) {
// network request and parsing to Object1
Object1 obj = new Object1();
obj1 = Parser.parseObject1(httpClient.execute(...));
return obj1;
}
#Override
protected Object1 onPostExecute(Object1... ret) {
return ret[0];
}
}).execute();
Object1 is a placeholder for different objects (Car, Bicycle, Truck...), each one in a different AsyncTask.
What are my alternatives other than returning the output of httpClient in a String and parsing in the Main Thread (UI Thread)? Avoid parsing in the UI Thread sounds reasonable if it's going to parse a lot of data, am I right?
-= UPDATE =-
Let me rephrase the question: I'm asking for a more intelligent way to develop my application avoiding being repetitive (AsyncTask has a lot of boilerplate code). The way I did was by creating 20+ subclasses of AsyncTask, which clearly is not DRY (do not repeat yourself).
In iOS we have lambda expressions so callbacks done in web requests are very easy and succinct.
You can create classes that contain most of your boilerplate code. E.g.
public class SpecialAsyncTask<T> extends AsyncTask<String, Void, T> {
public interface ResultProvider<T> {
T generateResultInBackground(String... params);
}
public interface ResultConsumer<T> {
void handleResultInForeground(T result);
}
private final ResultProvider<T> mProvider;
private final ResultConsumer<T> mConsumer;
private SpecialAsyncTask(ResultProvider<T> provider, ResultConsumer<T> consumer) {
mProvider = provider;
mConsumer = consumer;
}
#Override
protected T doInBackground(String... params) {
return mProvider.generateResultInBackground(params);
}
#Override
protected void onPostExecute(T result) {
mConsumer.handleResultInForeground(result);
}
public static <T> void execute(ResultProvider<T> provider, ResultConsumer<T> consumer, String... params) {
new SpecialAsyncTask<T>(provider, consumer).execute(params);
}
}
is an example how you could keep Object1 as a generic parameter while being able to specify an object that only needs to implement an interface to handle code that would otherwise have to be inside a new AsyncTask instance.
With a schema like that you could for example define some common code as static content:
class Providers {
public static final ResultProvider<String> HTTP_GETTER = new ResultProvider<String>() {
#Override
public String generateResultInBackground(String... params) {
return MagicHttpLibrary.getContentAsString(params[0]);
}
};
}
And you can just use Providers.HTTP_GETTER as parameter instead of implementing doInBackground. Or create a new class hierarchy of that implement one of those interfaces with different methods to access them (like factories for example)
Use of above example would look for example like below
class User extends Activity implements ResultConsumer<String> {
#Override
protected void onCreate(Bundle savedInstanceState) {
SpecialAsyncTask.execute(Providers.HTTP_GETTER, this , "http://google.com");
SpecialAsyncTask.execute(Providers.HTTP_GETTER, this , "http://yahoo.com");
}
#Override
public void handleResultInForeground(String result) {
Toast.makeText(this, result, Toast.LENGTH_LONG).show();
}
}
and there is more or less no repeated code besides the different method calls. It depends on how you want to use a class and what actually changes in the code to know how to design something like that. Identify the parts that need to be parametrized and move code that repeats into a re-used place (inheritance / composition).
Google's Volley HTTP request library does the request and parsing both in the same worker thread. So, that's a pretty good example to code by.

Is it possible to add an interceptor to all answers when using Mockito?

Suppose I have a validation annotation on my Interface method to validate input arguments and return value.
Is it possible at the moment (V 1.9.5) to tell Mockito to invoke this validator during the invocation process?
The background would be to prevent developers from writing unrealistic tests by mocking the given interface in a way that violates the specified validator.
So what I would want is to register something like
class MyAnswerInterceptor<T> implements AnswerInterceptor<T> {
#Override
public Answer<T> intercept(final Answer<T> answer) {
return new Answer<T>() {
#Override
public T answer(InvocationOnMock invocation) throws Throwable {
validateArguments(invocation);
T result = answer.answer(invocation);
validateReturnValue(result);
return result;
}
}
}
}
to be called on every answer of a given mock.
Is this possible at all? I've looked into the code, also to check if I could hack in at some point (even using reflection or the like), but it seems due to entanglement of instance creation and logic, it's hardly possible to achieve what I want (i.e. stuff like MockHandler mockHandler = new MockHandlerFactory().create(settings); makes it impossible to hook in and put custom stuff on top without patching and deploying the whole thing...)
Any insight would be highly appreciated :-)
You could achieve that by creating a custom MockMaker.
MockMaker is an extension point that makes it possible to use custom dynamic proxies and avoid using the default cglib/asm/objenesis implementation
Our custom implementation delegates all the complex stuff to the default MockMaker: CglibMockMaker. It "decorates" only the createMock method by registering on the settings parameter an InvocationListener. This listener will be notified when an invocation have been done allowing use to call validateArguments and validateReturnValue.
import org.mockito.internal.creation.CglibMockMaker;
import org.mockito.invocation.Invocation;
import org.mockito.invocation.MockHandler;
import org.mockito.listeners.InvocationListener;
import org.mockito.listeners.MethodInvocationReport;
import org.mockito.mock.MockCreationSettings;
import org.mockito.plugins.MockMaker;
public class ValidationMockMaker implements MockMaker {
private final MockMaker delegate = new CglibMockMaker();
public ValidationMockMaker() {
}
#Override
public <T> T createMock(MockCreationSettings<T> settings, MockHandler handler) {
settings.getInvocationListeners().add(new InvocationListener() {
#Override
public void reportInvocation(MethodInvocationReport methodInvocationReport) {
Invocation invocation = (Invocation) methodInvocationReport.getInvocation();
validateArguments(invocation.getArguments());
validateReturnValue(methodInvocationReport.getReturnedValue());
}
});
return delegate.createMock(settings, handler);
}
#Override
public MockHandler getHandler(Object mock) {
return delegate.getHandler(mock);
}
#Override
public void resetMock(Object mock, MockHandler newHandler, MockCreationSettings settings) {
delegate.resetMock(mock, newHandler, settings);
}
protected void validateArguments(Object... arguments) {
// Arrays.stream(arguments).forEach(Objects::requireNonNull);
}
private void validateReturnValue(Object result) {
// Objects.requireNonNull(result);
}
}
Last but not least, we need to tell to Mockito to use our implementation. This is possible by adding a file
mockito-extensions/org.mockito.plugins.MockMaker
containing our MockMaker class name:
ValidationMockMaker
See Using the extension point section in the javadoc.

switching implementation in runtime

I'm writing simple Chat System. There are should be two implementations of communication:
using Serialization
and XML (own protocol).
Implementation is chosen by user in GUI.
So, is it okay to use if-else or switch for choosing implementation ?
I have thought about Java Reflection but I can't figure out how to realize it.
Any suggestions ?
I'd say it can be "okay" to use a if-else or switch statement to choose the implementation. A better (and more OOP) approach would be something along these lines:
//////////////////////////////////
// The communication interfaces
//////////////////////////////////
public interface IChatCommunicationFactory {
public String toString();
public IChatCommunication create();
}
public interface IChatCommunication {
public sendChatLine(String chatLine);
public registerChatLineReceiver(IChatLineReceiver chatLineReceiver);
}
public interface IChatLineReceiver {
public void onChatLineReceived(String chatLine);
}
//////////////////////////////////
// The communication interface implementations
//////////////////////////////////
public class XMLChatCommunicationFactory implements IChatCommunicationFactory {
public String toString() {
return "XML implementation";
}
public IChatCommunication create() {
return new XMLChatCommunication();
}
}
public class XMLChatCommunication implements IChatCommunication {
private XMLProtocolSocket socket;
public XMLChatCommunication() {
// set up socket
}
public sendChatLine(String chatLine) {
// send your chat line
}
public registerChatLineReceiver(IChatLineReceiver chatLineReceiver) {
// start thread in which received chat lines are handled and then passed to the onChatLineReceived of the IChatLineReceiver
}
}
// Do the same as above for the Serialization implementation.
//////////////////////////////////
// The user interface
//////////////////////////////////
public void fillListBoxWithCommuncationImplementations(ListBox listBox) {
listBox.addItem(new XMLChatCommunicationFactory());
listBox.addItem(new SerializationChatCommunicationFactory());
}
public IChatCommunication getChatCommunicationImplementationByUserSelection(ListBox listBox) {
if (listBox.selectedItem == null)
return null;
IChatCommunicationFactory factory = (IChatCommunicationFactory)listBox.selectedItem;
return factory.create();
}
You could go one step further and implement something like a ChatCommunicationFactoryRegistry where each IChatCommunicationFactory is registerd. That would help to move the "business" logic out of the user interface because the fillListBoxWithCommuncationImplementations() method would only need to know the registry, not the individual implementations anymore.
Inheritance and plain old Java is the 'pattern' to use here. Instantiate the implementation to be used, and save a reference to it in the object that needs to use it. When the user switches methods, instantiate the new one.

Categories