mercredi 25 janvier 2017

How to create a common AsyncTask class for webservice call in an android app?

I am trying to write a common webservice class where in any of the activities within my application has to point to this common class for webservice stuff. Currently I got stuck in between i.e; to pass the success/failure message to the calling class, My current implementation is like below, I have an interface class where in I have 2 methods,

 public void webServiceReqExecutedSuccessfully();
 public void webSerReqFailed();

and each webservice calling class implements these methods as per their requirements. And my common webservice class is like below,

    public class WebServiceRequest extends AsyncTask < String, Void, Boolean> 
    {
            
        private static final MediaType FORM_DATA_TYPE = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
            
            public enum HTTPServiceTags {
            
          POST_IT,
          GET_ALL_ITEMS
         }

         HTTPServiceTags requestTag;
         public ATWebServiceRequest(HTTPServiceTags reqTag, Callable < Void > _ServiceResponseSuccess, Callable < Void > _ServiceResponseFailure) {
          this.requestTag = reqTag;
         }

         @Override
         protected Boolean doInBackground(String...postDataSet) {
          Boolean result = true;
          String requestURL = postDataSet[0];
          String postBody = getPostBody(postDataSet);
          Log.d(requestURL, postBody);
          try {
           OkHttpClient client = new OkHttpClient();
           RequestBody body = RequestBody.create(FORM_DATA_TYPE, postBody);
           Request request = new Request.Builder().url(requestURL).post(body).build();
           Response response = client.newCall(request).execute();
          } catch (IOException exception) {
           result = false;
          }
          return result;
         }

         @Override
         protected void onPostExecute(Boolean result) {
          if (result) {
           switch (requestTag) {
            case POST_IT:
//HOW CAN I NOTIFY/INVOKE webServiceReqExecutedSuccessfully METHOD OF THE CALLING CLASS HERE??? 
             break;
            case GET_ALL_ITEMS:
             break;
            default:
             break;
           }
          }
         }
        }

My question here is after the service call response how can I notify/invoke the calling class interface methods(webServiceReqExecutedSuccessfully() / webSerReqFailed()) from which object reference? Any help is appreciated in advance. Thanks

Call method in foreach with clean code

I'm using DomDocument to access a HTML page and convert into a Object but every time I need to search nodes with some different tag. I want a method with the logic name as parameter, but each logic have different number of parameters.

public function foo(){
    $this->findTag('bar', $parameters);
}
public function findTag($logic, $parameters){
    foreach ($this->dom->getElementsByTagName($this->tag) as $node) {
        $this->$logic($node, $parameters);
    }
}
public function logic1($node, $foo, $bar){
    //something with $foo and $bar
}
public function logic2($node, $fooBar){
    //something with $fooBar
}

This is a bad approach? How can I make this foreach a unique function always called when needed some info from the DomObject, using a different tag.

Design pattern for surrounding code in start, complete and fail methods

Suppose I have various arbitrary sections of code to run, but before each section, I have to run a Start() method and then after each section I need to run a Complete() method. However, if an exception is thrown in the code section, I want to run a Fail(string message) method instead of Complete(). Is there a design pattern that elegantly encapsulates this to make it neat and easily repeatable?

For example, let's say I have a type called Thing that contains a Start() method that adds a row to a logging db table to reflect that a task is in progress, a Complete() method that changes that row to reflect that the task finished and a Fail(string message) method that changes the row to reflect that the task failed. These are just examples though, they could be doing any set-up and tidy up type tasks.

The naive implementation might be simply to call those methods manually:

public void DoStuff()
{
    var thing = new Thing();
    thing.Start();
    try
    {
        DoImportantStuff();
        thing.Complete();
    }
    catch (Exception e)
    {
        thing.Fail(e.Message);
    }
}

But if I'm going to have to repeat this in a lot of different places, it ends up creating quite a lot of duplication and it might be easy to forget to call Complete or mess this up in some subtle way.

In C#, there's the using pattern, which provides a good way of encapsulating most of this. For example, if my Thing type looked like this:

public class Thing : IDisposable
{
    public Thing(){
        Start();
    }

    private void Start() { /* start */ }
    private void Complete() { /* complete */ }

    public void Dispose()
    {
        Complete();
    }
}

My DoStuff() method could now be simplified to this:

public void DoStuff()
{
    using(new Thing())
    {
        DoImportantStuff();
    }
}

Which is much nicer. But it doesn't allow me to call Fail instead of Complete if an exception is thrown because (I think!) the Dispose method is essentially called in a Finally block.

I have thought of having a try/catch inside the using block and then setting a thing.HasFailed flag inside the catch block and then using that in the Dispose method to decide whether to Complete or Fail. But that seems a bit fiddly and I'd like the consumer of Thing to have to do as little as possible to make it work correctly.

So is there a design pattern that encapsulates what I want to do and avoids the need to manually write a try\catch each time?

In which direction to make the association in domain model

Is there some rule of thumb, in which direction to make the association when designing domain model?

For example, we have products in the stock. Stock status of a product is a rather complex data structure, containing enumerations of multiple variations of the product either being in the stock, being out of stock or being bookable. Thus we make a seperate object of the stock status associated with the product. Now the question is, if product object should have a reference to it's stock status, or stock status have a reference to a particular product.

First solution feels like, it's not the real concern of product knowing it's stock state. Product is just a product, and maybe we should manipulate them in different context, where stocking is not a concern. In the other hand, stock status being a root feels awkward, as when thinking about stock, first we think about a product being in the stock.

How to decide, which entity acts as a root for the association?

mardi 24 janvier 2017

Comparing two csv files and outputting matches using Java

I have two csv files

One csv file with one column: user agent strings (10,000 count)

Another csv file with 3 columns: regex pattern, rank, and type (86 count)

I was told to create a program that would test all the user agent strings with the regex patterns and have a file that outputted two columns:

User Agents and their type based on the tests.

Is there any way to do this? I've been working at this for a week with no solution in sight.

Modular promises and Promise.all()

I have a bunch of functions that return promises that I want to make generalized, and so I write them like this:

function prf1(data){
    var promise = new Promise(function(resolve,reject){
        //some stuff here
        data.new_variable1 = 1;
        resolve(data);
    });
    return promise;
)};

function prf2(data){
    var promise = new Promise(function(resolve,reject){
        //some stuff here involving data.new_variable1 or something else
        data.new_variable2 = 2;
        resolve(data);
    });
    return promise;
)};

function prf3(data){
    var promise = new Promise(function(resolve,reject){
        //some stuff here involving data.new_variable2 or data.new_variable1 or something else
        data.new_variable3 = 3;
        resolve(data);
    });
    return promise;
)};

I resolve data in each function because I plan to have a lot of these types of functions, and I don't know the order they'll be called in while chaining:

prf1(somedata)
.then(prf3)
.then(prf5)
.then(prf2)
//etc

This works fine until I have to do Promise.all:

 Promise.all([
    prf1(somedata),
    prf2(somedata)
 ])
.then(prf3)
//etc

This gives me errors, because the new promise returned by Promise.all() is an object that contains both resolutions from prf1 and prf2. Essentially, in prf3, I can't access data.new_variable1 or data.new_variable2 because the resulting promise is [somedata, somedata].

Is there a pattern I can follow to help me achieve what I need to do? I need to make the promises modular providing them with as much data as possible.

Adding and abstract subclass in PHP without modifying all the inheriting children classes

I have a similar class hierarchy

interface ISomething
{
    public function foo();
    ...
}

abstract class TopAbstract implements ISomething
{
    ...
}

abstract class HighAbstract extends TopAbstract 
{
    public function foo()
    {
        ...
    }
}

and 46(!) classes that inherit from HighAbstract 

class One extends HighAbstract
{
}

...

class FortySix extends HighAbstract
{
}

Now I have to add functionnality and that requires having an alternate HighAbstract::foo() (amongst other things). What would be the best way to achieve that?

  • I could just modify HighAbstract but I'd like to keep that new functionality separate (separation of concern)

  • I could add a subclass to HighAbstract but then I would have to edit the 46 subclasses to change their parent.

  • I could add a trait to HighAbstract but that still implies modifying it (HighAbstract) with branching and using the trait in HighAbstract::foo()

  • Any other ideas?

I think using the trait with minimal edits in HighAbstract may be the least bad solution, that way the code is somewhat separated and if the new functionality is ever dropped, it could be done with minimal changes.

What do you think?

Thanks