How to write code for adaptor to get ad from our user defined network in adwhirl - adwhirl

I implemented one interface in that it has to implement requestAd on success and failure, onLeaveApplication, onPresentScreen , onReceiveAd. I also extended the AdwhirlLayout class. I implemented only two methods in Adaptor.java class requestAd on success and failure only by these lines
public void requestAdSuccess() {
// TODO Auto-generated method stub
adWhirlLayout.adWhirlManager.resetRollover();
adWhirlLayout.nextView = adView;
adWhirlLayout.handler.post(adWhirlLayout.viewRunnable);
adWhirlLayout.rotateThreadedDelayed();
}
public void requestAdFail() {
// TODO Auto-generated method stub
adView.setAdListener(null);
adWhirlLayout.rollover();
}
public void onLeaveApplication(Ad arg0) {
// TODO Auto-generated method stub
}
public void onPresentScreen(Ad arg0) {
// TODO Auto-generated method stub
}
public void onReceiveAd(Ad arg0) {
// TODO Auto-generated method stub
}
I refresh my ad every 15 seconds. I wrote this based on GoogleAdAdaptor.java code in adwhirl sample. What else do I have to add to the code in onLeaveApplication()?

Please read my response to a similar question here for information about implementing custom events.
From the code you've posted here, AdWhirlLayout doesn't have a nextView so I don't think adWhirlLayout.nextView = adView; will work. Also, I think you will want to post the view runnable like this:
adWhirlLayout.handler.post(new ViewAdRunnable(adWhirlLayout, adView));
As far as I know, you're not missing anything in onLeaveApplication, unless the specific ad network you're working with does something special on leave.

Related

Apache HttpAsyncClient and CountDownLatch

When using apache htttpasyncclient how does one handle various exception cases properly? Consider the following pseudo code based on this example where I have added the consumer parameter to the execute call. The intention is to make an asynchronous http request where the data is processed as a stream when the bytes come in rather than waiting for the full response to be done before processing. Various issues can occur such as a timeout exception on the http request, failure to connect (could be no network), etc. Is it always guaranteed that for example on a timeout with a response not coming back in time that releaseResources() is always called. The question is where does latch.countDown() need to be put in the below code to always guarantee that the await call doesn't just hang no matter what the exception. Is the call to latch.countDown() in StreamConsumer.releaseResources() enough to prevent hanging on the await?
public static void main(final String[] args) throws Exception {
client.execute(HttpAsyncMethods.createGet(u), new StreamConsumer(...), new FutureCallback<Boolean>() {
#Override
public void cancelled() {
// Is latch call needed here?
// latch.countDown();
}
#Override
public void completed(Boolean response) {
// Is latch call needed here?
// latch.countDown();
}
#Override
public void failed(Exception e) {
// Is latch call needed here?
// latch.countDown();
}
});
latch.await();
}
static class StreamConsumer extends AsyncByteConsumer<Boolean> {
#Override
protected void onResponseReceived(final HttpResponse response) {
latch.countDown();
}
#Override
protected void onByteReceived(final ByteBuffer buf, final IOControl ioctrl) throws IOException {
}
#Override
protected void releaseResources() {
latch.countDown();
}
}
CloseableHttpAsyncClient#execute method terminates immediately upon submission of a request into the request execution pipeline and returns a Future object representing the future result of the operation.
Therefore the latch in the example is required to make sure that the client does not get shut down immediately after CloseableHttpAsyncClient#execute call.
If one uses CloseableHttpAsyncClient as a singleton with a defined life-cycle (as one should) synchronization of request completion and the client shutdown may be unnecessary.

how to execute piece of code in hadoop cluster nodes?

I created a hadoop multinode cluster and my target is to know processor information of all nodes in the cluster by running jar file in master.I have the code to know processor info in a node.How can i run this code in all nodes and retrieve the processor information using java.
thanks in advance for help..
Driver code:
Here i have used only mapper class
public class ProcInfoCluster extends Configured implements Tool {
#Override
public int run(String[] arg0) throws Exception {
// TODO Auto-generated method stub
if(arg0.length<2)
{
System.out.println("please provide the output file paths");
return -1;
}
JobConf conf=new JobConf(ProcInfoCluster.class);
conf.setJobName("ProcesorInfo");
FileInputFormat.setInputPaths(conf, new Path(arg0[0]));
FileOutputFormat.setOutputPath(conf,new Path(arg0[1]));
conf.setMapperClass(ProcInfoMapper.class);
//conf.setReducerClass(WordReducer.class);
conf.setMapOutputKeyClass(Text.class);
conf.setMapOutputValueClass(Text.class);
conf.setOutputKeyClass(Text.class);
conf.setOutputValueClass(Text.class);
JobClient.runJob(conf);
return 0;
}
public static void main(String args[])
throws Exception
{
int exitCode=ToolRunner.run(new ProcInfoCluster(), args);
System.exit(exitCode);
}
}
Mapper code:
Here in this mapper code i have written code to know processor information and tried to send it as key value pairs
public class ProcInfoMapper extends MapReduceBase implements Mapper<LongWritable, Text, Text,Text>
{
#Override
//map function to retrieve processor information of all nodes
public void map(LongWritable key, Text value,
OutputCollector output, Reporter reporter)
throws IOException {
// TODO Auto-generated method stub
String no=System.getenv("PROCESSOR_ARCHITEW6432");
//to know processor info
System.out.println(no);
String s=new String("ProcInfo");
output.collect(new Text(s), new Text(no));
}
}
and i had a doubt that whether we can write a map reduce application only with mapper class without the reducer class

What's the meaning of Proctectable interface in JUnit source code?

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.

How should I handle exceptions within a controller constructor in WebAPI?

Say I have a constructor where it's initialization can potentially throw an exception due to reasons beyond my control.
FantasticApiController(IAwesomeGenerator awesome,
IBusinessRepository repository, IIceCreamFactory factory)
{
Awesome = awesome;
Repository = repository;
IceCream = factory.MakeIceCream();
DoSomeInitialization(); // this can throw an exception
}
Ordinarily, when a Controller action in WebAPI throws an exception I can handle it via a csutom ExceptionFilterAttribute:
public class CustomErrorHandler
{
public override void OnException(HttpActionExecutedContext context)
{
// Critical error, this is real bad.
if (context.Exception is BubonicPlagueException)
{
Log.Error(context.Exception, "CLOSE EVERYTHING!");
Madagascar.ShutdownAllPorts();
}
// No big deal, just show something user friendly
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent("Hey something bad happened. " +
"Not closing the ports though"),
StatusCode = HttpStatusCode.InternalServerError;
});
}
So if I have a have a BoardPlane API method which throws a BubonicPlagueException, then my CustomerErrorHandler will shut down the ports to Madagascar and log it as an error as expected. In other instances when it's not really serious, I just display some user friendly message and return a 500 InternalServerError.
But in those cases where DoSomeInitialization throws an exception, this does absolutely nothing. How can I handle exceptions in WebAPI controller constructors?
The WebApi Controllers are created, and thus constructors called via HttpControllerActivators. The default activator is System.Web.Http.Dispatcher.DefaultHttpControllerActivator.
Very rough examples for options 1 & 2 on github here https://github.com/markyjones/StackOverflow/tree/master/ControllerExceptionHandling/src
Option 1 which works quite nicely involves the use of a DI container (you may well be using one already). I have used Ninject for my example and have used "Interceptors" Read More to intercept and try/catch calls to the Create method on the DefaultHttpControllerActivator. I know of at least AutoFac and Ninject that can do something simlar to to the following:
Create the interceptor
I don't know what the lifetime scope of your Madagascar and Log items are but they could well be injected into your Interceptor
public class ControllerCreationInterceptor : Ninject.Extensions.Interception.IInterceptor
{
private ILog _log;
private IMadagascar _madagascar;
public ControllerCreationInterceptor(ILog log, IMadagascar madagascar)
{
_log = log;
_madagascar = madagascar;
}
But keeping to the example in your question where Log and Madagascar are some kind of Static global
public class ControllerCreationInterceptor : Ninject.Extensions.Interception.IInterceptor
{
public void Intercept(Ninject.Extensions.Interception.IInvocation invocation)
{
try
{
invocation.Proceed();
}
catch(InvalidOperationException e)
{
if (e.InnerException is BubonicPlagueException)
{
Log.Error(e.InnerException, "CLOSE EVERYTHING!");
Madagascar.ShutdownAllPorts();
//DO SOMETHING WITH THE ORIGIONAL ERROR!
}
//DO SOMETHING WITH THE ORIGIONAL ERROR!
}
}
}
FINALLY Register the interceptor In global asax or App_Start (NinjectWebCommon)
kernel.Bind<System.Web.Http.Dispatcher.IHttpControllerActivator>()
.To<System.Web.Http.Dispatcher.DefaultHttpControllerActivator>().Intercept().With<ControllerCreationInterceptor>();
Option 2 is to implement your own Controller Activator implementing the IHttpControllerActivator interface and handle the error in creation of the Controller in the Create method. You could use the decorator pattern to wrap the DefaultHttpControllerActivator:
public class YourCustomControllerActivator : IHttpControllerActivator
{
private readonly IHttpControllerActivator _default = new DefaultHttpControllerActivator();
public YourCustomControllerActivator()
{
}
public System.Web.Http.Controllers.IHttpController Create(System.Net.Http.HttpRequestMessage request, System.Web.Http.Controllers.HttpControllerDescriptor controllerDescriptor, Type controllerType)
{
try
{
return _default.Create(request, controllerDescriptor, controllerType);
}
catch (InvalidOperationException e)
{
if (e.InnerException is BubonicPlagueException)
{
Log.Error(e.InnerException, "CLOSE EVERYTHING!");
Madagascar.ShutdownAllPorts();
//DO SOMETHING WITH THE ORIGIONAL ERROR!
}
//DO SOMETHING WITH THE ORIGIONAL ERROR!
return null;
}
}
}
Once you have your own custom activator the default activator can be switched out in the global asax :
GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerActivator), new YourCustomControllerActivator());
Option 3 Of course if your initialisation in the constructor doesn't need access to the actual Controllers methods, properties etc... i.e. assuming it could be removed from the constructor... then it would be far easier to just move the initialisation to a filter e.g.
public class MadagascarFilter : AbstractActionFilter
{
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
try{
DoSomeInitialization(); // this can throw an exception
}
catch(BubonicPlagueException e){
Log.Error(e, "CLOSE EVERYTHING!");
Madagascar.ShutdownAllPorts();
//DO SOMETHING WITH THE ERROR
}
base.OnActionExecuting(actionContext);
}
public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
{
base.OnActionExecuted(actionExecutedContext);
}
public override bool AllowMultiple
{
get { return false; }
}
}

JMS MessageCreator.createMessage() in Grails

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