Wednesday, June 14, 2023

Entrepreneurship: Startup - Where are you now?

Since 2019, I've had the privilege of working with entrepreneurs as a technology consultant through Dartmouth - Magnuson Center. During this time I met with many startup teams and found patterns on their stages. Here are my metaphorical categories that represent the different stages of startups.


1. Satellite level

    The satellite level, you hear a lot of shiny objects (exciting ideas), each idea has a magnetic pull on you. But everything is too far to grasp. Ideas flutter past, capturing your interest for a day or two. But soon, their luster fades away. At times, you find yourself drawn to an idea simply because of the person who shared it with you. The excitement is so strong that you can't wait to dive in the next morning. Unfortunately, before you even have a chance to fully comprehend the idea, its sparkle diminishes.

  What is evident here is your innate attraction to entrepreneurship. You have a strong desire to utilize your personal time in order to cultivate and establish your own entrepreneurial endeavor.

 Things to consider: When evaluating an idea, go beyond its novelty and feasibility, and prioritize understanding the underlying problem you are seeking to solve. Emphasizing the problem itself will yield greater benefits than immediately embracing the initial solution generated by your team.




   

2. Cloud level

3. Glider Plane level

4. Mountain top level

5. Tree top level

6. Ground level 

7. Tunnel level 



Tuesday, July 5, 2016

Mac TimeMachine Backup Maintenance

Original Source:

http://apple.stackexchange.com/questions/39287/how-can-i-manually-delete-old-backups-to-free-space-for-time-machine/55646


Short notes:

1. COMPUTER_NAME=$(/usr/sbin/scutil --get ComputerName)
2. OLDEST_BACKUP=$(/usr/bin/tmutil listbackups |/usr/bin/grep "$COMPUTER_NAME" |/usr/bin/head -n1);echo $OLDEST_BACKUP
3. sudo /usr/bin/tmutil delete "$OLDEST_BACKUP"


Checks: 


1. NBACKUPS=$(/usr/bin/tmutil listbackups | /usr/bin/grep "$COMPUTER_NAME" | /usr/bin/wc -l); echo $NBACKUPS
2. LATEST_BACKUP=$(/usr/bin/tmutil latestbackup); echo Latest backup: $LATEST_BACKUP




From the apple stackexchange:
COMPUTER_NAME=$(/usr/sbin/scutil --get ComputerName)
NBACKUPS=$(/usr/bin/tmutil listbackups | /usr/bin/grep "$COMPUTER_NAME" | /usr/bin/wc -l)
OLDEST_BACKUP=$(/usr/bin/tmutil listbackups | /usr/bin/grep "$COMPUTER_NAME" | /usr/bin/head -n1)
LATEST_BACKUP=$(/usr/bin/tmutil latestbackup)
echo Latest backup: $LATEST_BACKUP
if [[ -n "$LATEST_BACKUP" && "$LATEST_BACKUP" != "$OLDEST_BACKUP" ]] then
  echo -n "$NBACKUPS backups. Delete oldest: ${OLDEST_BACKUP##*/} [y/N]? "
  read answer
  case $answer in
    y*)
      echo Running: /usr/bin/sudo /usr/bin/tmutil delete "$OLDEST_BACKUP"
      /usr/bin/sudo time /usr/bin/tmutil delete "$OLDEST_BACKUP"
      ;;
    *)
      echo No change
      ;;
  esac
 else
   echo "No backup available for deletion"
 fi

Tuesday, April 19, 2016

Groovy LDAP access

Groovy script to access and modify LDAP or Active Directory using groovy ldap library.

Need following library:
groovy-ldap.jar

Class loading:
this.getClass().classLoader.rootLoader.addURL(new File("lib/groovy-ldap.jar").toURL()); import org.apache.directory.groovyldap.*;

Connecting LDAP:
LDAP = Class.forName("org.apache.directory.groovyldap.LDAP"); SearchScope = Class.forName("org.apache.directory.groovyldap.SearchScope"); host = "<ldap_host_addr>"; ad_user = "<ldap_priv_userid>"; ad_password = "<password>"; ldap = LDAP.newInstance(host, ad_user, ad_password); println "Connected to AD => $host";

Reading an entry:
search_str = "uid=<uid_info>*"; //* regex match entries = ldap.search(search_str, "<ldap_ou_path>", SearchScope.ONE); print "${entries.size} entries are found\n\n"; for (entry in entries) { print """ DN: ${entry.dn} Common name: ${entry.cn} uid: ${entry.uid} Object classes: ${entry.objectclass} """ }

Modify an entry:
//user dn is needed; it wont modify cn dn = "<dn_of_entry_to_be_modified>"; mods = [ ["REPLACE", [<field_name_1>: "<new_value_1>"]], ["REPLACE", [<field_name_2>: "<new_value_2>"]], ["ADD", [<new_field>: "<new_value>"]] ] ldap.modify(dn, mods); print "LDAP entry modified\n";


Groovy OIM Access

Groovy script to access Oracle Identity Management using OIM Client library.
Need following libraries:
spring.jar
oimclient.jar
wlfullclient.jar
authwl.conf file content:
xellerate{ weblogic.security.auth.login.UsernamePasswordLoginModule required debug=true; };

Class loading:
#!/usr/bin/env groovy this.getClass().classLoader.rootLoader.addURL(new File("lib/spring.jar").toURL()); this.getClass().classLoader.rootLoader.addURL(new File("lib/oimclient.jar").toURL()); this.getClass().classLoader.rootLoader.addURL(new File("lib/wlfullclient.jar").toURL()); import oracle.iam.platform.*; import oracle.iam.identity.usermgmt.api.*;

Connecting OIM:
String oimUrl = "<server_url>"; String oimAdmin = "<privileged_user>"; String oimPasswd = "<password>"; String authwlFileName = "authwl.conf"; String authwl = getClass().getClassLoader().getResource(authwlFileName).toString(); System.setProperty("java.security.auth.login.config", authwl); System.setProperty("java.naming.factory.initial", "weblogic.jndi.WLInitialContextFactory"); System.setProperty("java.naming.provider.url", oimUrl); System.setProperty("OIM.AppServerType", "wls"); System.setProperty("APPSERVER_TYPE", "wls"); def OIMClient = Class.forName("oracle.iam.platform.OIMClient").newInstance(); Hashtable<String, String> env = new Hashtable<String, String>(); env.put("java.naming.factory.initial", "weblogic.jndi.WLInitialContextFactory"); env.put("java.naming.provider.url", oimUrl); OIMClient.login(oimAdmin, oimPasswd.toCharArray(), env); println "Connected to OIM => ${oimUrl}\n";

Read an entry:
usrMgr = OIMClient.getService(Class.forName("oracle.iam.identity.usermgmt.api.UserManager")); //Parameters to be read from OIM. Add additional fields based on need usrAttrs = new HashSet<String>(); usrAttrs.add("Common Name"); usrAttrs.add("Display Name"); usrAttrs.add("Email"); usrAttrs.add("First Name"); usrAttrs.add("Initials"); usrAttrs.add("Last Name"); usrAttrs.add("User Login"); user = usrMgr.getDetails("User Login", "<user_login_unique_value>", usrAttrs); //Print usrAttrs.each { println "$it \t\t=> ${user.getAttribute(it)}"; }

Modify an entry:
usrMgr = OIMClient.getService(Class.forName("oracle.iam.identity.usermgmt.api.UserManager")); //collect entityid HashSet<String> retAttrs = new HashSet<String>(); user = usrMgr.getDetails("User Login", "<user_login>", retAttrs); entityId = user.getEntityId(); //create user entry using entityid updateUser = Class.forName("oracle.iam.identity.usermgmt.vo.User").newInstance(entityId); //update the user updateUser.setAttribute("<field_name>", "<new_value>"); //refer OIM form mappings for attribute name usrMgr.modify(updateUser); println "User modified";

Friday, October 23, 2015

YAML Loader - Ruby

Sample YAML Loader:


Assume your yaml file 'email_credential.yml' exists in same directory and in the format below:

email:
  smtp_server: smtp.gmail.com
  smtp_port: 587


Here is the simple snippet to load YAML and collect data:

begin
  yml = YAML.load_file("email_credentials.yml")
  
  email = yml['email']['smtp_server']
  eport = yml['email']['smtp_port']
  
rescue Exception => e
  puts "Email credential YAML loading issue \n" + e.to_s
end

Website Monitor - Ruby Script

Simple Ruby Script file to check the web site and post an email using gmail service.

This script contains 2 main parts

  1. Checking website - for response OK and content
  2. Email to admin on failure [using gmail]

Checking Website:

    url = URI.parse(web_url)
  net_conn = Net::HTTP.new(url.host, url.port)
  net_conn.use_ssl = url.scheme == "https"
  res = net_conn.get('/')

   We can check res.code == 200 and verify res.body includes the content we wanted to see.

Email [Using gmail]

  NOTE: Gmail needs TLS encryption; so enable it before start sending msg
   
    smtp = Net::SMTP.new("smtp.gmail.com", 587)
    smtp.enable_starttls #gmail needs this encryption
    smtp.start("DOMAIN_FILLER", <gmail_acc>, <gmail_pwd>, :logindo |s| 
      s.send_message(<msg>, <gmail_acc>, <to>)
    end  

  Sample GMAIL Msg format:
   msg = [
    "From: WebMonitor <from_addr>",
    "To: Admin <to_addr>",
    "Subject: <subject>",
    "",
    "Hi,",
    "!!MORE DETAILED MSG!!"
  ].join("\r\n");


Gist: https://gist.github.com/sivajankan/8278d75c39bc5a8260ae

The script can be added to crontab to do automated testing

Thursday, August 20, 2015

Selenium - IE remote browser setup

Setup Selenium -  IE remote browser


  1. Install Java. If you are setting up from a base level testing VM, you may need to first install Java.
  2. Download following files from https://code.google.com/p/selenium/downloads/list into your windows machine (This page mostly has latest versions. Pick them)
    • a. selenium-server-standalone-2.39.0.jar
    • b. IEDriverServer _Win32_2.39.0.zip (There is version for 64 bit; pick appropriate version)
  3. Place the jar file and extracted exe file from zip, into C:\SeleniumServer folder
  4. In Command Prompt and navigate to 'C:\SeleniumServer'
  5. Run the command to start the standalone selenium server
java -jar selenium-server-standalone-2.35.0.jar -Djava.util.logging.Level=OFF -Dwebdriver.ie.driver="C:\SeleniumServer\IEDriverServer.exe"

Monday, July 6, 2015

Cap Deploy [Capistrano]

Capistrano

Ref:
http://capistranorb.com/
https://github.com/capistrano/ # Shows list of all capistrano repos
https://github.com/capistrano/capistrano
https://github.com/capistrano/rails
https://github.com/capistrano/passenger



Gemfile


gem 'capistrano'
gem 'capistrano-rails'
gem 'capistrano-passenger'
gem 'capistrano-rvm'  #if your preference is RVM



$> bundle install
$> bundle exec cap install #Make sure files are created
$> bundle exec cap install STAGES=production  #add additional env seperated by ','

Limited gem installation [selected env]
$> bundle install --without development test


Capfile


require 'capistrano/rails'

#or
require 'capistrano/rvm'
require 'capistrano/bundler'
require 'capistrano/rails/assets'
require 'capistrano/rails/migrations'
require 'capistrano/passenger'

#For rbenv
require 'capistrano/rbenv'
require 'capistrano/chruby'



Ref: http://capistranorb.com/documentation/getting-started/configuration/

config/deploy.rb


set :application, '<app_name>'
set :repo_url, 'git@.... <git repo>'

set :linked_files, fetch(:linked_files, []).push('config/database.yml')
set :linked_dirs, fetch(:linked_dirs, []).push('log', 'tmp/pids', 'tmp/cache', 'tmp/sockets', 'vendor/bundle', 'public/system')

set :keep_releases, 5



config/deploy/production.rb

server '<dest_server>', user: '<dest_server_user>', roles: %w{web db app}
set :deploy_to, "/var/www/html/<dir>"

set :passenger_restart_command, 'passenger-config restart-app'

set :passenger_restart_options, -> { "#{deploy_to} --ignore-app-not-running" }

Adding tasks

Ref: http://capistranorb.com/documentation/getting-started/cold-start/

in create lib/capistrano/tasks/access_check.rake file, and add

  namespace :check do
    desc "Check that we can access everything"
    task :write_permissions do
      on roles(:all) do |host|
        if test("[ -w #{fetch(:deploy_to)} ]")
          info "#{fetch(:deploy_to)} is writable on #{host}"
        else
          error "#{fetch(:deploy_to)} is not writable on #{host}"
        end
      end
    end
  end

$> bundle exec cap -T #to check the task existence
$> bundle exec cap production check:write_permissions #to verify the write permission


[Still working on Cap Scripting]

Basic Commands

cap production deploy:check
cap production deploy 
cap production deploy:rollback



Advance Comments [from capistrano Git page]


# list all available tasks
$ bundle exec cap -T

# deploy to the staging environment
$ bundle exec cap staging deploy

# deploy to the production environment
$ bundle exec cap production deploy

# simulate deploying to the production environment
# does not actually do anything
$ bundle exec cap production deploy --dry-run

# list task dependencies
$ bundle exec cap production deploy --prereqs

# trace through task invocations

$ bundle exec cap production deploy --trace


Advance Learning

https://github.com/capistrano/sshkit


Deploy issue with git

When you get: git stdout: permission denied (publickey).

$> eval $(ssh-agent)
$> ssh-add



Rails Life

Ruby Self Help Steps

Installation required Ruby setups!

http://code.tutsplus.com/tutorials/how-to-install-ruby-on-a-mac--net-21664
https://gorails.com/setup/osx/10.10-yosemite
http://railsapps.github.io/installrubyonrails-mac.html

Xcode installation if mac
RVM installation
Ruby installation
git installation
PostgreSQL or SQLite3


RVM Ruby version Preparation

rvm current #shows current default
rvm list #lists local installation

rvm get stable #get latest stable version
rvm reload # reload rvm
rvm list remote #all available to install
rvm install 2.2.5
rvm reinstall 2.2.0 --disable-binary

rvm --default use 2.1.5 #to make 2.1.5 as default

gem setup
$ echo 'gem: --no-document' >> ~/.gemrc

To create gemset
$ rvm use 2.2.1@gemset-2.2.1 --create

Install rails before the next step
$ gem install rails

Good start for first project
Ref: https://github.com/RailsApps/rails-composer/

#sudo gem install rails
rails new myapp -m https://raw.github.com/RailsApps/rails-composer/master/composer.rb



#Standard way
$rails new <project_name>

use .ruby-version  file to specify ruby version for the project
Example: 2.2.1@gemset_2_2_1

rspec
https://relishapp.com/rspec/rspec-rails/docs/gettingstarted

in Gemfile, development and test section
gem "rspec-rails"

bundle install
rails generate rspec:install

Remember: rake db:test:prepare

rake spec #to run tests


Cucumber
in Gemfile - development 

gem 'cucumber-rails', :require => false
gem 'database_cleaner'

  
bundle install
rails generate cucumber:install


Haml

add
gem "haml-rails", "~> 0.9" #Check version from https://github.com/indirect/haml-rails


rails generate haml:application_layout convert

rake haml:erb2haml # to convert existing erb files to haml



Devise
Add gem "devise" in Gemfile 
bundle install

rails generate devise:install
Follow suggestions


Registeration Email issue

Google account access blocking
SMTPAuthenticationError

http://stackoverflow.com/questions/18124878/netsmtpauthenticationerror-when-sending-email-from-rails-app-on-staging-envir

Add gem 'sass-rails' in Gemfile





Pry
http://pryrepl.org/


pry -r ./config/environment.rb





Passenger for Rails : CentOS

System Info

CentOS Linux release 7.0.1406 (Core) 
3.7GB Memory 
50GB diskspace
DUAL Core - Intel(R) Xeon(R) CPU E5-2680 v2 @ 2.80GHz
X86_64 - Architecture

Ref: 
https://www.digitalocean.com/community/tutorials/how-to-use-capistrano-to-automate-deployments-getting-started
https://www.digitalocean.com/community/tutorials/how-to-setup-a-rails-4-app-with-apache-and-passenger-on-centos-6

Root access:
yum -y update
yum groupinstall -y 'development tools'
curl -L get.rvm.io | bash -s stable  
  -- didnt work; and suggested next step in error
  >gpg2 --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3

curl -L get.rvm.io | bash -s stable
source /etc/profile.d/rvm.sh 
rvm reload
rvm get stable
rvm requirements
rvm reload
rvm install 2.1 #installed 2.1.5p273
rvm --default use 2.1.5

CONTINUE
https://www.rosehosting.com/blog/install-ruby-on-rails-with-apache-and-passenger-on-centos-6/

install rvm for newuser


adduser newuser
passwd newuser 
usermod -G wheel newuser #pick a fair name for new user
visudo #uncomment next line
  #%wheel ALL=(ALL) NOPASSWD:ALL
vim /etc/ssh/sshd_config #add next line to avoid ssh access using new user name
  DenyUsers newuser
service sshd restart
su - newuser

sudo yum -y update
sudo yum -y install curl curl-devel httpd-devel httpd mod_ssl
sudo curl -L get.rvm.io | bash -s stable  

  gpg2 --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3
#then sudo curl -L get.rvm.io | bash -s stable  
rvm get stable
rvm reload
rvm install 2.1.5
rvm use 2.1.5 --default
vim ~/.gemrc #put following lines to avoid lot of ri doc installations

---
:backtrace: false
:benchmark: false
:bulk_threshold: 1000
:sources:
- http://rubygems.org/
- http://gemcutter.org
:update_sources: true
:verbose: true
gem:
  --no-document
  --no-ri
  --no-rdoc

gem install rails
gem install passenger
passenger-install-apache2-module #follow the suggestions


PostgreSQL Installation

CentOS

#Postgres installation
ref: https://wiki.postgresql.org/wiki/YUM_Installation
ref2: http://karolgalanciak.com/blog/2013/07/19/centos-6-4-server-setup-with-ruby-on-rails-nginx-and-postgresql/

#as root
vim /etc/yum.repos.d/CentOS-Base.repo
 #add following line into [base] and [updates] section
 exclude=postgresql*

yum localinstall http://yum.postgresql.org/9.4/redhat/rhel-6-x86_64/pgdg-centos94-9.4-1.noarch.rpm
yum install postgresql94-server

yum install postgresql94 postgresql94-devel postgresql94-server postgresql94-libs postgresql94-contrib


Installation is complete: next setup
/usr/pgsql-9.4/bin/postgresql94-setup initdb
  #service postgresql-9.4 init db - failed
  #systemctl initdb postgresql-9.4.service - didnt work

chkconfig postgresql-9.4 on #postgres start on startup

#CONFIG 
vi /var/lib/pgsql/9.3/data/pg_hba.conf

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     md5
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
host    all             all             ::1/128                 md5


service postgresql-9.4 restart


#db setup
https://wiki.postgresql.org/wiki/First_steps

$>su - postgres
$>psql
psql>alter user postgres with password 'postgres-user-password';
psql>ctrl+d
exit

$> su - newuser #user in rails installation
$> psql postgres -U postgres #postgres password from previous step

psql>create user username with password 'secretPassword'; #username - new db account user
psql>create database testdb owner=username;


To delete postgres:
yum erase postgresql94*




Sunday, July 5, 2015

Git

Git server
http://git-scm.com/book/en/v2/Git-on-the-Server-Setting-Up-the-Server

cd ~

git config --global merge.ff false

mkdir repos
cd repos
mkdir ur_project.git
cd ur_project.git
git init --bare


Local machine

git remote add <urid>  git@your_ip:repos/ur_project.git
git remote -v


#To see the added url

git remote show origin


Git Cheat Sheet
ref: http://git.or.cz

Remember: git command --help

Global Git configuration is stored in $HOME/.gitconfig (git config --help)

Create
From existing data
cd ~/projects/myproject
git init
git add .

From existing repo
git clone ~/existing/repo ~/new/repo
git clone git://host.org/project.git
git clone ssh://you@host.org/proj.git

Show

Files changed in working directory
git status

Changes to tracked files
git diff

What changed between $ID1 and $ID2
git diff $id1 $id2

History of changes
git log

History of changes for file with diffs
git log -p $file $dir/ec/tory

Who changed what and when in a file
git blame $file

A commit identified by $ID
git show $id

A specific file from a specific $ID
git show $id:$file

All local branches
git branch

List remote
git remote -v

git remote --help


Git Repo Browser
git instaweb --httpd webrick

Log
git log
git reflog

Youtube video:
  https://www.youtube.com/watch?v=sevc6668cQ0


http://stackoverflow.com/questions/6565357/git-push-requires-username-and-password
A common mistake is cloning using the default (HTTPS) instead of SSH. You can correct this by going to your repository, clicking the ssh button left to the URL field and updating the URL of your origin remote like this:
git remote set-url origin git@github.com:username/repo.git

Monday, June 29, 2015

BeanShell - Java Scripting in Shell

BeanShell

  Ruby's IRB equivalent Java Scripting in console.

Home:
  http://www.beanshell.org/home.html


Get the latest beanShell jar file
   http://www.beanshell.org/download.html


To install as an extension place the bsh.jar file in your $JAVA_HOME/jre/lib/ext folder.

For Mac os: place the bsh.jar in /Library/Java/Extensions
( ~/Library/Java/Extensions for individual users)


CLASSPATH Update:
  unix:     export CLASSPATH=$CLASSPATH:bsh-xx.jar #update your bashrc
  windows:  set classpath %classpath%;bsh-xx.jar #update environment variables

NOTE: xx - should match you downloaded jar version


Start new Shell window

$ java bsh.Console # Starts bean console
$ java bsh.Interpreter   // run as text-only on the command line
$ java bsh.Interpreter filename [ args ] // run script file

Trial:
$ java bsh.Interpreter 
bsh %  int add(int a, int b) { return a+b;}
bsh % print(add(1,2)); //3

Manual
 http://www.beanshell.org/manual/bshmanual.html

Groovy Gears

Started from  http://www.groovy-lang.org/learn.html.

Decided to use GVM:

$ curl -s get.gvmtool.net | bash

  Installation went well; Updated bashrc and zshrc files.

  Started new shell window

$ gvm help # Showed help 

$ gvm install groovy #installed latest version

$ groovy -version # showed installed version


Create a (text) file hello_groovy
$ vim hello_groovy

Enter: System.out.println("Hello Groovy")
Save file

$ groovy hello_groovy #print "Hello Groovy"


Manual
http://www.vogella.com/tutorials/Groovy/article.html

Monday, May 25, 2015

Rails 4: Page Specific JS Load

To load JS files only on particular page:


1. Stop loading it globally
    In application.js file, stub (stop) loading the js file, you don't want to load.
 
    Example:
     //stub file_name


2. Add to Precompile
     Update config/initializer/assets.rb with following line to enable assets precompile.
      Rails.application.config.assets.precompile += %w( file_name.js )

     Rails throws 'AssetFilteredError', if the file is not precompiled.


3. Load JS file in specific folder
    Load the application JS and specific file JS where needed.
    Example:
      = javascript_include_tag 'application''data-turbolinks-track' => true
   = javascript_include_tag 'file_name''data-turbolinks-track' => true 




To call document ready for specific page:


1. Introduce new class to body or div of the page
2. Use jQuery selector for that class

Example:
  %div{"class": "_class_name"}


:javascript
   $("._class_name").on("ready", ready_function);
  

Monday, May 18, 2015

Mac iCal Shared Calendar (Exchange)

One liner:
iCal - Menu =>  'Preferences'  => 'Accounts' => 'Delegation'. Add accounts using the '+' sign in 'Accounts I can access'.

TLDR;

After a weekly MS Office update, MS Outlook stopped working in Mac 10.10.3 (Yosemite); Often it went to frozen mode, and every time I had to rebuild the using Microsoft Database Utility [Press alt(option) key and click on outlook icon to open DB utility]. This made me force to use the iCal.

Followed standard Exchange integration given by current outlook provider. But adding shared calendar was tricky with iCal 8.0.

To add Shared calendar, go to 'Preferences', then select 'Accounts' tab; then go to 'Delegation'; Add accounts using the '+' sign in 'Accounts I can access'.

The 'Accounts ...' and 'Add Account ..' options in iCal menu is kind of confusing when you try to access shared calendar with existing calendar account.


Tuesday, May 5, 2015

log4j - File & Format

Sample codes to configure log4j

General logger initialization

 Logger logger = Logger.getLogger(YourClass.class);

log4j.properties file sample (writes to file too)

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
#log4j.appender.stdout.layout.ConversionPattern=%d{DATE} %5p [%c]:%L - %m%n
#log4j.appender.stdout.layout.ConversionPattern=%d{ISO8601} %5p [%c]:%L - %m%n
#Same as ISO8601
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd'T'HH:mm:ss.S Z} %5p [%c]:%L - %m%n
log4j.appender.stdout.Threshold=trace

log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=${user.dir}/you_log_file.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=trace, stdout, file



Additional file outputs [2 sample layouts]


//Load the file handler for the logger 1
Appender fh = new FileAppender(new SimpleLayout(),  workingDir + File.separator + logfile);
logger.addAppender(fh);
fh.setLayout(new SimpleLayout());


//Load the file handler for the logger 2
TTCCLayout logLayout = new TTCCLayout();
logLayout.setDateFormat("dd MMM yyyy HH:mm:ss,SSS");
Appender fh = new FileAppender(logLayout,  workingDir + File.separator + logfile);
logger.addAppender(fh);
fh.setLayout(logLayout);


More options available with 'Enhanced Pattern Layout' and 'Layout'

Ref:
http://www.mkyong.com/logging/log4j-log4j-properties-examples/
http://stackoverflow.com/questions/4474646/how-to-write-to-a-text-file-using-to-log4j

API:
https://logging.apache.org/log4j/1.2/apidocs/index.html


Thursday, April 30, 2015

Excel - Hyperlink - Tying to a cell

Lately one friend asked my help to figure out the way to use hyperlink to a specific cell in Excel Sheet; Which was easy after trying 4-5 options and 2 hours of Google search. So I decided to document it for future reference!

One liner:
  The technique is 'define the name' for the cell to be linked and use that 'defined name' in hyper link.

Ref:
http://excelribbon.tips.net/T006195_Tying_a_Hyperlink_to_a_Specific_Cell.html
http://www.k2e.com/tech-update/tips/418-tip-fastest-way-to-create-defined-names-in-excel

Before going on step by step, please find what is 'Name Box'. [courtesy link from http://blog.accountants.intuit.com/ways-to-be-more-productive/low-tech-excel-tips/]

Name box:


 The left most cell in 'Formula bar' is the Name Box. When you hover the Name Box cell, it shows 'Enter a name for a cell range, or select a named range from the list' [in MSOffice 2013]


Step by Step:

Create the Defined Name:
  1. Select the cell you want to be hyperlinked (to be jumped to). In the 'Name Box' [check the image above], enter a 'reference' name and press return key. [Assumed 'Reference1' for our example case]
Use the Defined Name in Hyperlink
  1. Go to the cell where you want to place the hyperlink (to be jumped from), right click and click on 'Hyperlink' from the menu
  2. In the 'Insert Hyperlink' popup window, in 'Anchor' ['Link to' for older version] section, click on 'locate'; which opens another popup window
  3. In the 'Select Place in Document' popup, expand the 'Defined Names' by clicking the small triangle [or + icon] next to it [make the triangle point down, or change + to -, by clicking], and select the reference you made in step 2. [Our example 'Reference1']


Now your hyperlink pointed to the reference; so inserting or deleting any rows or columns won't affect your hyperlink pointing cell location.


All the best!

Tuesday, April 21, 2015

Java Working Directory - Wrong GDD

Lately I spend almost a day, actually a whole day to figure out jar file running directory. Actually what I needed was 'System.getProperty("user.dir")'



Here is the function first I wrote which worked across Mac, Linux and Windows 8

private static String workingDirectory() {
  File currentJavaJarFile = new File(<any>Util.class
                            .getProtectionDomain()
                            .getCodeSource()
                            .getLocation()
                            .getPath());
  String currentJavaJarFilePath = currentJavaJarFile.getAbsolutePath();
  String parentDir = currentJavaJarFile.getParent();
  String jarFilename = currentJavaJarFile.getName();
  parentDir = parentDir.toString().replace("\\", "\\\\"); //backslash directory separator error in windows
  String directory = currentJavaJarFilePath.replaceAll(parentDir.toString(), "").replace((File.separator + jarFilename), "");
  return directory;

Monday, April 13, 2015

OneJar - Cool Experience

Lately I had to build a executable jar with many other dependencies jars; Failed with 2 solutions, same as Simon Tuffs,  then I decided to use what he offered, the OneJar.


Here are the Steps used in Mac 10.10, Eclipse IDE 3.7

Ref: http://obscuredclarity.blogspot.com/2011/05/java-one-jar-example-using-ant-and.html


One time OneJar Load in IDE


  1. Downloaded one-jar-ant-task-0.97.jar
  2. Copied the file into /Applications/Eclipse/plugins
  3. In Eclipse IDE (3.7), Preferences -> Ant -> Runtime, in right side window, click on 'Ant Home Entries (Default)'; Then use 'Add External JARs...' to add the newly added one-jar-ant-task jar file.




Ant Build Changes

NOTE: Assuming the project build is successful, and you have to create the new exec bundled onejar

Copy and paste the follow code snippet to build onejar and execute the one jar file; Dont forget to edit main jar file location and lib jar file locations to fit the main Ant build


<taskdef name="one-jar" classname="com.simontuffs.onejar.ant.OneJarTask" onerror="report" />
  <target name="onejar" depends="jar">
    <!-- Construct the One-JAR file -->
    <one-jar destfile="${ant.project.name}Exec.jar">
      <manifest>
        <attribute name="One-Jar-Main-Class" value="${main-class}"/>
      </manifest>
      <main jar="${ant.project.name}.jar" />
      <lib>
        <fileset dir="${lib.dir}" />
      </lib>
      <fileset dir="${src.dir}" includes="log4j.properties"/>
    </one-jar>
  </target>

  <target name="run onejar" depends="onejar">
    <java jar="${ant.project.name}Exec.jar" fork="true" />
  </target>



Thanks Simon Tuffs!

Ant build xml in Gist

More Example: http://one-jar.cvs.sourceforge.net/viewvc/one-jar/one-jar-log4j/

Other Ref:
http://j2stuff.blogspot.com/2011/07/onejava-example.html