SyntaxHighlighter JS

2013-01-27

Android Mac Command Line

1.) Launch Android SDK Manager to download additional libraries and SDK versions

$ANDROID_SDK_PATH/tools/android sdk

2.) List Android SDK targets to create AVD (Android Virtual Devices)

$ANDROID_SDK_PATH/tools/android list targets

3.) Create AVD

$ANDROID_SDK_PATH/tools/android create avd -n avdName -t targetID 

4.) Start the AVD emulator

$ANDROID_SDK_PATH/tools/emulator -avd avdName

5.) Generate Android project build.xml if missing

$ANDROID_SDK_PATH/tools/android update project -p projectPath

6.) Compile Android project if build.xml exist

ant debug

7.) Install Android on emulator

ant debug install

or 

$ANDROID_SDK_PATH/platform-tools/adb install projectPath/bin/AppName.apk

Useful parameters

-r : Reinstall
-d: Install on USB device
-s emulatorID : Specifies emaulator ID in case running multiple emulators

8.) If running multiple emulators, see all emulators ID

$ANDROID_SDK_PATH/platform-tools/adb devices

2013-01-22

Unix Detective: Port of Call

Recently I had to administer an Unix server with no runbook. The immediate task was to find the application listening on port 8888, make some modifications, and restart.

1.) Find process listening on port 8888

netstat -plan | grep 8888

The output is

tcp     0   0 :::8888   :::*    LISTEN      2700/java 

This shows me that a java program at Process ID (PID) 2700 is listening on port 8888

2.) Find process info of PID 2700

ps -fp 2700 | more

The output is

oracle  2700   1  0 18:55 ?     0:00:02 
/usr/java/latest/bin/java -Xmx1024m -Xms256m -Dapex.port=8888
-Djava.io.tmpdir=/home/oracle/tmp
-jar/home/oracle/listener/apex.war 2>&1 >/tmp/apexListener.log

This shows me the full command line for PID 2700. Luckily the command line has all the necessary information like program type (Oracle Apex), log location, war file location, temporary directory, etc.

Sometimes we do not get so lucky and the command line is more cryptic. If that  is the case, execute command

lsof -p 2700

That command shows a list of open files used by process 2700. That will usually lead to log location and other important files.

...

java    2700 oracle    2w   REG        3,1     1700 1796967 /tmp/apex_listener.log
java    2700 oracle    3r   REG       3,65  9828505  134585 /home/oracle/listener/apex.war
java    2700 oracle    4r   REG        3,1 51796975  361047 /usr/java/jdk1.6.0_20/jre/lib/rt.jar
java    2700 oracle    5r   REG       3,65  1869025  132940 /home/oracle/tmp/apex/apex/____embedded/start.jar
java    2700 oracle    6r   REG       3,65  1539291  132946 /home/oracle/tmp/apex/apex/WEB-INF/lib/poi-3.6-20091214.jar
...

3.) Find how to stop and start the application
The ps -fp command in step 2 shows me that the parent process PID is 1. (It is the number after 2700). 

ps -fp 1 | more

gives the output

root    1     0  0 18:54 ?    00:00:00 init [5]

The command init is the startup script process that executes when Unix first boots up.  The startup scripts are in directory /etc/init.d

cd /etc/init.d
find . -name "*" | xargs grep apex

The output is

./oracle:   su - oracle -c "/home/oracle/apexlistener.sh start"
./oracle:   su - oracle -c "/home/oracle/apexlistener.sh stop"

Reading the file ./oracle with the command

more ./oracle

shows me how to stop and start Oracle Apex.

Find Unused Unix Ports

Problem:
You need to bring up another Unix web server but port 80 is already in use. How do you find another unused Unix port?

Solution:
(as one line)

netstat -ln | grep -v LISTENING | awk '{print $4}' | grep ":" | sort | uniq


You will get an output like

0.0.0.0:5353
0.0.0.0:68
0.0.0.0:80
10.0.2.15:123
::1:10089
::1:123

The number after the last colon is the port in use, e.g. 80, 123, 5353.  Pick any Unix port not already in use and assigned.

Oracle Linux Listener Permission Error

Problem:
When starting the Oracle listener, you get the error

lsnrctl: error while loading shared libraries: /ORA_PATH/lib/libnnz11.so: cannot restore segment prot after reloc: Permission denied


Solution:
The Oracle is running on Security-Enhanced Linux (SELinux) and the OS is not granting Oracle proper permission on the libnnz11.so library.

As root user or sudo, grant the proper permission via

chcon -v -t textrel_shlib_t '/ORA_PATH/lib/libnnz11.so'

If errors are still occurring, you can set SELinux to permissive move with command

setenforce 0

To make the change to SELinux permissive mode permanent, edit the file /etc/selinux/config and change the line "SELINUX=enforcing" to

SELINUX=permissive

android:layout_height

Android UI XML Attribute

Name
android:layout_height

Description
Controls the height of the UI element.

Values
Value Description
wrap_contentUI element is automatically sized to fit the UI element content
match_parent UI element is automatically sized to fit the UI element parent container.
fill_parent Deprecated. Functionally identical as match_parent.
#dp Density-independent pixels. Actual size depends on screen resolution of device. The preferred unit to define a specific numeric UI element size. Example usage: 16dp
#sp Scale-independent pixels. Actual size depends on both screen resolution and user's font size settings. Example usage: 16sp
#pt 1/72 of an inch. Example usage: 16pt
#mm A millimeter. Example usage: 16mm
#in An inch. Example usage: 16in
#px A physical pixel. Not recommended to use. Example usage: 16px

Example Usage
<TextView android:layout_height="wrap_content" />

Reference
Android API: layout_height

android:layout_width

Android UI XML Attribute

Name
android:layout_width

Description
Controls the width of the UI element.

Values
Value Description
wrap_contentUI element is automatically sized to fit the UI element content
match_parent UI element is automatically sized to fit the UI element parent container.
fill_parent Deprecated.  Functionally identical as match_parent.
#dp Density-independent pixels. Actual size depends on screen resolution of device.  The preferred unit to define a specific numeric UI element size. Example usage: 16dp
#sp Scale-independent pixels. Actual size depends on both screen resolution and user's font size settings. Example usage: 16sp
#pt 1/72 of an inch. Example usage: 16pt
#mm A millimeter. Example usage: 16mm
#in An inch. Example usage: 16in
#px A physical pixel. Not recommended to use. Example usage: 16px

Example Usage
<TextView android:layout_width="wrap_content" />

Reference
Android API: layout_width

2013-01-21

Java Gotchas: Boxed Primitive

Primitives are int, double, boolean, etc. Boxed primitives are the Object version of primitives, i.e. Integer, Double, BooleanAs a general rule, prefer using primitives over boxed primitives.

Gotchas
1.) Do not use the == operator to compare boxed primitives.
     

            Integer a = new Integer(7);
     Integer z = new Integer(7);

     System.out.println(a == z);

Prints out false because == is doing an identity comparison on the Integer   reference memory location.  Since object a and object z are two different objects in different areas of memory, the (a == z) test is false.

To do an equality test on boxed primitives, use the equals method.

           a.equals(z);

Or unbox the boxed primitive and then do the == test

     int x = a;
     int y = z;

     System.out.println(x == y);

2.) Do not unbox in a loop

     Long sum = 0L;
     for (long i = 0; i < Integer.MAX_VALUE; ++i) {
         sum += i;
     }

At code sum += i , the boxed primitive sum will be auto-unboxed to perform addition then a Long object created to assign to sum.  This caused time and space performance issues.

Fix the above code by changing sum to a primitive long.

3.) Boxed primitives can throw NullPointerException
   
     static Integer i;
           
     public static void main(String... args) {
         System.out.println(i == 42);
     }

The code i == 42 will throw a NullPointerException because when i gets auto-unboxed to do a comparison with primitive int 42, the variable i is null;

2013-01-20

Java Memory Leak: Obsolete reference

In program

public class Stack {
  private Object[] elements;
  private int size = 0;

  private static final int INIT_SIZE = 16;

  public Stack() {
    elements = new Object[INIT_SIZE];
  }

  public void push() {
    checkSize();
    elements[size++] = e;
  }

  public Object pop() {
    if (size == 0) { throws EmptyStackException(); }
    Object result = elements[--size];
    return result;

  }

  private void checkSize() {
    if (elements.length = size) {
        elements = Arrays.copyOf(elements, 2 * size + 1);
    }
  }
}

The code line
Object result = elements[--size];

is a Java memory leak because even though the size decrements, the obsolete reference to the Object at element[size] still exists in memory.

The fix is to null of the unneeded reference at elements

  public Object pop() {
    if (size == 0) { throws EmptyStackException(); }
    Object result = elements[--size];
    elements[size] = null;

    return result;
  }

Arrays and collections are places where memory leak obsolete references occur often.

Find and Kill WebLogic process

Sample problem:
In a script, you need to find a Unix WebLogic process by user wluser and kill it.

Solution:
(as one line)

ps -fu wluser | grep weblogic.Name | grep -v grep | 
awk '{print $2}' | xargs kill -9

The command grep -v grep will exclude the grep process that may result from grep weblogic.Name.

Handling CSV in Unix

Sample Problem:
Add the values of column 2 and column 4 from a comma separated value (CSV) file.

Solution:
awk -F, '{print $2" plus "$4" is "$2+$4}' thefile.csv

Assuming thefile.csv contains
5,10,15,20
2,4,6,8

This will print out

10 plus 20 is 30
4 plus 8 is 12

Null safe for-each loop

If a collection is null when used in a for-each loop, it will result in a NullPointerException.  To prevent this, use the following utility method to return an empty list if the collection is null.


    public static <T> Collection<T> nullSafe(Collection<T> c) {
        return (c == null) ? Collections.<T>emptyList() : c;
    }

To use,

    Set<String> c = null;
    for(String s : nullSafe(c)) {
        System.out.println(s);
    }

2013-01-19

Notes on Nested Classes

Use if class is only used with/by parent class.
Four kinds of nested classes, in order of preference.
  1. static member classes
         * Access to all enclosing class static members, even private.
            Can acces other static peer member class fields.
         * Same visibility rule as regular static members.
         * Can be an interface
         * If member class does not require access to enclosing instance, always make member class static.  Save time and space on enclosing class construction.
         * Example, Map.Entry
         * Usage syntax: new Classname.StaticMemberClass()
  2. nonstatic member classes
         * Access to all enclosing class static and instance members, even private.
         * Same visibility rule as regular instance members.
         * Cannot be interface
         * No static fields or methods, except for static final.
         * Can obtain explicit access to enclosing class instance members via
            Classname.this.instanceMember
     
    * Can obtain explicit access to the super class of the enclosing class via
           
    Classname.super.instanceMember
         * Usage syntax: classname.new NonStaticMemberClass() 
  3. anonymous classes
         * Normally used as function objects
         * Good if class is short, used once, and right away.
         * No constructor but can use instance initializer
         * No static fields or methods, except for static final
  4. local classes
         * Classes defined inside methods.
         * Can only use final fields of enclosing method.
         * Access to all enclosing class static and instance members, even private.
         * No static fields or methods, except for static final.

WebLogic Start Script

This sample WebLogic start script has some functionality needed for a production environment

  • Run WebLogic as background service.  WebLogic will continue to run even after the user logs off the terminal.
  • Logs WebLogic system output and errors into a file.
  • Rotate to a new log file at every startup.
  • Display log output on-screen after startup.
#!/bin/sh

PWD=`dirname $0`
LOGFILE="/home/wluser/Oracle/Middleware/user_projects/domains/base_domain/servers/AdminServer/logs/weblogicSys.out"

# Log rotation
if [ -f $LOGFILE ]; then
    APPENDIX=`date +%Y%m%d_%H%M%S`
    echo "Rotation log ${LOGFILE} to ${LOGFILE}_${APPENDIX}"
    mv ${LOGFILE} ${LOGFILE}_${APPENDIX}
fi

# Start up WebLogic as background service
touch $LOGFILE
nohup $PWD/startWebLogic.sh >> $LOGFILE 2>&1 &
tail -f $LOGFILE

2013-01-18

Strategy Pattern: Example

The Arrays.sort method and Comparator interface is a real world example of the Strategy pattern.

The Strategy pattern is composed of an interface defining exactly one method for the functional behavior.  The Comparator is an interface defining compare as the functional method.

Concrete implementations (function objects) can be defined for the Strategy interface, e.g. AscendingSortStrategy, DescendingSortStrategy.

  class AscendingSortStrategy implements Comparator<Integer> {
      private AscendingSortStrategy() { }
      public static final AscendingSortStrategy INSTANCE = 

        new AscendingSortStrategy();
      @Override
      public int compare(Integer i1, Integer i2) {
          final int int1 = i1;
          final int int2 = i2
          return  int1 - int2;
      }
  }

  class DescendingSortStrategy implements Comparator<Integer> {
     private DescendingSortStrategy() { }
     public static final DescendingSortStrategy INSTANCE =
       new DescendingSortStrategy();
     @Override
     public int compare(Integer i1, Integer i2) {
        final int int1 = i1;
        final int int2 = i2
        return int2 - int1;
     }
  }

To use, pass the concrete strategy to a method that can accept it.

  Integer[] integers = new Integer[] { 
    new Integer(5), new Integer(1), new Integer(7) ,
    new Integer(2)
  };

  Arrays.sort(integers, AscendingSortStrategy.INSTANCE);
  Arrays.sort(integers, DescendingSortStrategy.INSTANCE);

Object Oriented Principle:
Use interfaces instead of concrete implementation classes. 
Having Arrays.sort accept the Comparator interface allows the user flexibility to change the implementation details of the sort by creating new classes while keeping everything else the same.

2013-01-17

Integration Tests in Maven

Integration tests require access to external resources such as a relational database or a web service.  In Maven, use the core Failsafe plugin to execute integration tests.

To configure, add the Failsafe plugin to the pom.xml in the <plugins> section.

 <plugins>
 ...

   <plugin>                 
       <groupId>org.apache.maven.plugins</groupId>
       <artifactId>maven-failsafe-plugin</artifactId>
       <version>2.13</version>
       <executions>
           <execution>
               <id>integration-test</id>
               <goals>
                   <goal>integration-test</goal>
                   <goal>verify</goal>
               </goals>
           </execution>
       </executions>
    </plugin>
 ...
 </plugins>


To create a integration test, just create a Java class in the Maven test directory starting or ending with IT, e.g. ITWebService.java, DatabaseIT.java.

I usually disable integration tests by default since the external resources may be not operational and integration tests often take a long time to complete.

To disable by default, add the Maven skipITs property and set it to true.


 <properties>
 ...
   <skipITs>true</skipITs>
 ...
 </properties>

 <plugins>
 ...

   <plugin>                 
       <groupId>org.apache.maven.plugins</groupId>
       <artifactId>maven-failsafe-plugin</artifactId>
       <version>2.13</version>
       <configuration>
           <skipTests>${skipITs}</skipTests>
       </configuration>
       <executions>

           <execution>
               <id>integration-test</id>
               <goals>
                   <goal>integration-test</goal>
                   <goal>verify</goal>
               </goals>
           </execution>
       </executions>
    </plugin>
 ...
 </plugins>



To execute, run the command

    mvn -DskipITs=false clean install

Builder Pattern: Too many constructor parameters

Problem:
A class has too many parameters in the constructor. For example,

    new VitalSign(98, 120, 80, 42, 23); 

Issues:
  • Difficult to remember what each parameter represents. Problem exacerbated with increasing parameters.  Putting wrong value for parameter is a common cause of bugs.
  • No way to define optional parameters.
  • Adding new parameters mean creating another constructor or adding another parameter to an existing constructor.
Solution:
Use the Builder pattern.
Assume temperature is the only required vital sign.

public class VitalSign {
    private final int temperature;
    private final int systolic;

    private final int diastolic;
    private final int pulse;
    private final int respiratoryRate;

    private VitalSign(Builder b) {
       this.temperature = b.temperature;
       this.systolic = b.systolic;
       this.diastolic = b.diastolic;
       this.pulse = b.pulse;
       this.respiratoryRate = b.respiratoryRate;

       // Put any state validation logic here and throw
       // IllegalStateException if violated

    }

    public static class Builder {
        // Required
        private final int temperature;


       // Optional with defaults
       private int systolic = -1;
       private int diastolic = -1;
       private int pulse = -1;
       private int respiratoryRate = -1;

       public Builder(final int temp) {
           this.temperature = temp;
       }

       public Builder systolic(final int val) {
           this.systolic = val;
           return this;
       }

       public Builder diastolic(final int val) {
           this.diastolic = val;
           return this;
       }

       public Builder pulse(final int val) {
           this.pulse = val;
           return this;
       }

       public Builder respiratoryRate(final int val) {
           this.respiratoryRate = val;
           return this;
       }

       public VitalSign build() {
           return new VitalSign(this);
       }
    }
}

To use,

    new VitalSign.Builder(98).pulse(42).
      systolic(120).diastolic(80).build();

Advantages:
  • Construction code easy to understand.
  • VitalSign class is immutable.  No setters.
  • VitalSign.Builder.build method can throw an IllegalStateException if state validation fails.  For example, if there is a systolic value but not a diastolic or if temperature is greater than 130.

2013-01-16

Find and replace all files in Unix

Sample problem:
Find and replace the word TODO with the word DONE in all Java files in the directory src .


Solution:


  find src -name "*.java" | xargs perl -pi -e "s/TODO/DONE/g"

Singleton Pattern: Best Java implementation

For Java 5 and beyond, the best singleton implementation is using enum.

public enum Singleton {
    INSTANCE;

    public void doStuff() { ... }

}

To use the singleton


    Singleton.INSTANCE.doStuff();

2013-01-13

Null safe string equals

Instead of
if ( str != null && str.equals("TheString") ) 

use
if ( "TheString".equals(str) ) 

The second form is more concise and will return false if str is null.

How to restart Oracle

  1. Log into Oracle Unix account via SSH (i.e. PuTTY)
  2. From the Unix prompt, type the command below to log into Oracle sys account via sqlplus

    sqlplus sys as sysdba

  3. From sqlplus, type the commands below to shutdown and start up the database

    shutdown normal;
    startup mount;
    alter database open;
    exit;

  4. From the Unix prompt, type the command below to restart the Oracle listener
    lsnrctl stop
    lsnrctl start 

Log Unix output to screen and file simultaneously

To show Unix commands output on the console screen and log it in a text file at the same time, use the tee command.

For example, to show the result of a grep command on-screen and write it to a log file:


    grep word file.txt | tee filegrep.log

Use java.net.HttpURLConnection in WebLogic

By default in WebLogic, when using the API java.net.URL.openConnection(), the subclass returned is weblogic.net.http.HttpURLConnection .  This class may exhibit unwanted behavior especially in handling SSL connections.

To use the standard Sun java.net.HttpURLConnection in WebLogic, use this Java code


  new URL(null,
          serverURL,
          new sun.net.www.protocol.https.Handler());

Optimize Java DNS Lookup

  • Prefer IPv4
    Starting with version 4, Java performs both IPv6 and IPv4 DNS lookups. If the DNS server is not set up to properly respond to IPv6 queries, then Java will wait for the IPv6 query to time out. This can manifest in what looks like network slowdowns.

    To bypass IPv6 DNS lookups, set the Java System property java.net.preferIPv4Stack to true.

    Command line:  -Djava.net.preferIPv4Stack=true 
    Java:
    System.setProperty("java.net.preferIPv4Stack",
      "true");

  • Increase cache time
    When a Java 6 security manager is not set, the default DNS cache is 30 seconds.  To reduce network DNS queries, the number of seconds of DNS cache can be increased by setting the networkaddress.cache.ttl System property.  Set this property to -1 to never expire the DNS cache.


    Command line:  -Dnetworkaddress.cache.ttl=-1
    Java:  
    System.setProperty("networkaddress.cache.ttl",
      "-1");