Saturday, July 26, 2014

Python 2 by example

Python 2.7 syntax examples:
Code samples at : https://github.com/rwatsh/python 

1.       Math:
2**3 = 8 , where, ** is exponent operator
+, -, *, / = math operators
% = modulo operator
2.       Comments:
# - single line comment

“”” my multi line
comment “””
3.       Print:
print(“%.2f”, total) -> will print total rounded to 2 decimal places.
4.       Escape char:
'There\'s a snake in my boot!'
Not required when using double quotes for string.
5.       String:
fifth_letter = "MONTY"[4]
print fifth_letter => prints Y
parrot = "Norwegian Blue"
print len(parrot)
print parrot.lower()
print parrot.upper()
pi = 3.14
print str(pi) => str() converts non-strings to string
Methods that use dot notation only work with strings.
On the other hand, len() andstr() can work on other data types.
print "Spam " + "and " + "eggs"
print "The value of pi is around " + str(3.14)
string_1 = "Camelot"
string_2 = "place"

print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2)
ð  Let's not go to Camelot. 'Tis a silly place.
String slicing:
s = "Charlie"

print s[0]
# will print "C"

print s[1:4]
# will print "har"
Getting i/p and printing o/p:
name = raw_input("What is your name?")
quest = raw_input("What is your quest?")
color = raw_input("What is your favorite color?")

print "Ah, so your name is %s, your quest is %s, " \
"and your favorite color is %s." % (name, quest, color)
6.       Datetime library:
from datetime import datetime
print datetime.now() => 2014-07-25 17:42:13.304805
print now.month => 7
print now.day => 25
print now.year => 2014
print '%s/%s/%s' % (now.month, now.day, now.year) => 7/25/2014
print '%s:%s:%s' % (now.hour, now.minute, now.second) =>17:48:28

7.       Comparison:
==, !=, <, >, <=, >=
8.       Logical: and, or, not
9.       Conditional: if, elif, else
def clinic():
    print ("You\'ve just entered the clinic!")
    print ("Do you take the door on the left or the right?")
    answer = input("Type left or right and hit 'Enter'.").lower()
    if answer == "left" or answer == "l":
        print ("This is the Verbal Abuse Room, you heap of parrot droppings!")
    elif answer == "right" or answer == "r":
        print ("Of course this is the Argument Room, I've told you that already!")
    else:
        print ("You didn't pick left or right! Try again.")
        clinic()

clinic()
10.   Functions:
See above example –
def [function_name(param1, param2)]:
                x = 2
                return x
11.   Import:
a.       Generic import: Import a module by name. Ex:
import math

print math.sqrt(25)
b.      Function import:
from [module] import [function]

from math import sqrt
print sqrt(25)
c.       Universal import:
from [module] import *

from math import *
print sqrt(25)
d.      Check everything a module has:
Import math
Print dir(math)
12.   Built-in functions: max, min, abs, type
Max(1,2,3) => 3
Min(1,2,3) => 1
Abs(-10) => 10
Print type(1) => or type(num) == int
13.   List:
zoo_animals = ["pangolin", "cassowary", "cat", "dog"]
print "The first animal at the zoo is the " + zoo_animals[0]
print len(zooanimals)
print zooanimals[0:2] => 1st and 2nd elements in the list
pets = zooanimals[2:4] or zooanimals[2:] => cat and dog => slicing the list.
Cat_index = zooanimals.index(“cat”)
Zoonimals.insert(cat_index, “cobra”) => ["pangolin", "cassowary", “cobra”, "cat", "dog"]
Zooanimals.sort() => sort the list.
zooanimals.remove(“cat”) => remove element from list
                pets[] => empty list
                print “----“.join(zooanimals) => pangolin ---- cassowary ---- cobra ---- cat ----- dog
               
                List Comprehension syntax:      

                my_list = range(51)
evens_to_50 = [i for i in range(51) if i % 2 == 0]

List Slicing:
List slicing allows us to access elements of a list in a concise manner. The syntax looks like this:

[start:end:stride]

                my_list = range(1, 11) # List of numbers 1 - 10

# print all odds from start to finish so no need to specify the start and end only need stride.
print my_list[::2]
# reverse a list
backwards = my_list[::-1]


to_21 = range(1,22)
odds = to_21[::2]
middle_third = to_21[7:14:1]
14.   For loop:
my_list = [1,9,3,8,5,7]
for number in my_list:
    print 2*number
else:
    print “Well done”
The else block only executes if the for loop executes normally (ie there is no break causing the loop to terminate mid-way).
for loop with range():
n = [3, 5, 7]
def print_list(x):
    for i in range(0, len(x)):
        print x[i]
print_list(n)

for I in range(20) => 0 to 20
for I in range(1, 10) => 1 to 9
Need index with for each loop – use enumerate() built-in function:
choices = ['pizza', 'pasta', 'salad', 'nachos']
print 'Your choices are:'
for index, item in enumerate(choices):
    print index+1, item
Iterate over 2 or more lists at once:
Zip() will create pairs of elements when passed two lists, and will stop at the end of the shorter list.
list_a = [3, 9, 17, 15, 19]
list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]
for a, b in zip(list_a, list_b):
    # Add your code here!
    print max(a,b)
Populate a list:
evens_to_50 = [i for i in range(51) if i % 2 == 0]
print evens_to_50

15.   Dictionary:
residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106}
menu = {}
menu[‘Samosa’] = 1.60
del residents[‘Puffin’] => remove item from dictionary
menu[‘Samosa’] = 1.50

for key in residents
                print residents[key]

print residents.items() => returns dictionary as list of key/value pairs.
Print residents.keys() => list of all keys
Print residents.values() => list of all values
16.   While loop:
while count < 10:
                count += 1
else:
                print “Game over!”
17.   Print:
The , character after our printstatement means that our next printstatement keeps printing on the same line.
d = {'a': 'apple', 'b': 'berry', 'c': 'cherry'}

for key in d:
    # Your code here!
    print key, " ", d[key]
18.   Lambda: Anonymous function:
Python’s support for functional programming => meaning you are allowed to pass functions around just as if they were variables or values.

lambda x: x % 3 == 0

is same as:

def by_three(x):
    return x % 3 == 0

Usage: filter uses lamba expression below to print only those elements of the list that satisfy that return true for the lambda expression (or satisfy the condition divisible by 3).

my_list = range(16)
print filter(lambda x: x % 3 == 0, my_list) => [0, 3, 6, 9, 12, 15]
19.   Bitwise:

print 5 >> 4  # Right Shift => 0
print 5 << 1  # Left Shift => 10
print 8 & 5   # Bitwise AND => 0
print 9 | 4   # Bitwise OR => 13
print 12 ^ 42 # Bitwise XOR => 38
print ~88     # Bitwise NOT => -89 (equivalent to adding 1 to the number and putting a – sign).

XOR => in-equality is true (0b1100 ^ 0b101010 => 0b100110)

In Python, you can write numbers in binary format by starting the number with 0b.

print 0b1 + 0b11 => 4

bin() – to binary (as string)
hex() – to hex
oct() – to octal

print bin(5) => 0b101
print hex(5) => 0x5
print oct(5) => 05

int(str, radix)  - any string (includes, binary/hex/octal with appropriate radix (2,16,8)) to int

int("110", 2) => 6
print int("0b100",2) => 4
print int(bin(5),2) => 5

20.   Classes:
An empty class:
class Animal(object):
    pass

pass – special python keyword for placeholder – in areas of code where python expects an expression.

class Triangle(object):
    number_of_sides = 3
    def __init__(self, angle1, angle2, angle3):
        self.angle1 = angle1
        self.angle2 = angle2
        self.angle3 = angle3

    def check_angles(self):
        if self.angle1 + self.angle2 + self.angle3 == 180:
            return True
        else:
            return False

my_triangle = Triangle(90, 30, 60)
print my_triangle.number_of_sides
print my_triangle.check_angles()

class Equilateral(Triangle):
    angle = 60
    def __init__(self):
        self.angle1 = self.angle
        self.angle2 = self.angle
        self.angle3 = self.angle

class MyTriangle(Equilateral):
    def __init__(self, beauty):
        self.beauty = beauty
        self.angle1 = 70

my_triangle = MyTriangle(True)
print my_triangle.angle1 # angle1/2/3 not inherited from base class Triangle
print my_triangle.number_of_sides # member inherited from Triangle
print my_triangle.angle # member inherited from Equilateral

1.       object is base class from which all classes inherit (same as Java).
2.       Constructors are - __init__(self…)
3.       Self needs to be the first param for all member methods and constructors.
4.       Derived class constructor needs to initialize all base members that don’t have a default value.
5.       Derived class inherits all base class members that have default values (defined outside of base class’s constructor).

21.   File I/O:
my_list = [i**2 for i in range(1,11)]
# Generates a list of squares of the numbers 1 - 10

f = open("output.txt", "w")

for item in my_list:
    f.write(str(item) + "\n")

f.close()

or

with open("text.txt", "w") as my_file:
                my_file.write("Success!")


with … as syntax is like try-with-resources in Java and it auto closes the file.

Monday, July 21, 2014

Book Review: Pro Git


Very nicely explained and author has a sound understanding of the fundamentals of the Git version control system is evident from his writing. I did not need to buy the dead tree version of the book since the ebook for my kindle was available for free. It delves into the basic topics first so that if you have read the first 4 chapters, then that knowledge will be sufficient to get you to start using git on a day 2 day basis. The remaining chapters can be browsed over and read on an as needed basis. Since the book is available in several formats it is very easy to access it at work on a PC and at home on my kindle. Scott Chacon has done an excellent job explaining Git concepts very clearly and the illustrations in the book are also very well done and aid in the understanding of the text and the subject matter. Highly recommended.

Sunday, July 20, 2014

Concise Git Reference for everyday use


This is compilation of all Git commands referring to "Pro Git" book by Scott Chacon.
  • Git config files:
    • /etc/gitconfig - config applicable to all users.
    • /.gitconfig - specific to a user.
    • ~/.git/config - config per git repo.
    • Typical configs:
      • git config --global user.name "Watsh Rajneesh"
      • git config --global user.email "rwatsh@gmail.com"
      • git config --global color.ui true
      • git config --global push.default simple
      • git config alias.last=log -1 HEAD
    • git config -l => shows the current config.
  • git [command]  --help
    • e.g. git commit --help
  • Create a new git repo from existing directory:
    • git init
    • git add *
    • git commit -m 'my comment'
  • Cloning an existing repo:
    • git clone https://github.com/rwatsh/MyGit.git
      • will create a local .git directory which will hold the entire repo with all the history known at the time of cloning.
      • will create a tracking branch "master" which will track the "master" branch on remote (or origin/master - see below point)
      • will save the https://github.com/rwatsh/MyGit.git as remote named "origin"
  • Git lifecycle states:
    • Untracked -> staged -> committed (tracked)
  • git status => shows:
    • Changes to be committed - staged files
    • Changed but not updated - modified files
  • git diff - to see diff between modified and staged version
    • git diff --cached - to see diff between staged and last committed version
  • git commit -a -m 'message' => skips staging and directly commits all modified files.
  • Remove files:
    • git rm [file]
    • git rm --cached => keeps the modified file but removes the staged versions of the file.
  • Rename a file:
    • git mv [file_from] [file_to]
  • Git log:
    • git log --pretty=format:"%h <%cr> [%cn] %s" --graph --name-only --since=2.weeks --author=Watsh
    • gitk - GUI to visualize history
  • Change last commit:
    • git commit --amend
  • Unstage a staged file:
    • git reset HEAD [file]
  • Unmodify a modified file:
    • git checkout -- [file]
  • Remotes:
    • git remote -v
    • git remote add watsh_repo https://github.com/rwatsh/MyGit.git
    • Inspecting remote:
      • git remote show watsh_repo
    • Removing and renaming remote:
      • git remote rename watsh_repo watsh_repo2
      • git remote rm watsh_repo2
  • Fetching from remote:
    • git fetch [remote]
      • git fetch watsh_repo
    • The command goes out to that remote project and pulls down all the data from that remote project that you don’t have yet. After you do this, you should have references to all the branches from that remote, which you can merge in or inspect at any time.
    • If you fetched a new branch created and pushed by your colleague and you need to start working on the same branch, you first get the branch reference in your local git repo (the .git directory) by doing a git fetch and then create a new branch referring to that reference ([remote]/[remotebranch]). The new branch thus created will be a tracking branch (hence git pull/push will automatically resolve to the right remote branch from the local tracking branch context).
      • git fetch watsh_repo
      • git checkout -b bug456 watsh_repo/bug456
  • Pushing to remote:
    • git push
      • git push watsh_repo master
      • It pushes your "master" branch changes to watsh_repo's "master" branch.
    • git push [remote] [localbranch]:[remotebranch]
      • git push watsh_repo master:release1.2.3_branch
      • Pushes local master to release1.2.3_branch remote branch on watsh_repo.
  • Tagging:
    • git tag -l 'v1.2.3.*'
    • git tag -a v1.4 -m 'my version 1.4' => creates annotated tags
    • git show  [tagname]
    • git push [remote] [tagname] => by default tags are not pushed with git push so we need to do this explicitly.
      • git push watsh_repo2 v1.4
      • git push watsh_repo2 --tags => push all tags
  • Auto completion for git:
    • wget https://github.com/git/git/blob/master/contrib/completion/git-completion.bash 
    • . ~/.git-completion.bash
    • cp ~/.git-completion.bash /etc/bash_completion.d => will enable git auto completion on bash launch for all users.
  • Branching & Merging:
    • git branch bug123
    • git checkout bug123
      • Fix the bug123 by making changes
      • git commit -a -m 'added fix for bug123'
    • git checkout -b 'hotfix'
      • Make hotfixes
      • git commit -a -m 'hotfixes done'
    • git checkout master
      • git merge hostfix
      • git branch -d hotfix => since we are done with hotfix branch, so delete it.
      • git merge bug123
      • git branch -d bug123
    • See which branches are already merged into:
      • git branch --merged
    • See all branches that contain work you have not merged in:
      • git branch --no-merged
    • Checking out a local branch from a remote branch automatically creates what is called a tracking branch. Tracking branches are local branches that have a direct relationship to a remote branch. If you’re on a tracking branch and type git push, Git automatically knows which server and branch to push to. Same is true for git pull.
    •  git checkout -b [branch] [remotename]/[branch]
      • git checkout -b sf origin/serverfix
      • Now, your local branch sf will automatically push to and pull from origin/serverfix 
    • Delete remote branch:
      • git push [remotename]  :[remotebranch]
      • Giving no local branch name before ':' above has the effect of deleting the remote branch.
  • Use cases:
    • Begin working on a new feature/bug:
      • git checkout -b myfeature_branch origin_feature_branch
      • git pull 
      • // do your works on myfeature_branch
      • git push origin myfeature_branch 
        • Make your myfeature_branch available on the remote git server so others can checkout it for reviewing or working with you (say multiple ppl working on the myfeature feature).
      • // once work is reviewed and ready to be merged to origin_feature_branch
      • git checkout origin_feature_branch
      • git pull
      • git merge --squash myfeature_branch 
        • Merge with --squash option which will commit all changes from myfeature_branch (across several commits on myfeature_branch) into a single commit on the origin_feature_branch. This ensures a cleaner history, ease of reverting the changes collectively that were brought in from myfeature_branch.
        • Note down this SHA-1 - we can use this for cherry picking this change to release branch next.
      • git push origin origin_feature_branch 
      • Delete the myfeature_branch from remote and local:
        • git branch -d myfeature_branch
        • git push origin :myfeature_branch
    • Cherry pick a change by its SHA-1 id:
      • git checkout release_branch
      • git cherry-pick [SHA-1 of the squashed commit from myfeature_branch]
      • git push origin release_branch
  • Git credentials:
You can store your credentials using the following command. This was very helpful to not having to re-enter github.com credentials everytime i did a git push for instance.
$ git config credential.helper store
$ git push http://example.com/repo.git
Username: 
Password: 
Also I suggest you to read
$git help credentials
The above is generally the basic working knowledge of Git which one needs on a day-to-day basis. Of course there are more advanced use cases related to stashing away your changes (pushing to a stack and popping them out), rebasing (which is more or less like merge command). I intend to cover those in later updates to this post. So long...

Sunday, July 06, 2014

MyGit repo - Some of my code samples

rwatsh/MyGit - https://github.com/rwatsh/MyGit

I have pushed some sample code which i had written recently covering various areas of Java programming (maven, OSGI, JUnit, Annotations, REST, JSF, Design patterns, algorithms, data structures, Java EE etc.).

Use https://github.com/rwatsh/MyGit.git to clone.

Reset the AdminServer Password in WebLogic 11g and 12c

ORACLE-BASE - Reset the AdminServer Password in WebLogic 11g and 12c



Reset the AdminServer Password in WebLogic 11g and 12c

If you forget the AdminServer password for your WebLogic 11g domain, you can reset it from the command line using the following process.
  • Set up the following environment variables. They are not necessary for the process itself, but will help you navigate. In this case my domain is called "ClassicDomain". Remember to change the value to match your domain.

    export MW_HOME=/u01/app/oracle/middleware
    export DOMAIN_HOME=$MW_HOME/user_projects/domains/ClassicDomain
  • Shut down the WebLogic domain.

    $ $DOMAIN_HOME/bin/stopWebLogic.sh
  • Rename the data folder.

    $ mv $DOMAIN_HOME/servers/AdminServer/data $DOMAIN_HOME/servers/AdminServer/data-old
  • Set the environment variables.

    $ . $DOMAIN_HOME/bin/setDomainEnv.sh
  • Reset the password using the following command. Remember to substitute the appropriate username and password.

    $ cd $DOMAIN_HOME/security
    $ java weblogic.security.utils.AdminAccount <username> <password> .
  • Update the "$DOMAIN_HOME/servers/AdminServer/security/boot.properties" file with the new username and password. The file format is shown below.

    username=<username>
    password=<password>
  • Start the WebLogic domain.

    $ $DOMAIN_HOME/bin/startWebLogic.sh

Wednesday, July 02, 2014

Book Review: The Complete Tales of Winnie The Pooh by A.A.Milne


The Complete Tales and Poems of Winnie-the-PoohThe Complete Tales and Poems of Winnie-the-Pooh by A.A. Milne
My rating: 5 of 5 stars

Read it to my about-to-be 7 years old son, who generally likes science fiction chapter books to be read to him, but for a change, one day picked up this book and to my surprise we read chapter after chapter for a few days in succession during bed time. He was particularly delighted by the humor in the book and it was a great fun reading him this classic by A.A.Milne. Christopher Robin in the stories is author's son and author is narrating the stories as if he is reading it to his son and then at times he will come out of the hundred acre woods to the real world and respond to his son's questions. Most children who have watched disney's rendition of Pooh's world already will be familiar with the characters in the stories - from Pooh, to piglet, to owl, eeyore, rabbit, kanga, roo and tigger. The book and its prose may be more suited to a child 5yrs and above as then they will be able to appreciate the humor and the literature of the book. One humorous incident in one of the stories happens between Pooh and Owl when Owl is trying to tell him about an "issue" and Pooh thinks Owl is sneezing when he is saying "issue". The way author presents this in the story is very humorous and both me and my son went rolling with laughter. A must read collection of short stories.

View all my reviews

Thursday, June 12, 2014

Setting up static IP in Ubuntu and autostarting vncserver

$sudo nano /etc/networks/interfaces

Edit this file and change the ip/netmask/gateway and dns as per your network.

auto lo
iface lo inet loopback

auto eth0
iface eth0 inet static
address 192.168.1.178
netmask 255.255.255.0
gateway 192.168.1.1
dns-nameservers 8.8.8.8 192.168.1.1

Restart networking service.

$ sudo service networking stop
$ sudo service networking start


Auto starting vnc server - http://askubuntu.com/questions/120973/how-do-i-start-vnc-server-on-boot

  1. First, install the TightVNC server sudo apt-get install tightvncserver.
  2. Set up the VNC server for the user you wish to log in as. When you run "vncserver" for the first time, it will ask you to set a password. only allow SSH tunnelled or VPN connections. To launch programs or a session when your VNC session starts, modify ~/.vnc/xstartup. Here is an example.
    #!/bin/sh
    
    xrdb $HOME/.Xresources
    xsetroot -solid black
    /opt/azureus/azureus &
    k3b &
    icewm-session &
    
  3. Copy the following into /etc/init.d/vncserver. The easiest way to do it is to copy it to your clipboard, run sudo -i && cat > /etc/init.d/vncserver && exit in a terminal, paste it in, and type CTRL-D. Be sure to change the USER variable to whatever user you want the VNC server to run under.
    #!/bin/sh -e
    ### BEGIN INIT INFO
    # Provides:          vncserver
    # Required-Start:    networking
    # Default-Start:     3 4 5
    # Default-Stop:      0 6
    ### END INIT INFO
    
    PATH="$PATH:/usr/X11R6/bin/"
    
    # The Username:Group that will run VNC
    export USER="mythtv"
    #${RUNAS}
    
    # The display that VNC will use
    DISPLAY="1"
    
    # Color depth (between 8 and 32)
    DEPTH="16"
    
    # The Desktop geometry to use.
    #GEOMETRY="x"
    #GEOMETRY="800x600"
    GEOMETRY="1024x768"
    #GEOMETRY="1280x1024"
    
    # The name that the VNC Desktop will have.
    NAME="my-vnc-server"
    
    OPTIONS="-name ${NAME} -depth ${DEPTH} -geometry ${GEOMETRY} :${DISPLAY}"
    
    . /lib/lsb/init-functions
    
    case "$1" in
    start)
    log_action_begin_msg "Starting vncserver for user '${USER}' on   localhost:${DISPLAY}"
    su ${USER} -c "/usr/bin/vncserver ${OPTIONS}"
    ;;
    
    stop)
    log_action_begin_msg "Stoping vncserver for user '${USER}' on localhost:${DISPLAY}"
    su ${USER} -c "/usr/bin/vncserver -kill :${DISPLAY}"
    ;;
    
    restart)
    $0 stop
    $0 start
    ;;
    esac
    
    exit 0
    
  4. Make the script executable with sudo chmod +x /etc/init.d/vncserver.
  5. Finally, connect to your server with a VNC client on port 590X, where X is the value of "DISPLAY" in the vncserver script. On OS X, I like to use Chicken of the VNC. On Windows and Linux, the TightVNC client works nicely.

Wednesday, June 11, 2014

Docker: Container Virtualization

Docker provides so called container virtualization, allowing an application and its dependencies to run as an isolated process inside a virtual environment. This environment is then portable from local computers to backend infrastructure and cloud. Docker uses LinuX Containers (LXC) running in the host OS allowing you to share the resouces available to the host.

Docker started in March 2013, in 15 months it had 8,741 commits from more than 460 contributors. 2.75 millions downloads and 14,000 "Dockerized" apps. Docker is supported by major technology and service providers like Canonical, Fedora, Google Cloud Platform, OpenStack, Rackspace and Red Hat.

Docker today announced the release of version 1.0 of its container virtualization solution.

For a full list of what changed in version 1.0 see the features and fixes commits list.

This post is excerpted from : http://virtualization.info/en/news/2014/06/release-docker-docker-engine-1-0.html
http://readwrite.com/2014/06/10/docker-goes-enterprise#awesm=~oGOZEndiwnkius

Friday, May 23, 2014

OpenStack Devstack: Some Important Commands

Recently attended a training on OpenStack by Mirantis (Trainer: Devin Parrish). Following were some of the useful commands for working on devstack (which installs openstack on Ubuntu 12.04):

create a credrc.sh:
export OS_USERNAME=admin
export OS_PASSWORD=password
export OS_TENANT_NAME=demo
export OS_AUTH_URL=http://10.24.51.182:35357/v2.0/


$ source ./credrc.sh
$ cd devstack
$ ./rejoin_stack.sh - This command starts a screen session. You can attach to the screen session with Cntl + A + " and detach from screen session using Cntl + A + D key combination. Within the session use UP/DOWN arrow keys to navigate between the different log files for the different processes in OpenStack like nova scheduler (n-sched), etc.

$ sudo service libvirt-bin status
$ sudo service rabbitmq-server status
$ sudo service rabbitmq-server start
$ sudo rabbitmqctl list_queues
$ nova-manage service list
$ neutron --os-username admin agent-list
$ keystone --os-username admin endpoint-list
$ keystone --os-username admin service-list

$ ps aux | grep nova (similarly, cinder, glance, neutron, keystone, swift, horizon).

$ sudo service /etc/init.d/apache2 reload
$ mysql -uroot -pstack ...

$ neutron subnet-list
$ ip netns list
$ sudo ip netns exec qrouter-xxxxx  
where,
cmd = ping [VM IP] or ssh  [VM IP] or curl http:// [VM IP] or curl http:// [VM IP]

Rest can all be done using horizon UI (as of Havana release).

$ ceilometer alarm-threshold-create --name cpu_high \
--description 'instance running hot' -m cpu_util \
--statistic avg --period 300 --evaluation-periods 3 \
--comparison-operator gt --threshold 80.0 \
--alarm-action 'log://' -q resource_id = [ID of VM]

Tuesday, April 08, 2014

Parameterized JUnit Tests by Example


public class ReverseString {

 public static void main(String[] args) {
  String str = "abracadabra0";
  System.out.println(reverseStr(str));
 }

 public static String reverseStr(String str) {
  StringBuilder sb = new StringBuilder();
  for (int i = str.length() - 1; i >= 0; i--) {
   sb.append(str.charAt(i));
  }
  return sb.toString();
 }

}
import static org.junit.Assert.assertEquals;

import java.util.Arrays;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class ReverseStringTest {
 String testStr = "";
 String expectedStr = "";
 

 @Rule
 public ExpectedException exception = ExpectedException.none();

 public ReverseStringTest(String ts, String es) {
  this.testStr = ts;
  this.expectedStr = es;
 }
 
 @Parameters
 public static Iterable data() {
  return Arrays
    .asList(new Object[][] { { "abracadabra0", "0arbadacarba" },
      { null, null }, { "", "" } });
 }


 @Test
 public void test() {
  if (testStr == null) {
   exception.expect(NullPointerException.class);
  }
  assertEquals(expectedStr, ReverseString.reverseStr(testStr));
 }

}

Java Annotations by Example


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Annotations are defined via the @interface annotation before the class name.
 * Via @Retention you define if the annotation should be retained at runtime or
 * not. The @Target annotation lets you define where this annotation can be
 * used, e.g. the class, fields, methods, etc.
 * 
 * @author Watsh
 * 
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CanRun {

}
public class AnnotatedMethodsClass {

    public void method1() {
        System.out.println("method1");
    }

    @CanRun
    public void method2() {
        System.out.println("method2");
    }

    @CanRun
    public void method3() {
        System.out.println("method3");
    }

    public void method4() {
        System.out.println("method4");
    }

    public void method5() {
        System.out.println("method5");
    }

} 
import java.lang.reflect.Method;

public class AnnotationAnalyzer {

 /**
  * The main method of this class analyzes the annotations and calls the
  * corresponding methods.
  * 
  * @param args
  */
 public static void main(String[] args) {
  AnnotatedMethodsClass clz = new AnnotatedMethodsClass();
  Method[] methods = clz.getClass().getMethods();

  for (Method m : methods) {
   CanRun annos = m.getAnnotation(CanRun.class);
   if (annos != null) {
    try {
     m.invoke(clz);
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  }
 }
}