How to get rid of SearchMine.Net on Safari

I hate to confess, but I made a terrible mistake… and it is embarrassing to write about it. The other day, I was looking for a math worksheet for my daughter. I went on a legit website, and clicked on the image to print. I was redirected on a page to update Adobe Flash. I never do that kind of things. It always smells fishy. But this time, my daughter is next to me whining. My son is playing with his noisy electric circuit. I have a online meeting coming up soon. I didn’t think too much… and I clicked on “update!” As it started to do things, I was thinking “not good…” I tried to cancel, but too late. Safari redirected me to searchmine.net.

Hate to see this screen…

I was hoping it was not a big deal. I googled how to remove searchmine, and did a few things: get rid of any weird application, cleared caches, private information, extensions, looked at homepage, installed Malwarebytes, Avast, ComboCleaner (free to scan, but not to remove threats. What a scam! Hey ComboCleaner, if you’re not free, just say it!). SearchMine was still there.

Last thing to do: remove Mac OS profile configuration. BUT I was not able to do it. Profiles was greyed out:

Cannot use the UI to update profiles.

Only solution: use command lines since I was admin on my machine. First, list the profiles:

sudo profiles -L

The list was like:

_computerlevel[1] attribute: profileIdentifier: some sort of ID
_computerlevel[2] attribute: profileIdentifier: some sort of ID
_computerlevel[3] attribute: profileIdentifier: com.mycouponsmart.safari.XXXXXXXXXXXXXXXXXXXXXX
_computerlevel[4] attribute: profileIdentifier: some sort of ID

Finally I see the culprit… To get rid of it, I removed it with this command line:

sudo profiles -R -p com.mycouponsmart.safari.XXXXXXXXXXXXXXXXXXXXXX

And that’s it! no more searchmine! Here are the lessons I have learned:

  • Hate Adobe Flash!
  • Hate myself for clicking on “Update.” I should have followed my instinct… If needed, go to the official website to download what you need.
  • Never assume you are too smart to avoid malwares.
  • Never assume Mac OS is free from malwares.

The Command Pattern

The Command Pattern is useful to implement an instruction to perform a particular action. It contains and encapsulates all the information necessary for the action to be taken. It can allow to create composite commands, to keep track of a sequence of commands, and possibly to undo one of the commands. It can be used in GUI or transactions for example.

Think of a text editor. We can type characters and format them. Each command will implement an interface:

public interface Command {
   void perform();
   void undo();
}

public class Write implements Command {

   private TextEditor editor; // we will assume this class exists.
   private String string;
   private boolean success;

   public Write(TextEditor editor, String string) {
      this.editor = editor;
      this.string = string;
      this.success = false; // by default, a boolean is false, but it does not hurt to make it explicit!
   }

   @Override
   public void perform() {
       editor.write(string);
       success = true;
   }

   @Override
   public void undo() {
      if (success) { // we do not want to undo if the operation failed
        editor.erase(string); // more complex in reality, but not the purpose of this example.
      }
   }
}

public class Formatter implements Command {

  public enum Format {
     BOLD,
     ITALICIZE
  }

   private TextEditor editor;
   private Format format;
   private int startPosition; 
   private int endPosition;
   private boolean success;

   public Formatter(TextEditor editor, Format format, int startPosition, int endPosition) { // could chain with Write.. Chain of responsibility pattern!
      this.editor = editor;
      this.format = format;
      this.startPosition = startPosition;
      this.endPosition = endPosition;
      this.success = false;
   }

   @Override
   public void perform() {
      switch (format) {
         case BOLD:
           success = editor.bold(startPosition, endPosition);
           break;
         case ITALICIZE:
           success = editor.italicize(startPosition, endPosition);
           break;
         default: 
           break;
      }
   }

   @Override
   public void undo() {
      if (!success) return; // we do not want to undo if the operation failed
      switch (format) {
        case BOLD:
          editor.unbold(startPosition, endPosition);
          break;
        case ITALICIZE:
          editor.unbold(startPosition, endPosition);
          break;
        default:
          break;
      }
   }
}

The client code can chain commands or undo, etc.

TextEditor editor = new TextEditor();
Command awesome = new Write(editor, "This is awesome!");
Command author = new Write(editor, "By John Doe");
Command formatAwesome = new Formatter(editor, Formatter.Format.BOLD, 8, 15); 
Command formatAuthor = new Formatter(editor, Formatter.Format.ITALICIZE, 16, 27);

List<Command> cmds = new ArrayList<>();
cmds.add(awesome);
cmds.add(formatAwesome);
cmds.add(author);
cmds.add(formatAuthor);

try {
  cmds.forEach(Command::perform); // run
} catch (Exception e) {
  Collections.reverse(cmds); // reverse the command sequence.
  cmds.forEach(Command::undo); // will undo only those that succeeded.
}

This pattern can be combined with the Chain of Responsibility pattern or the Strategy pattern.

This is awesome! But is it really useful you could ask? What about just calling TextEditor’s methods? True! I was wondering the same. What is really powerful is how we can manage those commands. It can be more complex commands, sequenced, and we can create rollbacks, etc.

The Chain of Responsibility Pattern

The Chain of Responsibility pattern is useful when there is a chain of components that need to accomplish the same operation. Each component may have a default implementation and/or cancel the processing chain.

Let’s say we want to write a class that handles http requests. For each request, we want to log it, verify its authentication, and parse the content. Each operation can be designed as a class implementing the same interface.

public interface HttpRequestHandler {

   HttpRequestHandler next();
   void setNext(HttpRequestHandler next);

   // allows to chain other handlers
   default void add(HttpRequestHandler handler) {
      if (next() != null) {
        next().add(handler);
      } else {
        setNext(handler);
      }
   }; 

   void process(HttpRequest request);
}

public class Logger implements HttpRequestHandler {

   private Log log = ...
   private HttpRequestHandler next;

   // implements getter/setter
   // ...

   public void process(HttpRequest request) {
      log.log(request); // order can changed if we want the operations to start at the end of the chain
      if (next != null) next.process(request);
   }
}

public class Authenticator implements HttpRequestHandler {

    private HttpRequestHandler next;

    // implements getter/setter
    // ...

    public void process(HttpRequest request) {
      if (authenticate(request)) {
         if (next != null) next.process(request);
      }
      // the chain is disrupted if the request does not pass the security check
    }

    private boolean authenticate(HttpRequest request) {
      // ...
    }
}


public class Parser implements HttpRequestHandler {

    private HttpRequestHandler next;

    // implements getter/setter
    // ...

    public void process(HttpRequest request) {
      parse(request);
      if (next != null) next.process(request);
    }

    private void parse(HttpRequest request) {
       // ...
    }
}

The good thing with this design is that we can add more operations without too much effort. Now we can have our client code manipulating the handlers:

public class WebServer {

   public HttpResponse respondTo(HttpRequest request) {
      handlers().handle(request);
   }

   private HttpRequestHandler handlers() {
      Logger logger = new Logger();
      Authenticator auth = new Authenticator();
      Parser parser = new Parser();
      logger.add(auth);
      logger.add(parser);
      return logger;
   }

}

The Proxy Pattern

The Proxy pattern creates an interface giving access to a resource to hide any underlying-complexity as well as to add improvements of the underlying code. The proxy interface looks like the interface it “caches.”

Let’s think about a query object we want to use to query a database. It is great to log any request for debugging purpose.

public class SimpleQuery<T> implements Query<T> {

   public T findBy(String id) { 
       // connect to database, query, etc.
       return db.query(sql);
   }

   public void insert(T object) {
       // connect to database, create id, etc.
       db.insert(sql);
   }
}

We are going to proxy this with inheritance. It is possible to implement this pattern with other techniques such as composition (having a reference of the object to proxy), or introspection if we want the proxy to be dynamic (done at runtime).

public class ProxyQuery<T> extends SimpleQuery<T> {

   private Logger logger = ... // whatever framework you want to use
   
   public T findBy(String id) {
     // connect to database, query, etc.
     String sql = "select * from table where id="+id;
     logger.debug(sql);
     return db.query(sql);
   }

   public void insert(T object) {
     // connect to database, create id, etc.
     String sql = "insert into table (id, value) values ("+id+","+object+")";
     logger.debug(sql);
     db.insert(object);
   }

}

And that’s all! Of course proxies can be much more complex. It can be used to call a remote object. It can be used to use a cache, etc.

Now you may wonder: what is the difference between the proxy pattern and the decorator pattern?

  • The proxy pattern provides an identical interface while the decorator provides an enhanced interface.
  • The decorator usually aggregates (composition) what it is decorating. The proxy does not have to work that way.
  • Proxy might interface an object that has not been created yet. For example, you may want to stack up / validate information before creating the actual object for performance sake.

Java Generics and Interfaces

Why are the two related? Because subclasses may need to know what specific class it is handling.

We get confused because we subclass generic interfaces to specify what type of items it is handling. For example, we may want to create a high level interface Renderer<T extends Shape> to draw shapes. Then we want to subclass it for:

SimpleRenderer<Point>: render points. The logical “relation” tree is:

SimpleRenderer<ComplexShape>: render complex shapes. The relations are:

BufferedRenderer<LargeComplexShape>: render large complex shapes . We may think it would work to have:

The purpose is to be able to have a single object manipulating both SimpleRenderer<ComplexShape> and BufferedRenderer<LargeComplexShape> “under” Renderer<ComplexShape>… but it does not work.

The relation tree for large complex shapes is actually:

So we cannot use Renderer<ComplexShape> to manipulate both. Painful, isn’t it?

Here are my suggestions to help design classes:

Suggestion #1: do not think of Generics for inheritance, but to avoid casting object.

Suggestion #2: do I need to know the subclass type? if not, do not use Generics. Use interfaces

The Fluent Builder as Solution to the Builder Pattern and Inheritance

What a title! If you do not know what the builder pattern is, you can look at my post here. A builder can be helpful, but you quickly realize it is painful to handle this pattern with inheritance.

Let’s use this simple example: we want to create classes representing a SUV and a coupe.

public class Car { 

    private Color color;
    private Engine engine;

}

public class SUV extends Car { 

   private FourWheelDriveSystem wdSystem;

}

public class Coupe extends Car {  

   private Door[] twoDoors;

}

We want to use the builder pattern to instantiate SUV and Coupe objects. We could simply duplicate the code from the Car Builder in SUV and Coupe. It may be ok if there are not many properties. But if we want to avoid duplicating, we can create a Car, SUV and Coupe Builders:

public class Car {

  private Color color;
  private Engine engine;

  public static class Builder { // see post on builder pattern for more details
     private Color color;
     private Engine engine;

     public Builder withColor(Color color) { ... }
     public Builder withEngine(Engine engine) { ... }
     public Car build() { ... } 
  }

}

public class SUV extends Car {

   private FourWheelDriveSystem wdSystem;

   public static class Builder extends Car.Builder { 
     private FourWheelDriveSystem wdSystem;

     public Builder withWdSystem(FourWheelDriveSystem wdSystem) { ... }
     public SUV build() { ... }
   }
}

public class Coupe extends Car {

   private DoorSystem twoDoors;

   public static class Builder extends Car.Builder {
      private DoorSystem twoDoors;

      public Builder withTwoDoors(DoorSystem twoDoors) { ... }
      public Coupe build() { ... }
   }

}

So far so good. However, this code fails:

new SUV.Builder()
  .withColor(color) // returns a Car.Builder
  .withWdSystem(wdSystem) // do not compile because the function belongs to SUV.Builder
  .withEngine(engine)
  .build(); // would return a Car object, not a SUV...

One solution is to use Recursive Generics:

// in Car class
public static class Builder<SELF extends Car.Builder<SELF>> {

  public SELF withColor(Color color) { 
    this.color = color;
    return (SELF) this;
  }
  ...
}

// in SUV class
public static class Builder extends Car.Builder<Builder> {

  public Builder withWdSystem(FourWheelDriveSystem wdSystem) { 
     this.wdSystem = wdSystem;
     return this;
  }

}

Now the code works:

new SUV.Builder()
   .withColor(color) // now returns a SUV.Builder
   .withWdSystem(wdSystem) 
   .withEngine(engine)
   .build(); // would return a SUV object

Et voila! But it takes a bit of brain power to understand for a programmer who has not developed the code to understand what the builder does…

The Flyweight Pattern

The flyweight pattern seeks to avoid redundancy when storing data. It is a space optimization technique that uses less memory by storing data from similar objects.

Let’s say we want to render the movements of an animal on map based on GPS coordinates collected every 10 seconds from an implanted GPS device. The data collected are represented by a list of GpsPoint:

public class GpsPoint {
  private double longitude;
  private double latitude;
  private double altitude;

  // getters/setters
}

Now we may want to track multiple animals on a single map. The number of points can quickly increase. We can use a buffer to keep in memory duplicated points. Indeed, the animal may stay or go back to the same spots. Our buffer can be very simple:

public class Buffer<GpsPoint> {

   private List<GpsPoint> points;

   public boolean contains(GpsPoint point) {
      return points.contains(point); // assume GpsPoint overrode equals() and hashcode()
   }

   // ...
}

We would need a buffer manager or the renderer can manage the buffer. For example, it would check if the point exists in the buffer before adding it:

public class Renderer {

   private Buffer<GpsPoint> buffer;

   public void render(GpsPoint point) {
       if (!buffer.contains(point)) { // does not keep duplicate in memory
          buffer.add(point);
       }

       buffer.forEach(pt -> drawPoint(pt)); // render each point of the buffer
   }

}

Buffer has less points than what the trace has. Simple technique… the most complicated part of this pattern is probably its name 🙂

The Facade Pattern

The Facade Pattern exposes several components through a single interface. The goal is to simplify the API for the client components.

Let’s say we want to make a robot. A robot is made out of different parts. Our code may look like:

public class SimpleArm implements Arm {

  public SimpleArm() {
  }

}

public class Robot {

   private Arm arm;

   public Robot(Arm arm) {
     this.arm = arm;
   }

   public void moveArm() {
     ...
   }
}

Now this code looks simple, but it could be more complex if the Arm is complicated to be instantiated… and if we add more parts to our robots that are configurable. And we can even have a complex robot made of other robots. Instead of forcing the client code to create the different parts and “assemble” them in the Robot class, we can offer a facade class that requires only a few parameters, instantiate the different parts and offer simple methods to move the robot. The only disadvantage is the possible lack of flexibility for optimization and specification.

The Decorator Pattern

The idea is to augment an existing class with new functionalities without rewriting the existing code. There are two possibilities to do it:

Solution 1: Inherit if the class is not final.

Solution 2: Add a decorator class using composition.

Let’s say we want to program a draw shapes. We can create a Display interface that will be implemented by all of our classes.

public interface Display {

  public void draw();

}

Our basic class draws the shape

public class SimpleDisplay implements Display {

   public void draw() {
     // draw shape
   }

}

Now we want to fill the shape. We can extend what SimpleDisplay does with another class:

public class FillerDisplay {

   private Display display;

   public FillerDisplay(Display display) {
     this.display = display;
   }

   public void draw() {
     fill();
     display.draw();
   }

}

We can also add a zoom effect:

public class ZoomDisplay {

   private Display display;

   public ZoomDisplay(Display display) {
     this.display = display;
   }

   public void draw() {
      zoom();
      display.draw(); 
   }

}

So we can combine those decorators to obtain the result we want:

// a simple display
Display simple = new SimpleDisplay();

// a display filling the shape
Display fill = new FillerDisplay(new SimpleDisplay());

// a display that can zoom
Display zoom = new ZoomDisplay(new FillerDisplay(new SimpleDisplay()));

Notice we do not have to have a filler. A display can simply draw a shape and zoom. There are also ways to simplify the creation of the objects.

What can be trickier is accessing methods in one of the layers. For example, we can imagine that we want the FillerDisplay to use an image to fill the shape. In that case, we would add a method called setImageBackground() but it would be specific to FillerDisplay. To access that method, we would need to implement a getDisplay() in each layer, and we would have a code that looks like:

display.getDisplay().getDisplay()... getDisplay().setImageBackground(img)

which is not … very pretty … (Coding is art after all). What’s possible is to create a “shortcut” method in the client code if it is used frequently:

private Display getFillerDisplay() {
   return display.getDisplay().getDisplay()... getDisplay();
}

It can be lengthy code if each display is a generic:

LayerDisplay<ZoomDisplay<FillerDisplay<RandomDisplay<SimpleDisplay>>>>> display;

hmmm… so good. 🙂

The Composite Pattern

The Composite Pattern creates a mechanism for trading individual objects and compositions of objects in a uniform manner.

What the heck is this definition!?? This is why programming sounds crazy for some. It is sometimes difficult to define programming concepts simply and concisely.

What this composite pattern seeks to do is to handle objects that are composed of other “similar” objects. It is actually very simple. Simply think of a tree of objects with the same behavior. Let’s say we want to know how much each employee, manager, and branch of a bank manages.

public class Employee {  // Leaf
   public double calculatePortfolio() { ... }
}

public class Manager {  // Composite
   private List<Employee> employees;
   private List<Managers> managers; // a manager can manage other managers
   public double calculatePortfolio() { 
     return employees
     .stream()
     .reduce((e1, e2) -> e1.calculatePortfolio() + e2.calculatePortfolio())
     + managers
     .stream()
     .reduce((e1, e2) -> e1.calculatePortfolio() + e2.calculatePortfolio())
   }
}

public class Branch { // Other composite or component
  private List<Manager> managers;
  public double calculatePortfolio() {
    return managers
     .stream()
     .reduce((e1, e2) -> e1.calculatePortfolio() + e2.calculatePortfolio())
  }
}

By calling the calculatePortfolio method, we are able to get the amount of money managed at each level of the tree.