Addressing Scalability,Performance and Optimization issues in RMI Application? - performance

my problem is: this design is working fine for one ball but i m unable to get it work for multiple balls, i have basically problem in replacing the "this" keyword in updateClients ().
i thought i need to do something like this but i m failed:
System.out.println("in ballimpl" + j.size());
for (ICallback aClient : j) {
aClient.updateClients(BallImpl[i]);
}
The current situation of code is :
The model remote object, which is iterating client list and calling update method of them,
public class BallImpl extends UnicastRemoteObject implements Ball,Runnable {
private List<ICallback> clients = new ArrayList<ICallback>();
protected static ServerServices chatServer;
static ServerServices si;
BallImpl() throws RemoteException {
super();
}
....
public synchronized void move() throws RemoteException {
loc.translate((int) changeInX, (int) changeInY);
}
public void start() throws RemoteException {
if (gameThread.isAlive()==false )
if (run==false){
gameThread.start();
}
}
/** Start the ball bouncing. */
// Run the game logic in its own thread.
public void run() {
while (true) {
run=true;
// Execute one game step
try {
updateClients();
} catch (RemoteException e) {
e.printStackTrace();
}
try {
Thread.sleep(50);
} catch (InterruptedException ex) {
}
}
}
public void updateClients() throws RemoteException {
si = new ServerServicesImpl();
List<ICallback> j = si.getClientNames();
System.out.println("in messimpl " + j.size());
if (j != null) {
System.out.println("in ballimpl" + j.size());
for (ICallback aClient : j) {
aClient.updateClients(this);
}
} else
System.err.println("Clientlist is empty");
}
}
The client which is implementing callback interface and has update method implementation :
public final class thenewBallWhatIwant implements Runnable, ICallback {
.....
#Override
public void updateClients(final Ball ball) throws RemoteException {
try {
ball.move();
try {
Thread.sleep(50);
} catch (Exception e) {
System.exit(0);
}
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}
.....
}
thanks for any feedback.
jibbylala

Separate your RMI logic from your Ball logic.
You should be able to run your ball simulation without needing any RMI modules. Just to run it locally, to test it. Then you should find a way to wrap that process in RMI so that you can still run it locally to test it without any sort of RMI interface. This block of code is the engine, and it is very important to be able to test it in as atomic a form as possible. Having extra parts integrated with it just increases the complexity of what will undoubtedly be some of the most complex code.
Don't let any extra interfaces into your engine. It should be very specific and few the packages required to use your engine. Any new functionality your software needs, implement it appropriately in the engine to support generic design. Wrap that to provide specific functionality outside the core of the engine. This protects the engine design against changes to the environment. It also allows for more complete testing of the engine.
We make exceptions sometimes in cases where something will only ever be used in one way. But in this case, testing without RMI would seem to be critical to getting your engine working correctly. If your engine runs faster than the network can keep up due to large numbers of clients connecting, do you want the whole game to slow down, or do you want the clients to lag behind? I say, you want to be able to make that choice.

Related

odd behaviour - websocket spring - send message to user using listen / notify postgresql

I am experiencing an odd behavior of my spring boot websocket set-up.
Sometimes it works, sometimes it doesn't, it just feels random.
I have tried the several setups, none proved solid: I moved the last piece of code in a commandlinerunner inside the primary class of the application and the last choice was a different class with #Component annotation.
My setup is the following: I use a jdbc driver (pgjdbc-ng) to use the listen notify function of postgres.I have a function and a trigger that listens to a specific postgres table for inserations. If any occur, notifications are sent through the websocket. The other and is an angular app that uses ng2-stompjs to listen to /topic/notificari for notifications. I am not posting the code because the notifications don't get out of spring, the angular is not the problem.
Kind regards,
This is my WebSocketConfiguration
Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic", "/queue", "/user", "/notificari");
registry.setApplicationDestinationPrefixes("/app");
registry.setUserDestinationPrefix("/user");
}
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/socket").setAllowedOrigins("*")
.setHandshakeHandler(new CustomHandshakeHandler());
}
I am using a class ListenNotify and the JDBC driver pgjdbc-ng to connect to the postgresql db and use listen notify functionality
public class ListenNotify {
private BlockingQueue queue = new ArrayBlockingQueue(20);
PGConnection connection;
public ListenNotify() {
PGNotificationListener listener = new PGNotificationListener() {
#Override
public void notification(int processId, String channelName, String payload) {
queue.add(payload);
}
};
try {
PGDataSource dataSource = new PGDataSource();
dataSource.setHost("localhost");
dataSource.setDatabase("db");
dataSource.setPort(5432);
dataSource.setUser("user");
dataSource.setPassword("pass");
connection = (PGConnection) dataSource.getConnection();
connection.addNotificationListener(listener);
Statement statement = connection.createStatement();
statement.execute("LISTEN n_event");
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public BlockingQueue getQueue() {
return queue;
}
}
And finally this is the code that instantiate the ListenNotify object and listens to postgres for events that might trigger notifications that have to be send using websocket.
#Component
public class InstantaNotificari {
#Autowired
SimpMessagingTemplate template;
#EventListener(ApplicationReadyEvent.class)
public void runn() {
System.out.println("invocare met");
ListenNotify ln = new ListenNotify();
BlockingQueue queue = ln.getQueue();
System.out.println("the que ies "+ queue);
while (true) {
try {
String msg = (String) queue.take();
System.out.println("msg " + msg);
template.convertAndSend("/topic/notificari", msg);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
I didn't use Spring so I can't test your code. Here is my tested version. I think this summarizes the differences -
Change to a try with resources block. This will close the connection on destruction of the class.
Move your while(true) into the try block on the Listener so that the
lines inside the try block doesn't ever get out of execution scope.
The while(true) is blocking, so it needs to be on another thread. ListenNotify extends Thread
I'm sure there are other ways of implementing and welcome corrections to any of my assumptions.
My tested, running code is in this answer JMS Websocket delayed delivery.

Consumer to enclose try catch logic does not work

I am refactoring some legacy code and I come across this function:
private static void parseOptionalValues(Product product, Input source) {
try {
product.setProductType(...some operation with source...);
} catch (IllegalArgumentException ignored) {}
try {
product.setMaterial(...some operation with source...);
} catch (IllegalArgumentException ignored) {}
try {
product.setUnitPricingBaseMeasure(...some operation with source...);
} catch (IllegalArgumentException ignored) {}
try {
product.setUnitPricingMeasure(...some operation with source...);
} catch(IllegalArgumentException ignored){}
}
My common sense says to me that in order to keep the Don't Repeat Yourself principle I should wrap this try-catch logic so I introduced this change:
private static void parseOptionalValues(Product product, Input source) {
setOptionalParameter(...some operation with source..., product::setProductType);
setOptionalParameter(...some operation with source..., product::setMaterial);
setOptionalParameter(...some operation with source..., product::setUnitPricingBaseMeasure);
setOptionalParameter(...some operation with source..., product::setUnitPricingMeasure);
}
private static <T> void setOptionalParameter(T value, Consumer<T> consumer) {
try {
consumer.accept(value);
} catch (IllegalArgumentException ignored) {}
}
I am running some unit tests and debugging but the code doesn't behave as previously as the IllegalArgumentException is not catched but raised so the program fails.
Any idea on how to solve this enclosing the try-catch logic in a single place?
I think the problem might be that the exception is thrown by the code that gets the arguments to be passed to the setters. So one possible approach would be to make that part of the code lazy by using a Supplier, then invoke .get() on the Supplier inside a the try/catch block (as well as invoking the Consumer):
private static <T> void setOptionalParameter(
Supplier<? extends T> supplier,
Consumer<? super T> consumer) {
try {
consumer.accept(supplier.get());
} catch (IllegalArgumentException ignored) {
}
}
You could invoke that method as follows:
setOptionalParameter(() -> ...some operation with source..., product::setProductType);
Note that I've improved the signature of your method so that it now accepts a wider range of generic subtypes and supertypes for the Supplier and Consumer, respectively.
EDIT: As per the comments, the approach above might be not flexible enough, i.e. if the method accepts more than one argument, etc. In this case, it would be better to use a Runnable instance:
private static void setOptionalParameter(Runnable action) {
try {
action.run();
} catch (IllegalArgumentException ignored) {
}
}
And invocation would now become:
setOptionalParameter(() -> {
ProductType productType = ...some operation with source...;
Material material = ...some operation with source...;
product.doSomethingWith2Args(productType, material);
});

Handle Hibernate optimistic locking with Spring

I am using Hibernate and Spring Data, it will perform optimistic locking when insert or update an entity, and if the version in database doesn't match with the one to persist, it will throw exception StaleObjectStateException, in Spring, you need to catch it with ObjectOptimisticLockingFailureException.
What I want to do is catch the exception and ask the user to refresh the page in order to get the latest data from database like below:
public void cancelRequest()
{
try
{
request.setStatus(StatusEnum.CANCELLED);
this.request = topUpRequestService.insertOrUpdate(request);
loadRequests();
//perform other tasks...
} catch (ObjectOptimisticLockingFailureException ex)
{
FacesUtils.showErrorMessage(null, "Action Failed.", FacesUtils.getMessage("message.pleaseReload"));
}
}
I assume it will also work with the code below but I have not tested it yet.
public void cancelRequest()
{
RequestModel latestModel = requestService.findOne(request.getId());
if(latestModel.getVersion() != request.getVersion())
{
FacesUtils.showErrorMessage(null, "Action Failed.", FacesUtils.getMessage("message.pleaseReload"));
}
else
{
request.setStatus(StatusEnum.CANCELLED);
this.request = requestService.insertOrUpdate(request);
loadRequests();
//perform other tasks...
}
}
I need to apply this checking on everywhere I call requestService.insertOrUpdate(request); and I don't want to apply them one by one. Therefore, I decide to place the checking code inside the function insertOrUpdate(entity) itself.
#Transactional
public abstract class BaseServiceImpl<M extends Serializable, ID extends Serializable, R extends JpaRepository<M, ID>>
implements BaseService<M, ID, R>
{
protected R repository;
protected ID id;
#Override
public synchronized M insertOrUpdate(M entity)
{
try
{
return repository.save(entity);
} catch (ObjectOptimisticLockingFailureException ex)
{
FacesUtils.showErrorMessage(null, FacesUtils.getMessage("message.actionFailed"),
FacesUtils.getMessage("message.pleaseReload"));
return entity;
}
}
}
My main question is, there will be one problem with this approach. The caller side will not know whether the entity persisted successfully or not since the exception will be caught and handled inside the function, so the caller side will always assume the persist was success, and continue do the other tasks, which is I don't want. I want it to stop performing tasks if fail to persist:
public void cancelRequest()
{
try
{
request.setStatus(StatusEnum.CANCELLED);
this.request = topUpRequestService.insertOrUpdate(request);
//I want it to stop here if fail to persist, don't load the requests and perform other tasks.
loadRequests();
//perform other tasks...
} catch (ObjectOptimisticLockingFailureException ex)
{
FacesUtils.showErrorMessage(null, "Action Failed.", FacesUtils.getMessage("message.pleaseReload"));
}
}
I know when calling the insertOrUpdate , I can catch the returned entiry by declaring new model variable, and compare it's version to the original one, if version is same, means the persistance was failed. But if I doing it this way, I have to write the version checking code on everywhere I call insertOrUpdate. Any better approach then this?
The closest way to being able to do this and not having to necessarily make significant code changes at all the invocation points would be to look into some type of Spring AOP advice that works similar to Spring's #Transactional annotation.
#FacesReloadOnException( ObjectOptimisticLockingFailureException.class )
public void theRequestHandlerMethod() {
// call your service here
}
The idea is that the #FacesReloadOnException annotation triggers an around advice that catches any exception provided in the annotation value and does basically handles the call the FacesUtils should any of those exception classes be thrown.
The other options you have available aren't going to be nearly as straight forward and will require that you touch all your usage points in some fashion, its just inevitable.
But I certainly would not consider putting the try/catch block in the service tier if you don't want to alter your service tier's method return types because the controllers are going to need more context as you've pointed out. The only way to push that try/catch block downstream would be if you returned some type of Result object that your controller could then inspect like
public void someControllerRequestMethod() {
InsertOrUpdateResult result = yourService.insertOrUpdate( theObject );
if ( result.isSuccess() ) {
loadRequests();
}
else {
FacesUtils.showErrorMessage( ... );
}
}
Otherwise you'd need to get creative if you want to somehow centralize this in your web tier. Perhaps a web tier utility class that mimics your BaseService interface like the following:
public <T extends BaseService, U> U insertOrUpdate(T service, U object, Consumer<U> f) {
try {
U result = service.insertOrUpdate( object );
f.accept( result );
return result;
}
catch ( ObjectOptimisticLockingFailureException e ) {
FacesUtils.showErrorMessage( ... );
}
}
But being frank, unless you have a lot of call sites that are similar enough to where such a generalization with a consumer like this makes sense, you may find its more effort and work to generalize it than it would to just place the try/catch block in the controller itself.

CompletableFuture exceptionally breaks the work chain

The idea of using CompletableFuture is because it offers a chain, while the first several steps encapsulate beans before the last step uses it. Because any exception may happen in these steps and exceptionally is used to handle error. However, exceptionally only accepts Throwable argument and so far I haven't found a way to grab those encapsulated beans.
CompletableFuture.supplyAsync(this::msgSource)
.thenApply(this::sendMsg).exceptionally(this::errorHandler).thenAccept(this::saveResult)
public List<Msg> msgSource() // take message from somewhere.
public List<Msg> sendMsg(List<Msg>) // exceptions may happen like 403 or timeout
public List<Msg> errorHandler() // set a success flag to false in Msg.
public void saveResult(List<Msg>) // save send result like success or false in data center.
In the above example, comments are the working flow. However, since errorHandler neither accepts List<Msg> nor passes it on, so the chain is broken. How to get the return from msgSource?
EDIT
public class CompletableFutureTest {
private static Logger log = LoggerFactory.getLogger(CompletableFutureTest.class);
public static void main(String[] args) {
CompletableFutureTest test = new CompletableFutureTest();
CompletableFuture future = new CompletableFuture();
future.supplyAsync(test::msgSource)
.thenApply(test::sendMsg).exceptionally(throwable -> {
List<String> list = (List<String>) future.join(); // never complete
return list;
}).thenAccept(test::saveResult);
try {
future.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
private List<String> saveResult(List<String> list) {
return list;
}
private List<String> sendMsg(List<String> list) {
throw new RuntimeException();
}
public List<String> msgSource() {
List<String> result = new ArrayList<>();
result.add("1");
result.add("2");
return result;
}
}
A chain implies that each node, i.e. completion stage, uses the result of the previous one. But if the previous stage failed with an exception, there is no such result. It’s a special property of your sendMsg stage that its result is just the same value as it received from the previous stage, but that has no influence on the logic nor API design. If sendMsg fails with an exception, it has no result that the exception handler could use.
If you want to use the result of the msgSource stage in the exceptional case, you don’t have a linear chain any more. But CompletableFuture does allow to model arbitrary dependency graphs, not just linear chains, so you can express it like
CompletableFuture<List<Msg>> source = CompletableFuture.supplyAsync(this::msgSource);
source.thenApply(this::sendMsg)
.exceptionally(throwable -> {
List<Msg> list = source.join();
for(Msg m: list) m.success = false;
return list;
})
.thenAccept(this::saveResult);
However, there is no semantic difference nor advantage over
CompletableFuture.runAsync(() -> {
List<Msg> list = msgSource();
try {
list = sendMsg(list);
} catch(Throwable t) {
for(Msg m: list) m.success = false;
}
saveResult(list);
});
which expresses the same logic as an ordinary code flow.

Spring Beans constructed multiple times?

I am teaching myself how to use REST Assured and Spring right now. I am running into a few problems with the Spring Beans. Below is the System.println output from the REST Assured gets every time a bean is created. As of now, it should actually only be created once per use of the beans (I would imagine or at least that's what I want).
Top of Cucumber Steps
private BasicApi guideBox;
private ApplicationContext context = new AnnotationConfigApplicationContext(BaseApiConfig.class);
It is important to note here that the Application Context is used in each scenario to give guideBox what it needs for each scenario.
The output below is currently generated for each cucumber scenario indicating that the 3 beans I am currently using are created and initialized before each scenario is run. This output occurs three times meaning the beans are created three times; once before each of the three scenarios. As you can see from the first result giving an error for too many API requests, this is all happening too fast and too often. Is there a way to stop bean creation until that specific bean is needed, or is every bean going to be created every time? Is there a way to create all the beans just one time instead of before every scenario?
Output During Each Scenario
{"error":"You are sending API requests too quickly. You are limited to 1 API request per second. Please refer to the API docs for more information."}
{"results":[{"id":2098,"title":"Arrested Development","alternate_titles":[],"container_show":0,"first_aired":"2003-11-02","imdb_id":"tt0367279","tvdb":72173,"themoviedb":4589,"freebase":"\/m\/02hct1","wikipedia_id":496020,"tvrage":{"tvrage_id":2649,"link":"http:\/\/www.tvrage.com\/shows\/id-2649"},"artwork_208x117":"http:\/\/static-api.guidebox.com\/091414\/thumbnails_small\/2098-4213483650-208x117-show-thumbnail.jpg","artwork_304x171":"http:\/\/static-api.guidebox.com\/091414\/thumbnails_medium\/2098-6882581105-304x171-show-thumbnail.jpg","artwork_448x252":"http:\/\/static-api.guidebox.com\/091414\/thumbnails_large\/2098-7307781619-448x252-show-thumbnail.jpg","artwork_608x342":"http:\/\/static-api.guidebox.com\/091414\/thumbnails_xlarge\/2098-677562375-608x342-show-thumbnail.jpg"}],"total_results":1}
{"results":[{"id":1,"region":"US","name":"United States","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/us.png"},{"id":12,"region":"AI","name":"Anguilla","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/ai.png"},{"id":11,"region":"AG","name":"Antigua and Barbuda","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/ag.png"},{"id":16,"region":"AR","name":"Argentina","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/ar.png"},{"id":14,"region":"AM","name":"Armenia","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/am.png"},{"id":3,"region":"AU","name":"Australia","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/au.png"},{"id":17,"region":"AT","name":"Austria","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/at.png"},{"id":18,"region":"AZ","name":"Azerbaijan","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/az.png"},{"id":28,"region":"BS","name":"Bahamas","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/bs.png"},{"id":23,"region":"BH","name":"Bahrain","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/bh.png"},{"id":31,"region":"BY","name":"Belarus","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/by.png"},{"id":20,"region":"BE","name":"Belgium","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/be.png"},{"id":32,"region":"BZ","name":"Belize","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/bz.png"},{"id":25,"region":"BM","name":"Bermuda","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/bm.png"},{"id":27,"region":"BO","name":"Bolivia","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/bo.png"},{"id":30,"region":"BW","name":"Botswana","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/bw.png"},{"id":8,"region":"BR","name":"Brazil","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/br.png"},{"id":108,"region":"VG","name":"British Virgin Islands","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/vg.png"},{"id":26,"region":"BN","name":"Brunei","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/bn.png"},{"id":22,"region":"BG","name":"Bulgaria","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/bg.png"},{"id":75,"region":"KH","name":"Cambodia","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/kh.png"},{"id":4,"region":"CA","name":"Canada","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/ca.png"},{"id":39,"region":"CV","name":"Cape Verde","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/cv.png"},{"id":79,"region":"KY","name":"Cayman Islands","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/ky.png"},{"id":35,"region":"CL","name":"Chile","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/cl.png"},{"id":37,"region":"CO","name":"Colombia","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/co.png"},{"id":38,"region":"CR","name":"Costa Rica","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/cr.png"},{"id":40,"region":"CY","name":"Cyprus","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/cy.png"},{"id":41,"region":"CZ","name":"Czech Republic","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/cz.png"},{"id":42,"region":"DK","name":"Denmark","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/dk.png"},{"id":43,"region":"DM","name":"Dominica","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/dm.png"},{"id":44,"region":"DO","name":"Dominican Republic","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/do.png"},{"id":46,"region":"EC","name":"Ecuador","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/ec.png"},{"id":48,"region":"EG","name":"Egypt","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/eg.png"},{"id":114,"region":"SV","name":"El Salvador","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/sv.png"},{"id":47,"region":"EE","name":"Estonia","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/ee.png"},{"id":52,"region":"FM","name":"Federated States Of Micronesia","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/fm.png"},{"id":51,"region":"FJ","name":"Fiji","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/fj.png"},{"id":50,"region":"FI","name":"Finland","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/fi.png"},{"id":9,"region":"FR","name":"France","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/fr.png"},{"id":55,"region":"GM","name":"Gambia","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/gm.png"},{"id":7,"region":"DE","name":"Germany","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/de.png"},{"id":54,"region":"GH","name":"Ghana","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/gh.png"},{"id":56,"region":"GR","name":"Greece","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/gr.png"},{"id":53,"region":"GD","name":"Grenada","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/gd.png"},{"id":57,"region":"GT","name":"Guatemala","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/gt.png"},{"id":58,"region":"GW","name":"Guinea-Bissau","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/gw.png"},{"id":61,"region":"HN","name":"Honduras","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/hn.png"},{"id":60,"region":"HK","name":"Hong Kong","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/hk.png"},{"id":63,"region":"HU","name":"Hungary","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/hu.png"},{"id":67,"region":"IN","name":"India","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/in.png"},{"id":64,"region":"ID","name":"Indonesia","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/id.png"},{"id":65,"region":"IE","name":"Ireland","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/ie.png"},{"id":66,"region":"IL","name":"Israel","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/il.png"},{"id":69,"region":"IT","name":"Italy","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/it.png"},{"id":72,"region":"JP","name":"Japan","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/jp.png"},{"id":71,"region":"JO","name":"Jordan","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/jo.png"},{"id":81,"region":"LA","name":"Lao People\u2019s Democratic Republic","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/la.png"},{"id":88,"region":"LV","name":"Latvia","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/lv.png"},{"id":82,"region":"LB","name":"Lebanon","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/lb.png"},{"id":86,"region":"LT","name":"Lithuania","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/lt.png"},{"id":87,"region":"LU","name":"Luxembourg","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/lu.png"},{"id":94,"region":"MO","name":"Macau","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/mo.png"},{"id":140,"region":"MY","name":"Malaysia","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/my.png"},{"id":97,"region":"MT","name":"Malta","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/mt.png"},{"id":98,"region":"MU","name":"Mauritius","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/mu.png"},{"id":5,"region":"MX","name":"Mexico","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/mx.png"},{"id":93,"region":"MN","name":"Mongolia","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/mn.png"},{"id":141,"region":"MZ","name":"Mozambique","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/mz.png"},{"id":142,"region":"NA","name":"Namibia","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/na.png"},{"id":146,"region":"NL","name":"Netherlands","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/nl.png"},{"id":6,"region":"NZ","name":"New Zealand","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/nz.png"},{"id":145,"region":"NI","name":"Nicaragua","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/ni.png"},{"id":143,"region":"NE","name":"Niger","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/ne.png"},{"id":147,"region":"NO","name":"Norway","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/no.png"},{"id":149,"region":"OM","name":"Oman","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/om.png"},{"id":150,"region":"PA","name":"Panama","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/pa.png"},{"id":126,"region":"PY","name":"Paraguay","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/py.png"},{"id":151,"region":"PE","name":"Peru","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/pe.png"},{"id":153,"region":"PH","name":"Philippines","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/ph.png"},{"id":155,"region":"PL","name":"Poland","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/pl.png"},{"id":125,"region":"PT","name":"Portugal","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/pt.png"},{"id":127,"region":"QA","name":"Qatar","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/qa.png"},{"id":89,"region":"MD","name":"Republic Of Moldova","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/md.png"},{"id":128,"region":"RO","name":"Romania","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/ro.png"},{"id":129,"region":"RU","name":"Russia","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/ru.png"},{"id":130,"region":"SA","name":"Saudi Arabia","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/sa.png"},{"id":134,"region":"SG","name":"Singapore","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/sg.png"},{"id":136,"region":"SK","name":"Slovakia","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/sk.png"},{"id":135,"region":"SI","name":"Slovenia","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/si.png"},{"id":111,"region":"ZA","name":"South Africa","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/za.png"},{"id":49,"region":"ES","name":"Spain","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/es.png"},{"id":84,"region":"LK","name":"Sri Lanka","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/lk.png"},{"id":76,"region":"KN","name":"St. Kitts and Nevis","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/kn.png"},{"id":115,"region":"SZ","name":"Swaziland","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/sz.png"},{"id":133,"region":"SE","name":"Sweden","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/se.png"},{"id":34,"region":"CH","name":"Switzerland","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/ch.png"},{"id":124,"region":"TW","name":"Taiwan","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/tw.png"},{"id":119,"region":"TJ","name":"Tajikistan","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/tj.png"},{"id":118,"region":"TH","name":"Thailand","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/th.png"},{"id":123,"region":"TT","name":"Trinidad and Tobago","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/tt.png"},{"id":122,"region":"TR","name":"Turkey","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/tr.png"},{"id":120,"region":"TM","name":"Turkmenistan","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/tm.png"},{"id":104,"region":"UG","name":"Uganda","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/ug.png"},{"id":103,"region":"UA","name":"Ukraine","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/ua.png"},{"id":10,"region":"AE","name":"United Arab Emirates","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/ae.png"},{"id":2,"region":"GB","name":"United Kingdom","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/gb.png"},{"id":107,"region":"VE","name":"Venezuela","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/ve.png"},{"id":109,"region":"VN","name":"Vietnam","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/vn.png"},{"id":112,"region":"ZW","name":"Zimbabwe","map_img":"http:\/\/static-api.guidebox.com\/misc\/flags_iso\/48\/zw.png"}]}
Java Config File
Just in case there is something wrong with how I am configuring my config file, here it is.
#Configuration
#PropertySources(
#PropertySource(value = {"classpath:/properties/guideBox.properties"}))
public class BaseApiConfig
{
#Bean
public GuideBoxProperties properties()
{
return new GuideBoxProperties();
}
#Bean
public BasicApi provideBasicApi()
{
return new BasicApi();
}
#Bean
public BasicApi provideHome() throws Exception
{
return new BasicApi(properties().getApiFull());
}
#Bean
public BasicApi provideArrestedDevleopmentSearch() throws Exception
{
return new BasicApi(properties().getArrestedDevelopmentSearch());
}
#Bean
public BasicApi provideAllRegions() throws Exception
{
return new BasicApi(properties().getAllRegions());
}
}
A Cucumber Scenario
#Given("^that the database contains \"([^\"]*)\"$")
public void that_the_database_contains(String title)
{
showTitle = title;
try
{
guideBox = (BasicApi) context.getBean("provideArrestedDevleopmentSearch");
}
catch (Exception e)
{
guideBox.basicHandle("Init Error: ", e);
}
}
#When("^the client requests a database search for Arrested Development$")
public void the_client_requests_a_database_search_for_Arrested_Development()
{
try {
guideBox.searchJson("results.title");
}
catch (Exception e)
{
guideBox.basicHandle("Json Search Error: ", e);
}
}
#Then("^the title should be visible in the search results$")
public void the_title_should_be_visible_in_the_search_results()
{
try
{
Assert.assertThat(guideBox.getJsonResults(), CoreMatchers.containsString(showTitle));
}
catch(Exception e)
{
guideBox.basicHandle("Assertion Error: ", e);
}
}
UPDATE 1
I managed to fix the problem in a general sense. I made the BasicApi parameterized constructor less busy, resulting in a bit more code in the step defs to manually control some requests. This got rid of the too many API request error.
That being said, although the program now works as expected, my question does still stand, as I think (or hope) that there is probably a better way to do this than using the ApplicationContext the way I am using it.

Resources