marți, 22 decembrie 2015

Design Patterns: The principle of least knowledge (Law of Demeter)


The principle of least knowledge (Law of Demeter) - Talk only to your immediate friends
  • We should only invoke methods that belong to:
    • The object itself
    • Objects passed as a parameter to the method
    • Any object the method creates or instantiates
    • Any components of the object (HAS-A )
  • Reduces the dependencies between objects
  • Reduces software maintenance
  • Help with debugging

miercuri, 9 decembrie 2015

ExtJS: Reset invalid controls to its last good value

Ext.form.Panel control contains two interesting events (inherit from BasicForm):
These events help to monitor if a form is valid or not (the alternative is to monitor each field from that form)

If you try to reload the store or view model for that form and the form contains invalid values - the fields are marked with "red" - the new values from store are not loaded (the fields remains marked with red and with the invalid values). This is happening because the field in store is not changed till a valid value is provided.

liStore.loadRawData(testModel, false);


To overcome this issue, my solution is to restore the valid values in invalid controls.
This solution supposes two steps:
- identify the invalid fields (http://stackoverflow.com/questions/19354433/extjs-form-isvalid-is-false-but-how-to-know-why-the-form-is-invalid)

    getInvalidFields: function(formCtrl) {

        var invalidFields = [];
        Ext.suspendLayouts();
        formCtrl.form.getFields().filterBy(function(field) {
            if (field.validate()) return;
            invalidFields.push(field);
        });
        Ext.resumeLayouts(true);
        return invalidFields;
    },

- restore the valid values (last valid values)

        var invalidFields = this.getInvalidFields(formCtrl);
        invalidFields.forEach(function(f) {
            //console.log(f);
            f.setValue(f.bind.value.lastValue);
        });

duminică, 6 decembrie 2015

JavaScript: 'Falsy' Statements

if ('') {} else (console.log('false statement')); // empty string
if (0) {} else (console.log('false statement')); // zero
if (null) {} else (console.log('false statement')); // null
if (false) {} else (console.log('false statement')); // false
if (undefined) {} else (console.log('false statement')); // undefined
if (NaN) {} else (console.log('false statement')); // NaN

luni, 23 noiembrie 2015

Java : Semaphore sample

package SemaphoreSample;

import java.util.concurrent.Semaphore;

public class StatViewsSample {
public static void main(String[] args) {
// assume that only two statistics providers are available
Semaphore statProviders = new Semaphore(2);
// list of views waiting to access the statistics providers
new StatView(statProviders, "User 1 View Chart");
new StatView(statProviders, "User 1 View 2 Grid");
new StatView(statProviders, "User 2 View Chart");
new StatView(statProviders, "User 3 View Chart");
new StatView(statProviders, "User 3 View 2 Chart");
new StatView(statProviders, "User 3 View 3 Grid");
}
}

class StatView extends Thread {
private Semaphore statProvider;

public StatView(Semaphore statProviders, String name) {
this.statProvider = statProviders;
this.setName(name);
this.start();
}

public void run() {
try {
System.out.println(getName()
+ " waiting to access an Statistics provider");
statProvider.acquire();
System.out.println(getName()
+ " is accessing an Statistics provider");
Thread.sleep(1000); // simulate the time required for using the
// Statistics provider
System.out.println(getName()
+ " is done using the Statistics provider");
statProvider.release();
} catch (InterruptedException ie) {
System.err.println(ie);
}
}
}

miercuri, 7 octombrie 2015

Java: Stack Implementation

public class Stack<T> {
private LinkedList<T> container = new LinkedList<T>();
public void push(T v) { container.addFirst(v); }
public T peek() { return container.getFirst(); }
public T pop() { return container.removeFirst(); }
public boolean empty() { return container.isEmpty(); }
public String toString() { return container.toString(); }
}

vineri, 2 octombrie 2015

Java: JUnit: Run a unit test inside a inner class -- using @RunWith(Enclosed.class)

package com.test;

//public class in the file
@RunWith(Enclosed.class)
public class GetCountryBasedOnIPDelegate {
    ...
}

//another class in the file (package access)
@RunWith(Enclosed.class)
class CSVGeoCodeNameProvider {
    ...
    public static class TestCSVGeoCodeNameProvider extends TestCase {
@Before
@Override
public void setUp() throws Exception {
//do some setups
                        ...
}
                //add some tests
@Test
public void testbuildCache() {
long countryIPRangeListSize = countryIPRangeList.size();
GenericUtils.debug(String.format("No. of items in file %s is %d",
GeoIPUtils.ipv4FilePath, countryIPRangeListSize));
assertNotSame(countryIPRangeListSize, 0);
assertNotNull(countryIPRangeList.get(new Long(18153472)).countryCode);
assertEquals(
countryIPRangeList.get(new Long(18153472)).countryCode,
"JP");
}
}
}

marți, 29 septembrie 2015

Java: Check an IPv4 address if it is privarte or loopback address

package test; 

import java.net.InetAddress; 
import java.net.UnknownHostException; 
import java.util.ArrayList; 

public class TestLocalIP { 

    public static void main(String[] args) throws UnknownHostException { 
          
         ArrayList<String> ips = new ArrayList<String>(); 
         ips.add("10.205.23.168"); 
         ips.add("192.168.0.1"); 
         ips.add("127.0.0.1"); 
         ips.add("1.1.1.1"); 

         for (String ip : ips) { 
             InetAddress ad = InetAddress.getByName(ip); 
             System.out.println("\n\n" + ip); 
             System.out.println("\n\tLocal Site: " + ad.isSiteLocalAddress());
             System.out.println("\n\tLoopback: " + ad.isLoopbackAddress()); 
        } 
         
    } 

}

joi, 24 septembrie 2015

Java: XML Parser Sample

package test; 

import java.io.*; 

import javax.xml.parsers.*; 

import org.w3c.dom.Document; 
import org.w3c.dom.NodeList; 
import org.xml.sax.SAXException; 

public class TestXMLParser { 

    public static void main(String[] args) { 
        String xml = "<superflow name=\"BreakingPoint ClientSim HTTP Slow Post\" class=\"canned\">\r\n" 
                + "      <label>\r\n" 
                + "        <string>ClientSim HTTP Slow POST</string>\r\n" 
                + "      </label>\r\n" 
                + "      <description>\r\n" 
                + "        <string>This Super Flow enacts an HTTP POST DDoS attack by exploiting a web server's support for users with slow or intermittent connections. The Content-Length header contains a message body size that will be fulfilled over several TCP packets.[RFC 2616]</string>\r\n" 
                + "      </description>\r\n" 
                + "    </superflow>"
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
        InputStream is = new ByteArrayInputStream(xml.getBytes()); 
        try { 

            // Using factory get an instance of document builder 
            DocumentBuilder db = dbf.newDocumentBuilder(); 

            // parse using builder to get DOM representation of the XML file 
            Document dom = db.parse(is); 
            NodeList stringNodes = dom.getElementsByTagName("string"); 
            String superflowName = dom.getElementsByTagName("superflow").item(0).getAttributes().getNamedItem("name").getNodeValue().replace("\n"""), 
                   superflowLabel = stringNodes.item(0).getTextContent(), 
                   superflowDescription =stringNodes.item(1).getTextContent(); 
            System.out.println(superflowName); 
            System.out.println(superflowLabel); 
            System.out.println(superflowDescription); 
        } catch (ParserConfigurationException pce) { 
            pce.printStackTrace(); 
        } catch (SAXException se) { 
            se.printStackTrace(); 
        } catch (IOException ioe) { 
            ioe.printStackTrace(); 
        } 
    } 

miercuri, 23 septembrie 2015

The Virtutes (after Benjamin Franklin)

1. Temperance. Eat not to dullness; drink not to elevation.
2. Silence. Speak not but what may benefit others or yourself; avoid trifling conversation.
3. Order. Let all your things have their places; let each part of your business have its time.
4. Resolution. Resolve to perform what you ought; perform without fail what you resolve.
5. Frugality. Make no expense but to do good to others or yourself; i. e. , waste nothing.
6. Industry. Lose no time; be always employ'd in something useful; cut off all unnecessary actions.
7. Sincerity. Use no hurtful deceit; think innocently and justly; and, if you speak, speak accordingly.
8. Justice. Wrong none by doing injuries, or omitting the benefits that are your duty.
9. Moderation. Avoid extremes; forbear resenting injuries so much as you think they deserve.
10. Cleanliness. Tolerate no uncleanliness in body, clothes, or habitation.
11. Tranquility. Be not disturbed at trifles, or at accidents common or unavoidable.
12. Chastity.

13. Humility. Imitate Jesus and Socrates.

vineri, 4 septembrie 2015

Java: Dispose Sample


public class ShapesSample extends Shape { 
    Cicle c; 
    Square s; 
    public ShapesSample(int i) {  
        super(i); 
        c = new Cicle(i); 
        s = new Square(i); 
        System.out.println("ShapesSample ctor"); 
    } 
     
    @Override 
    void dispose() { 
        s.dispose(); 
        c.dispose(); 
        System.out.println("ShapesSample dispose"); 
        super.dispose(); 
    } 
     
    public static void main(String[] args) { 
        ShapesSample sample = new ShapesSample(0); 
        try { 
             
        } 
        finally { 
            sample.dispose(); 
        } 
    } 


class Shape { 
    Shape(int i) { 
        System.out.println("Shape ctor"); 
    } 
     
    void dispose() { 
        System.out.println("Shape dispose"); 
    } 


class Cicle extends Shape { 
    Cicle(int i) { 
        super(i); 
        System.out.println("Cicle ctor"); 
    } 
     
    @Override 
    void dispose() { 
        System.out.println("Cicle dispose"); 
        super.dispose(); 
    } 


class Square extends Shape { 
    Square(int i) { 
        super(i); 
        System.out.println("Square ctor"); 
    } 
    @Override 
    void dispose() { 
        System.out.println("Square dispose"); 
        super.dispose(); 
    } 

vineri, 3 iulie 2015

Java: Image Virtual Proxy

ImageProxyTest.java

package test.patterns.virtualproxy;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.*;

public class ImageProxyTest {

public static void main(String[] args) {
ImageProxyTest test = new ImageProxyTest();
try {
test.start();
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
}

public void start() throws MalformedURLException {
//This has a BorderLayout manager's control
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Icon icon = WebIconFactory.getIcon("http://politeia.org.ro/wp-content/uploads/2014/09/ponta-china.jpg");

ImageComponentWrapper wrapper = new ImageComponentWrapper(icon);
//ImageComponent wrapper = new ImageComponent(icon);
frame.getContentPane().add(wrapper);
frame.setSize(1000, 700);
frame.setVisible(true);
}

}


WebIconFactory.java

package test.patterns.virtualproxy;

import javax.swing.*;
import java.awt.*;
import java.net.*;

public class WebIconFactory {
public static Icon getIcon(String url) throws MalformedURLException {
return new ImageProxy(new URL(url));
}

}

ImageProxy.java

package test.patterns.virtualproxy;

import javax.swing.*;
import java.awt.*;
import java.net.*;

public class ImageProxy implements Icon {
ImageIcon imageIcon;
URL imageURL;
Thread retrievalThread;
boolean retriving = false;

public ImageProxy(URL url) {
imageURL = url;
}

public int getIconWidth() {
if (imageIcon != null) {
return imageIcon.getIconWidth();
} else {
return 800;
}
}
public int getIconHeight() {
if (imageIcon != null) {
return imageIcon.getIconHeight();
} else {
return 600;
}
}
public void paintIcon(final Component c, Graphics g, int x, int y) {
if (imageIcon != null) {
imageIcon.paintIcon(c, g, x, y);
} else {
g.drawString("Loading Image from web ... ", x + 300, y + 200);
if (!retriving) {
retriving = true;
retrievalThread = new Thread(new Runnable() {
public void run(){
try {
//simulate a long time to get the image
java.lang.Thread.sleep(2500);
imageIcon = new ImageIcon(imageURL, "CD Cover");
c.repaint();
} catch(Exception ex) {
ex.printStackTrace();
}
}
});
retrievalThread.start();
}

}
}

}


ImageComponentWrapper.java

package test.patterns.virtualproxy;

import java.awt.*;
import javax.swing.*;


public class ImageComponentWrapper  extends JComponent {
private Icon icon;

public ImageComponentWrapper(Icon icon) {
this.icon = icon;
}

public void setIcon(Icon icon) {
this.icon = icon;
}

public void paintComponent(Graphics g) {
super.paintComponent(g);
int w = icon.getIconWidth();
int h = icon.getIconHeight();
int x = (800 - w)/2;
int y = (600 - h)/2;
icon.paintIcon(this, g, x, y);
}

}

Icon.java

package test.patterns.virtualproxy; 

import javax.swing.*; 
import java.awt.*; 

public interface Icon { 
    public int getIconWidth(); 
    public int getIconHeight(); 
    public void paintIcon(final Component c, Graphics g, int x, int y);
}

Steps

  • >javac -d class *.java
  • >cd class
  • \class>java test.patterns.virtualproxy.ImageProxyTest


References

Head First Java, 2nd Edition By Kathy Sierra, Bert Bates