Thursday, January 28, 2016

force maven to add jars to your workspace (eclipse)

Firs of all, the reason why I am posting this is: I hit a snag because of this and took a few hours to resolve my issue. The following plugin came to rescue, so I though to post it in case anybody else in the world needs it.

Just adding the execution plugin in your pom.xml does the trick of downloading all the jars to the target directory of your project in eclipse. 

<execution>
<phase>install</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration>
</execution>

Here is how the same would look like under the parent build element. 

<build>
   <plugins>
     <plugin>
       <artifactId>maven-dependency-plugin</artifactId>
          <executions>
            <execution>
              <phase>install</phase>
               <goals>
                <goal>copy-dependencies</goal>
               </goals>
                <configuration>
        <outputDirectory>${project.build.directory}/lib</outputDirectory>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
</build>

If this is what you were looking for, hope it is a help!

Cheers!

Tuesday, February 24, 2015

Automata

Let Σ be an alphabet. 
We define Σk to be the set of all strings of length k, each of whose symbols is in Σ.

Powers of an alphabet:
Σ = {a, e, t}
Σ0 = {ε}
Σ1 = {a, e, t}
Σ2 = {aa, ae, at, ea, ee, et, ta, te, tt}

Σ*  =  Σ0 U Σ1 U Σ2 U Σ3 U Σ4 U . . .
Σ+  =  Σ1 U Σ2 U Σ3 U Σ4 U . . .
Σ*  =  Σ0  U  Σ+  =  {ε} U  Σ+

More precisely if  string x and y are as:
x = a1 a2 a3 . . . ai
and
y = b1 b2 b3 . . . bj
then
x y = a1 a2 a3 . . . ai  b1 b2 b3 . . . bj

Language:
If Σ is an alphabet and L is a subset of Σ*,
then L is a language over alphabet Σ.

Example of Language:
ex. a language over {a, e, t}
{ a, at, ate, eat, tat, tea, tee }

Sometimes it is difficult to specify the strings of a language.

The language of all strings consisting of n 0's followed by n 1's for some n ≥ 0. { empty, 0 1,  0 0 1 1, 0 0 0 1 1 1, . . . }
2. The set of strings of 0's and 1's with an equal number of each.
3. The set of binary numbers whose value is a prime.
4. Σ* for any alphabet Σ.
5. Φ, the empty language, is a language over any alphabet.
6. {ε}, the language consisting of only the empty string is a language over any alphabet. Notice that Φ ≠ {ε}.

In automata theory, a problem is the question of deciding whether a given string is a member of some particular language.
If Σ is an alphabet and L is a language over Σ , then the problem L is:
Given a string w in Σ*, decide whether or not w is in L.

Notes from: Book Chapter 1 Sections 1.2 to 1.4, 1.5 and Chapter 2

To be added later

--------###########-----------
Components of a finite automaton
automaton has a finite set of states
control moves from state to state in response to external inputs

Kinds of finite automata:
Deterministic (it is also a finite automata)
automaton cannot not be in more than one state at one time

nondeterministic (it is also a finite automata)
automaton may be in several states at once

right linear grammars:
HMU, p. 182
Right-linear: if each production body has at most one variable, and that variable is at the right end. That is, all productions of a right-linear grammar are of the form A -> wB or A -> w, where A and B are variables and w some string of zero or more terminals.

Exactly the same languages can be:
• recognized by a finite state automaton (deterministic or nondeterministic)
• defined by a regular expression
• defined by a right linear grammar (or a left linear grammar)

A deterministic finite automaton is a 5-tuple
A = (Q, Σ, δ, q0, F)
where
Q is a finite set of states,
Σ is a finite set of input symbols,
δ is a transition function
δ: Q x  Σ →  Q
q0  ε Q  is the start state (or initial state), and
F is a subset of Q called the set of final states or accepting states.





The language of a deterministic finite automaton
A = (Q, Σ, δ, q0, F)
is
L(A) = { w | δ'(q0,w) is in F, w is in Σ* }
If L = L(A) for some dfa A, we say that L is a regular language.
i.e., the language of A is the set of strings w that take the start state q0 to one of the accepting states. If L is L(A) for some DFA A, then we say L is a regular language.


transition table (or state table)
A transition table is a tabular representation of a transition function.
Each row corresponds to a state.
Each column corresponds to an input symbol.
The entry in the row corresponding to state q and the column corresponding to input symbol a is the state δ(q,a).

An IDENTIFIER is a string of characters (typically letters or digits) that refers to (identifies) an entity, such as a data object, a procedure, a class, or a type.
All identifiers are names, but not all names are identifiers.
NAMES can be expressions.
x.y might denote the field y of a structure denoted by x.
x and y are identifiers; x.y is a name but not an identifier
Composite names like x.y are called QUALIFIED NAMES.
A VARIABLE refers to a particular location of the store. 
It is common for the same identifier to be declared more than once; each such declaration introduces a new variable. 
Even if each identifier is declared just once, an identifier local to a recursive procedure will refer to different locations of the store at different times.

IDENTIFIER
BASIC (early)
letter or letter followed by digit
FORTRAN IV
1-6 letters or digits, 1st character is letter
ALGOL 60
1 or more letters or digits, 1st character is letter

Java - Identifier
"an identifier is one or more characters selected from alpha, digit, underscore, or dollar sign. The only restriction is the first character can't be a digit."
http://www.cs.umd.edu/~clin/MoreJava/Intro/var-ident.html


Any missing transitions are assumed to lead to an error state.
Once the DFA is in the error state, it remains in that error state.



Example DFAs and NDFAs on Final slides in L02CS422-2014D.pptx

Some problems to solve (basedon HMU, pp. 52-55)

State: the purpose of a state is to remember the relevant portion of the system’s history.

In finite automata, since there are finite number of states and entire history of the system can not be remembered, so the system must be designed carefully to remember what is important and forget what is not.

The advantage of finite automaton is that we can implement the system with a fixed set of resources because the number of states is finite.

A language L, which is cannot be defined by a regular expression or finite automaton is NOT a Regular Language.

IN designing system: what should be important about the problem is what sequences of events can happen, not who is allowed to initiate them.

Deterministic: On each input there is one and only one state to which the automaton can transition from its current state. A nondeterministic automaton can be in several states at once.

---------##########--------------

Nondeterministic finite automaton:
Difference from Deterministic Finite Automaton is:
δ: Q x  Σ →  2Q

2Q = { A | A is a subset of Q }
ex. Q = { a, b, c }
2Q = { Φ, {a}, {b}, {c}, {a,b}, {a,c}, {b,c}, {a,b,c} }
Why this notation?
|2Q| = 2|Q| 
ex. |2{a,b,c} | = 2|{a,b,c}|  = 23 = 8

Dead States:
A dead state is a nonaccepting state that goes to itself on every possible input symbol.  It corresponds to Φ, the empty set of states.
We can add a dead state to any automaton that has no more than one transition for any state and input symbol.  Then add a transition to the dead state from each other state q, on all input symbols for which q has no other transition.
HMU, p. 67
(Some we call this an "error" state or a "trap" state.)

Ways of thinking about execution of a NFA (nondeterministic finite automaton)

At each time step, the automaton can be in multiple states.
2. When a transition would send the automaton to multiple next states, make a separate copy for each legal state and continue (with each copy only in a single state).
3. Perform a depth-first search, quitting with success when one path is in a final state when all input has been read or quitting with failure when all paths have been followed with none ending in final state.


The deterministic finite automata and nondeterministic finite automata are equivalent in power.
By definition every deterministic finite automaton is a nondeterministic finite automaton.
The "subset construction" on the previous slide shows that for every nondeterministic finite automaton we can construct a deterministic finite automaton that recognizes exactly the same language.



To Convert NDFSA to DFSA
--replace all transitions from a state that puts the FSA into multiple other states with one transition that puts it into a *new* single state (that will represent the multiple states) and will take all transitions off those multiple states.


It is an open research question whether deterministic and nondeterministic linear bounded automata are  equivalent in power.  (type 1)



Wednesday, October 8, 2014

Algorithms

—Heap - controlled by developer (more bugs?)  malloc(), free(), and realloc()
Can cause “memory leak - means the memory getting so full that software-program crashes” because developer may forget to deallocate the memory in heat.
—Stack - automatic memory for function calls…each function call create one and is deallocated after the function call exists. (less bugs?)

—Pass the pointer to a thing by using & in c.

—In linked list, the head pointer(local to a function) is in stack and the node is in the heap(user created, malloc’d)

—Recursion is solving problem by solving a smaller problem of the same type.

—Recursive algorithm must have a base case. Where there is more than one recursive call, you will often need more than one base case.

Quick Sort
http://www.mycstutorials.com/artiles/sorting/quicksort

Algorithm for partition:

1. while data[index_to_bigger_data] <=data[pivot]
        ++index_to_bigger_data
2. while data[index_to_smaller_data] <=data[pivtot]
        --index_to_smaller_data
3. if index_to_bigger_data < index_to_smaller_data
        swap data[index_to_bigger_data] and data[index_to_smaller_data]
4. While index_to_smaller_data > index_to_bigger_data, go to 1.
5. Swap data[index_to_smaller_data] and data[pivot_index]


Friday, February 3, 2012

*nix logs, input output error redirection and tee


Something that nobody explains...Logging with the 0, 1, 2, > and & in *nix environments


Ever wondered what those greater than, less than and ampersand meant in commands that you encounter time to time? Well here is the answer:

I use three different input and output channels(STDIN, STDOUT and STDERR). A little bit of background on these: these are three pre connected input and output channels between a computer program and its environment, eg. a text terminal when it begins execution. These are called standard input(stdin), standard output(stdout) and standard error(stderr).
File Descriptor(search this on google) for STDIN, STDOUT and STDERR are 0, 1 and 2 respectively.
Now when you look at the example below, you will feel like you have gained something(I certainly hope so with the condition that you didn’t know about this before, or had only partial clue).
Examples for output redirection:

Example 1:
-----------------------------------------------
someprogram.bat  2>&1
-----------------------------------------------
Explanation:
someprogram.bat : is name of program or command
2:  stderr (remember 2 is file descriptor for STDERR)
> : symbol for redirection or for appending or sending something to whatever comes next
&: in such scenarios & is used just before the name of the target(maybe for dereferencing?)
1: stdout (recall? 1 is file descriptor for STDOUT)
summary of explanation: errors from program goes to 2(by default) but then whatever is in 2, we are manually redirecting to 1.
That’s all there is to it.

Example 2:
-----------------------------------------------
someprogram.bat  2>&1  | tee prog_log_error.log
-----------------------------------------------
Explanation:
read the above explanation then continue to next line here.
| : is piping, just like piping water from one tube to another.
tee: name of an internal *nix  command. (this command sends copies of output to two different
                destinations: a file and a console(the screen?)
prog_log_error.log: name of a log file that we give(make sure you give the full path of this file) where tee program sends whatever is in 1(stdout). Tee also sends the same content(in 1) to console(stdout).

Just one more fact: most *nix shells allow both standard output and standard error to be redirected to the same file using:
-----------------------------------------------
&> your_log_file_name 
-----------------------------------------------

Skol!

~Nirmal

“First they ignore you. Then they laugh at you. Then they fight you. Then you win.” – Mahatma Gandhi

Monday, December 26, 2011

Automate Email(gmail) with Spring, Quartz and Java

The tool I will describe here is automated email sending application that can be scheduled in various ways. It doesn't need to run on a server but you have the option for it.

I will include all end to end code, including the build instruction, setting up the libraries with maven and using it with various options.

Look for "Download" link for the zip file with all the projected files at the bottom of this blog (before my signature).
The link should take you to a free space hosting site. I have included complete source code with maven script, java source code and spring and quartz configuration files and the properties file.

Software framework used in this email scheduling application are:

Spring
Maven
Java 6 (java mail api)
QuartzScheduler
Spring-Quartz support

I have used Eclipse (J2EE SOA) to develop this application.

I will start with the application context file that I have used to tell spring what to load and what to inject.

1:    
2:  <?xml version="1.0" encoding="UTF-8"?>  
3:    
4:  <!--   
5:   Copyright 2011: Nirmal Singh Software Resource and Services.  
6:   Disclosure, Use or Reproduction without the written authorization of NSSRS is "not" is prohibited.  
7:  -->  
8:    
9:  <beans xmlns="http://www.springframework.org/schema/beans"  
10:       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
11:       xmlns:aop="http://www.springframework.org/schema/aop"  
12:       xmlns:tx="http://www.springframework.org/schema/tx"  
13:       xmlns:context="http://www.springframework.org/schema/context"  
14:       xsi:schemaLocation="http://www.springframework.org/schema/beans   
15:        http://www.springframework.org/schema/beans/spring-beans-2.0.xsd  
16:        http://www.springframework.org/schema/aop   
17:        http://www.springframework.org/schema/aop/spring-aop-2.0.xsd  
18:        http://www.springframework.org/schema/tx   
19:        http://www.springframework.org/schema/tx/spring-tx-2.0.xsd  
20:              http://www.springframework.org/schema/context   
21:              http://www.springframework.org/schema/context/spring-context.xsd">  
22:      
23:       <!-- the parent application context definition for the dashboard application -->  
24:         
25:    <bean id="propertyConfigurer"   
26:       class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
27:      <property name="locations">  
28:        <list>  
29:          <value>classpath:notification.properties</value>  
30:        </list>  
31:      </property>  
32:    </bean>  
33:         
34:       <bean id="emailerImpl" class="org.springframework.mail.javamail.JavaMailSenderImpl">  
35:      <property name="host" value="${mail.host}"/>  
36:      <property name="port" value="${mail.port}"/>  
37:      <property name="username" value="${mail.username}"/>  
38:      <property name="password" value="${mail.password}"/>  
39:      <property name="javaMailProperties">  
40:        <props>  
41:          <!-- Use SMTP transport protocol -->  
42:          <prop key="mail.transport.protocol">smtp</prop>  
43:          <!-- Use SMTP-AUTH to authenticate to SMTP server -->  
44:          <prop key="mail.smtp.auth">true</prop>  
45:          <!-- Use TLS to encrypt communication with SMTP server -->  
46:          <prop key="mail.smtp.starttls.enable">true</prop>  
47:          <prop key="mail.debug">true</prop>  
48:           <prop key="mail.smtp.quitwait">false</prop>  
49:        </props>  
50:      </property>  
51:    </bean>  
52:         
53:         
54:       <bean id="emailManager" class="com.nirmal.singh.spring.gmail.SimpleMailManager">  
55:            <property name="sender" ref="emailerImpl"/>  
56:            <property name="senderAddress" value="${mail.from}"/>  
57:            <property name="notificationGroup" value="${mail.to}"/>  
58:       </bean>  
59:         
60:  </beans>  
61:    


Lines 34 and 54 are crucial here. As you can see, the application is going to use org.springframework.mail.javamail.JavaMailSenderImpl and that object can intern be used by your(mine) custom written SimpleMailManager(implements custom written MailManager)

Here are SimpleMailManager and MailManager:

SimpleMailManager.java:
1:    
2:  package com.nirmal.singh.spring.gmail;  
3:    
4:  import org.springframework.mail.MailSender;  
5:  import org.springframework.mail.SimpleMailMessage;  
6:    
7:  import com.nirmal.singh.spring.gmail.mailmanager.MailManager;  
8:    
9:  public class SimpleMailManager implements MailManager {  
10:    
11:       public MailSender sender = null;  
12:    
13:       public String senderAddress;  
14:    
15:       public String[] notificationGroup;  
16:    
17:       public void setSender(MailSender sender){  
18:            this.sender = sender;  
19:       }  
20:    
21:       public void setSenderAddress(String senderAddress){  
22:            this.senderAddress = senderAddress;  
23:       }  
24:    
25:       public void setNotificationGroup(String delimitedAddressString){  
26:            if (delimitedAddressString != null && delimitedAddressString.trim().length() > 0){  
27:                 String[] possibleAddress = delimitedAddressString.split(";");  
28:                 int nonEmptyCnt = 0;  
29:                 for (String str : possibleAddress){  
30:                      if (str != null && str.trim().length() > 0){  
31:                           nonEmptyCnt++;  
32:                      }  
33:                 }  
34:                 if (nonEmptyCnt > 0){  
35:                      String[] nonEmpty = new String[nonEmptyCnt];  
36:                      int ind = 0;  
37:                      for (String str : possibleAddress){  
38:                           if (str != null && str.trim().length() > 0){  
39:                                nonEmpty[ind] = str.trim();  
40:                                ind++;  
41:                           }  
42:                      }  
43:                      this.notificationGroup = nonEmpty;  
44:                 }  
45:            }  
46:       }  
47:    
48:       public void process(SimpleMailMessage mail){  
49:            if (emptyString(mail.getFrom())){  
50:                 mail.setFrom(this.senderAddress);  
51:            }  
52:            if (mail.getTo() == null || mail.getTo().length < 1){  
53:                 mail.setTo(this.notificationGroup);  
54:            }  
55:              
56:            this.sender.send(mail);  
57:       }  
58:    
59:       public SimpleMailMessage getTemplateNotification(){  
60:            SimpleMailMessage message = new SimpleMailMessage();  
61:            message.setFrom(this.senderAddress);  
62:            message.setReplyTo(this.senderAddress);  
63:            message.setTo(this.notificationGroup);  
64:            return message;  
65:       }  
66:    
67:       private boolean emptyString(String str){  
68:            return str == null || str.trim().length() < 1;  
69:       }  
70:    
71:  }  
72:    
73:    

MailManager.java:

1:    
2:  package com.nirmal.singh.spring.gmail.mailmanager;  
3:  import org.springframework.mail.SimpleMailMessage;  
4:    
5:  public interface MailManager {  
6:       /**  
7:        * Gets an email instance with the typical addressing information for a general notification.  
8:        * @return An email object with the configured values for addresses.  
9:        */  
10:       public SimpleMailMessage getTemplateNotification();  
11:    
12:       public void process(SimpleMailMessage mail);  
13:    
14:  }  
15:    

Now, the best way to take care of all the dependencies, as most open source developers can agree, is to use maven dependencies for your project. Here is all in one pom.xml for this application.

pom.xml
1:    
2:  <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
3:   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
4:   <modelVersion>4.0.0</modelVersion>  
5:   <groupId>com.nirmal.singh.spring.sendemail</groupId>  
6:   <artifactId>SpringQuartzGmailMaven</artifactId>  
7:   <packaging>jar</packaging>  
8:   <version>1.0-SNAPSHOT</version>  
9:   <name>SpringExample</name>  
10:   <url>http://maven.apache.org</url>  
11:     
12:   <dependencies>  
13:    <!-- Spring framework -->  
14:       <dependency>  
15:            <groupId>org.springframework</groupId>  
16:            <artifactId>spring</artifactId>  
17:            <version>2.5.6</version>  
18:       </dependency>  
19:      
20:    <!-- Quartz framework -->  
21:    <dependency>  
22:         <groupId>opensymphony</groupId>  
23:         <artifactId>quartz</artifactId>  
24:         <version>1.6.3</version>  
25:       </dependency>  
26:    
27:       <dependency>  
28:         <groupId>commons-collections</groupId>  
29:         <artifactId>commons-collections</artifactId>  
30:         <version>3.2.1</version>  
31:       </dependency>  
32:    
33:       <!-- java activation framework -->       
34:       <dependency>  
35:            <groupId>javax.activation</groupId>  
36:            <artifactId>activation</artifactId>  
37:            <version>1.1</version>  
38:       </dependency>  
39:         
40:       <!-- java mail framework -->  
41:       <dependency>  
42:            <groupId>javax.mail</groupId>  
43:            <artifactId>mail</artifactId>  
44:            <version>1.4</version>  
45:       </dependency>  
46:         
47:      
48:   </dependencies>  
49:  </project>  
50:    

Since there are a lot of things that can change for email preferences, I have included those in a properties file.

notification.properties:
1:    
2:  # Properties file with mail-related settings, used for notification emails.  
3:  # Applied by PropertyPlaceholderConfigurer from "applicationContext.xml".  
4:  # Targeted at system administrators, to avoid touching the context XML files.  
5:  #copyright: Nirmal Singh Software Resource Services nirmalksingh@gmail.com  
6:    
7:  # SMTP host used as email relay  
8:  mail.host=smtp.gmail.com  
9:  mail.port=25  
10:  # Address appearing as "From" for template-based messages  
11:  mail.from=your_email_id@gmail.com  
12:    
13:  # Address(e) appearing as "To" for template-based messages  
14:  # Multiple addresses maybe separated by semi-colons (;)  
15:  #you can send email to as many as I guess 1000 or even more. Please check on that.  
16:  mail.to=some_address1@hotmail.com;some_address1@students.someuniv.edu;some_other@some_site.something  
17:    
18:  # google gmail requires your sender's email address for sending email from non-gmail application like this application  
19:  mail.username=your_gmail_address (eg. nirmalksingh@gmail.com)  
20:    
21:  # google gmail requires your sender's password for sending email from non-gmail application like this application  
22:  mail.password=your_password  
23:    


Now it is turn to talk about the Quartz Scheduler.
First of all I'll share with you the quartz scheduler configuration file.

Spring-Quartz.xml: ( we will load this file simultaneously when we load application contecxt file)
1:  <beans xmlns="http://www.springframework.org/schema/beans"  
2:  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
3:  xsi:schemaLocation="http://www.springframework.org/schema/beans  
4:  http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">  
5:     
6:    <bean id="sendEmailTask" class="com.nirmal.singh.spring.quartz.task.SendEmailTask" />  
7:      
8:    <bean name="jobDetailBean" class="org.springframework.scheduling.quartz.JobDetailBean">  
9:            <property name="jobClass" value="com.nirmal.singh.spring.quartz.job.RunJobSendEmailTask" />  
10:            <property name="jobDataAsMap">  
11:                 <map>  
12:                      <entry key="sendEmailTask" value-ref="sendEmailTask" />  
13:                 </map>  
14:            </property>  
15:       </bean>  
16:     
17:       <bean id="methodInvokingJobDetailFactoryBean" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">  
18:            <property name="targetObject" ref="sendEmailTask"/>  
19:            <property name="targetMethod" value="runSendEmailTask"/>  
20:            <!--If JobDetail objects implement the Stateful interface, this won't happen.   
21:            The second job will not start before the first one has finished.   
22:            To make jobs resulting from the MethodInvokingJobDetailFactoryBean non-concurrent,   
23:            set the concurrent flag to false. as in below-->  
24:            <property name="concurrent" value="false"/>  
25:       </bean>  
26:     
27:        <!-- experimental -->  
28:       <!-- Simple Trigger -->  
29:       <bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">  
30:             <!-- see the example of method invoking job above -->  
31:             <property name="jobDetail" ref="jobDetailBean"/>  
32:            <!-- 10 seconds -->  
33:             <property name="startDelay" value="10000"/>  
34:            <!-- repeat every 50 seconds -->  
35:  <!--           <property name="repeatInterval" value="50000"/>-->  
36:             <property name="repeatInterval" value="15000"/>  
37:       </bean>  
38:         
39:       <!-- Cron Trigger -->  
40:  <!--     <bean id="cronTrigger"-->  
41:  <!--          class="org.springframework.scheduling.quartz.CronTriggerBean">-->  
42:  <!--          <property name="jobDetail" ref="methodInvokingJobDetailFactoryBean" />-->  
43:  <!--          <property name="cronExpression" value="1 39-41 16 * * ?" /> Fire every minute starting at 4:06PM(inclusive) and ending at 4:09 (inclusive) PM, every day-->  
44:  <!--     </bean>-->  
45:    
46:       <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
47:            <property name="jobDetails">  
48:                 <list>  
49:                      <ref bean="jobDetailBean" />  
50:                 </list>  
51:            </property>  
52:            <property name="triggers">  
53:                 <list>  
54:                      <ref bean="simpleTrigger" /> <!-- experimental -->  
55:  <!--                    <ref bean="cronTrigger" />-->  
56:                 </list>  
57:            </property>  
58:       </bean>  
59:     
60:  </beans>  

That's it configuration-wise. Here are the java resources that are used by the above quartz scheduler configurer.

QuartzGmailMainApp.java is the starting of the application, you need to run this one to make the application work and send emails, be sure to use your preferred cron expression in the Spring-Quartz.xml file. Here are some examples of cronExpressions:


0 0 12 * * ? Fire at 12:00 PM (noon) every day
0 15 10 ? * * Fire at 10:15 AM every day
0 15 10 * * ? Fire at 10:15 AM every day
0 15 10 * * ? * Fire at 10:15 AM every day
0 15 10 * * ? 2005 Fire at 10:15 AM every day during the year 2005
0 * 14 * * ? Fire every minute starting at 2:00 PM and ending at 2:59 PM, every day
0 0/5 14 * * ? Fire every 5 minutes starting at 2:00 PM and ending at 2:55 PM, every day
0 0/5 14,18 * * ? Fire every 5 minutes starting at 2:00 PM and ending at 2:55 PM, AND fire every 5 minutes starting at 6:00 PM and ending at 6:55 PM, every day
0 0-5 14 * * ? Fire every minute starting at 2:00 PM and ending at 2:05 PM, every day
0 10,44 14 ? 3 WED Fire at 2:10 PM and at 2:44 PM every Wednesday in the month of March
0 15 10 ? * MON-FRI Fire at 10:15 AM every Monday, Tuesday, Wednesday, Thursday and Friday
0 15 10 15 * ? Fire at 10:15 AM on the 15th day of every month
0 15 10 L * ? Fire at 10:15 AM on the last day of every month
0 15 10 ? * 6L Fire at 10:15 AM on the last Friday of every month
0 15 10 ? * 6L Fire at 10:15 AM on the last Friday of every month
0 15 10 ? * 6L 2002-2005 Fire at 10:15 AM on every last friday of every month during the years 2002, 2003, 2004, and 2005
0 15 10 ? * 6#3 Fire at 10:15 AM on the third Friday of every month
0 0 12 1/5 * ? Fire at 12 PM (noon) every 5 days every month, starting on the first day of the month
0 11 11 11 11 ? Fire every November 11 at 11:11 AM




Here is the main class of the application:
QuartzGmailMainApp.java:

1:    
2:  package com.nirmal.singh.spring.quartz.gmail.mainapp;  
3:    
4:  import com.nirmal.singh.spring.quartz.task.SendEmailTask;  
5:    
6:  import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;  
7:  import org.springframework.context.support.GenericApplicationContext;  
8:  import org.springframework.core.io.ClassPathResource;  
9:    
10:  public class QuartzGmailMainApp {  
11:    public static void main( String[] args ) throws Exception {  
12:         GenericApplicationContext context = new GenericApplicationContext();  
13:         XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(context);  
14:            xmlReader.loadBeanDefinitions(new ClassPathResource("applicationContext-gmail.xml"));  
15:            xmlReader.loadBeanDefinitions(new ClassPathResource("Spring-Quartz.xml"));  
16:            context.refresh();  
17:         SendEmailTask.context = context;  
18:    }  
19:  }  
20:    

SendEmailTask.java (contains task invoked by the quartz scheduler)
1:  package com.nirmal.singh.spring.quartz.task;  
2:    
3:  import org.springframework.context.support.GenericApplicationContext;  
4:  import org.springframework.mail.SimpleMailMessage;  
5:    
6:  import com.nirmal.singh.spring.gmail.SimpleMailManager;  
7:    
8:  public class SendEmailTask {  
9:         
10:       static int i = 0;  
11:       public static GenericApplicationContext context;  
12:    
13:       /**  
14:        * This job is configured to trigger with a qurtz scheduler's cron expression in Spring-Quartz.xml file.   
15:        */  
16:       public void runSendEmailTask() {  
17:    
18:            System.out.println("Running job #" + ++i);  
19:    
20:            SimpleMailManager mailMgr = (SimpleMailManager) context.getBean("emailManager");  
21:            if (mailMgr.notificationGroup != null && mailMgr.notificationGroup.length > 0) {  
22:                 String[] str = (String[]) mailMgr.notificationGroup;  
23:                 System.out.println("Notified group email address(s) :");  
24:                 for (int i = 0; i < str.length; i++) {  
25:                      System.out.println(str[i]);  
26:                 }  
27:            }  
28:    
29:            System.out.println("Sender's address :");  
30:            System.out.println(mailMgr.senderAddress.toString());  
31:    
32:            SimpleMailMessage mail = mailMgr.getTemplateNotification();  
33:    
34:            StringBuffer sb = new StringBuffer();  
35:            sb.append("This is a test email from Nirmal, please ignore.");  
36:            mail.setText(sb.toString());  
37:            mail.setSubject("This is a test message, please ignore.");  
38:            mailMgr.process(mail);  
39:       }  
40:  }  

Quartz scheduler uses a "job" class to internally tell which user's task and target method for that task is to be used. As noted earlier in the Spring-Quartz.xml file. Here is the RunJobSendEmailTask.java
1:  package com.nirmal.singh.spring.quartz.job;  
2:    
3:  import org.quartz.JobExecutionContext;  
4:  import org.quartz.JobExecutionException;  
5:  import org.springframework.scheduling.quartz.QuartzJobBean;  
6:    
7:  import com.nirmal.singh.spring.quartz.task.SendEmailTask;  
8:     
9:  public class RunJobSendEmailTask extends QuartzJobBean {  
10:       private SendEmailTask sendEmailTask;  
11:     
12:       public void setSendEmailTask(SendEmailTask emailTask) {  
13:            this.sendEmailTask = emailTask;  
14:       }  
15:     
16:       protected void executeInternal(JobExecutionContext context)  
17:       throws JobExecutionException {  
18:            sendEmailTask.runSendEmailTask();  
19:       }       
20:  }  

That's all! Now you can run this application, give it a list of email address and tell the quartz scheduler when you want those email sent out.

Please feel free to ask any question you may have. I have built this application from scratch, I can explain each and every detail to you if you need me to. Please contact for fair pricing and commercial use of this software.
You can email me personally for the same at: nirmalksingh@gmail.com. Thanks for reading!

Link for downloading all the files: Download allFilesForBlogspot.zip

~Nirmal


Democracy means government by discussion, but it is only effective if you can stop people talking.
--Clement Atlee



Friday, October 22, 2010

Xml commenting Eclipse Shortcut

This shortcut is so important in my life that I decided to put out a blog just for sharing one line.

I always wished for a eclipse shortcut which would work for commenting out (for doing ) a line or a block in eclipse for .xml files.

One fine day while working, I can't remember whether it was a result of my derivative thought process or the big G, I got the way to comment out xml line/blocks with this short cut and that precious shortcut is:

CTRL+SHIFT+C

And it toggles.

Thanks for stopping by and thanks for reading...

~Nirmal

One of the cardinal rules of software development is: "Do not trust your own input"...

~anonymous

Tuesday, October 19, 2010

Maven commands for java developers

Yes if you know Maven you definitely are more advanced java developer. Using maven for day to day development has many benefits. I have been using for over three years now and recently encountered the fact that a lot of newbies are scared to use maven.

I decided to post this blog just to let know, all of the developer who are scared to use Maven, that it is really nothing. I mean all of us can usually download the stack and add it to the environment variable/path etc. But even after that I see newbies keep away from using it...well really the only thing most of the time we use Maven as a project management tool and as a build tool is as follows:

Clean, install and compile

prompt: mvn clean

prompt: mvn clean install

prompt: mvn clean install -Dmaven.test.skip=true

Happy Coding...

Thanks for reading...

~Nirmal

Monday, December 28, 2009

Perl regex, substitution, file reading/writing

Learning by doing is the best motto. With this motto when I was exploring perl I wrote few scripts to extract and use parts of learning materials on perl from the web.

Just because there are a lot of resource out there on the web doesn't mean they are going to help you be on a fast track of learning perl. There are a lot of redundant materials which we don't want to go over, often times we don't know how to cut to the chase.

I used to go to this site often: http://perldoc.perl.org

There are a lot of materials out there. In this article I would like to explore about pattern matching and substitution, reading from file and substituting certain parts of the lines in the file and writing the desired result to another file.

The program below builds the very fundamental concepts about:

1. Opening file.(a webpage from http://perldoc.perl.org)
2. Reading from the file line by line
3. Substituting into the line by getting rid of some interesting materials.
4. Writing to the file and to the console.

If you open http://perldoc.perl.org/perlrequick.html, you will see that the page tutors on pattern matching. It is a good material but personally I am only interested on things like:

1. "Hello World" =~ /World/; # matches

2. /[^a]at/; # doesn't match 'aat' or 'at', but matches # all other 'bat', 'cat, '0at', '%at', etc.

3. /[^0-9]/; # matches a non-numeric character

4. /[a^]at/; # matches 'aat' or '^at'; here '^' is ordinary

Looking at above line it is so easy to quickly build the idea without having to read all of the explanation.

So, as I continue to believe in "learning by doing", I wrote a couple of scripts to extract only info I wanted from such tutorial.


--The following script reads the input text file we created by coping/pasting from the url: http://perldoc.perl.org/perlrequick.html

--looks for only those lines which have a pattern as in: "1. blah or 1. blah etc"

--writes the matches lines from file input into a separate file and to the console.

*to successfully run the program you will have to select the page at http://perldoc.perl.org/perlrequick.html
and copy/paste into a text file (in my case the text file is called: perl_regex.txt located at my personal directory
on my mac which is "Users/my_name/perlscripts/"

#########################################################

#!/usr/bin/perl –w

$data_file = "/Users/my_name/perlscripts/perl_regex.txt"; #replace this line with location/name of your file

$out_file = "out_file.txt";

open(FHAND, $data_file) or die $!;

open(OUTHAND, ">out_file.txt") || die $!;

while(){
if($_ =~/^(\s.*[1-9]|[1-9])\./){
print "$_\n";
print OUTHAND "$_\n";
}
}

close(FHAND);
close(OUTHAND);

#########################################################


If you can successfully run the above you will be at a great relief(at least I was) when you see the simple to read concepts about pattern matching.

The out put looks something like

#########################################################

1. print "It matches\n" if "Hello World" =~ /World/;

1. print "It doesn't match\n" if "Hello World" !~ /World/;

1. $greeting = "World";

2. print "It matches\n" if "Hello World" =~ /$greeting/;

1. $_ = "Hello World";

2. print "It matches\n" if /World/;

1. "Hello World" =~ m!World!; # matches, delimited by '!'

2. "Hello World" =~ m{World}; # matches, note the matching '{}'

3. "/usr/bin/perl" =~ m"/perl"; # matches after '/usr/bin',

4. # '/' becomes an ordinary char

1. "Hello World" =~ /world/; # doesn't match, case sensitive

#########################################################

Still, it is a little unreadable if you look at the numbering and spacing. Those dotted numbers don't make sense. So?
Guess what we, we write another script to get rid of those as in the following:



To read the earlier output file, replace the numbering and space and to write the extracted text into a new file:

#########################################################
#!/usr/bin/perl -w

$read = "/users/nirmalksingh/perlscripts/out_file.txt";

open(READHANDLE, $read) || die $!;
open(WRITEHANDLE, ">out_file2.txt") || die $!;

while(){
# $_ =~ s/^([1-9]/.)\s.*/\s/g;
$_ =~ s/^([1-9]\.)\s+//g;
print WRITEHANDLE $_;
print "$_\n";
}

close READHANDLE;
close WRITEHANDLE;

#########################################################

Now, in essence, the output file/console looks more or less like as follows:

#########################################################

'cathouse' =~ /cat$foo/; # matches

'housecat' =~ /${foo}cat/; # matches

"housekeeper" =~ /keeper/; # matches

"housekeeper" =~ /^keeper/; # doesn't match

"housekeeper" =~ /keeper$/; # matches

"housekeeper\n" =~ /keeper$/; # matches

"housekeeper" =~ /^housekeeper$/; # matches

/cat/; # matches 'cat'

#########################################################

That's all.

As I succeeded along, I modified the input further on and on doing other substitutions and writing them to file/console accordingly.

It can get really really addictive because with perl it is always DWIS (do what i say) and that's very satisfying for programmers.

Thanks for visiting and reading, please feel free to write to me directly if you have any question/s. I will be glad to answer as you wish.

~nirmal

Friday, December 25, 2009

Perl man

One of the best ways to learn programming tools and languages which fall under *nix domain is using "MAN PAGES".
The following is a list of key words to explore using the "perldoc" command in your shell.

Usually you can enter keywords for most of the perl related manual pages followed by "perldoc".
For eg. if you enter as in below:

################################

blah-blah$perldoc perlsyn

################################

it will output a buffer of text about perl syntax as in below:

################################

PERLSYN(1) User Contributed Perl Documentation PERLSYN(1)



NAME
perlsyn − Perl syntax

DESCRIPTION
A Perl program consists of a sequence of declarations and statements
which run from the top to the bottom. Loops, subroutines and other
control structures allow you to jump around within the code.

Perl is a free‐form language, you can format and indent it however you
like. Whitespace mostly serves to separate tokens, unlike languages
like Python where it is an important part of the syntax.

Many of Perl’s syntactic elements are optional. Rather than requiring
you to put parentheses around every function call and declare every
variable, you can often leave such explicit elements off and Perl will
figure out what you meant. This is known as Do What I Mean,
abbreviated DWIM. It allows programmers to be lazy and to code in a
style with which they are comfortable.

Perl borrows syntax and concepts from many languages: awk, sed, C,
Bourne Shell, Smalltalk, Lisp and even English. Other languages have
borrowed syntax from Perl, particularly its regular expression
extensions. So if you have programmed in another language you will see
familiar pieces in Perl. They often work the same, but see perltrap
for information about how they differ.

Declarations

The only things you need to declare in Perl are report formats and
subroutines (and sometimes not even subroutines). A variable holds the
undefined value ("undef") until it has been assigned a defined value,
which is anything other than "undef". When used as a number, "undef"
is treated as 0; when used as a string, it is treated as the empty
string, ""; and when used as a reference that isn’t being assigned to,
it is treated as an error. If you enable warnings, you’ll be notified...

################################

just like perlsyn below are other important keywords which you can use to put yourself on fast track of
learning and using perl...

perlpod -perlpod − the Plain Old Documentation format

perlpodspec − Plain Old Documentation: format specification and notes

perldata − Perl data types

perlop − Perl operators and precedence

perlunicode − Unicode support in Perl

perluniintro − Perl Unicode introduction

perlref − Perl references and nested data structures

perlfunc − Perl builtin functions

perlsub − Perl subroutines

perlmod − Perl modules (packages and symbol tables)

As you can see above, many of the keywords for pulling the man pages are intuitive. It can be hard to memorize all of the keywords(i don't know if they are termed as keyword, I learnt perl on my own:) )
So doing a little guesswork to spell the keyword can be a faster way to quickly pull up related man pages when you need to get some info on a perl construct that you intend to use in your program.

For eg. if you want to get to manual pages which has examples on "opening" things in perl then you could do construct a key word like this: perl open tut (for perl opne tutorial) and could enter with perldoc as in:

####################

blah-blah$ perldoc perlopentut

####################

Another example can be: perl object or perl obj as in perlobject or perlobj.
Trying each of your guessworks as in above will cater to a faster learning process, talking from my personal experience, I can say, I am sure :)


perlmodlib − constructing new Perl modules and finding existing ones

Few good example of using acronyms in your guess work is "perlboot" (boot=beginner's object oriented tutorial)

perlboot − Beginner’s Object−Oriented Tutorial

perltoot − Tom’s object−oriented tutorial for perl

perltooc − Tom’s OO Tutorial for Class Data in Perl


Some of my favorite keywords for getting info on perl regular expression:

perlre − Perl regular expressions

perlretut − Perl regular expressions tutorial

perlrequick − Perl regular expressions quick start


Some more keywords:

perlpacktut − tutorial on "pack" and "unpack"

PerlIO − On demand loader for PerlIO layers and root of PerlIO::* name
space

perlform − Perl formats

perltie − how to hide an object class in a simple variable

perlipc − Perl interprocess communication (signals, fifos, pipes, safe
subprocesses, sockets, and semaphores)

perlvar − Perl predefined variables

perlthrtut − tutorial on threads in Perl

perlcc − generate executables from Perl programs

perlcompile − Introduction to the Perl Compiler−Translator

perldebug − Perl debugging

perldebtut − Perl debugging tutorial

I will be composing more and more stuff on perl in future.
Thanks for reading from my page.

~nirmal

Monday, July 20, 2009

iTunes Store Continuous Play

Hola Amigos e Amigas :)

The following is an AppleScript utility for making the iTunes Store continuous play. Every now and then when we want to check out some new songs, we go to the iTunes Store on iTunes and we find that it is tormenting because we have to be hitting next song every 30 seconds.

This script is a solution for that problem. It has its limitations though. First of all, it will need to be run for each list(i will enhance it and repost when I can).

To get it work for you: copy and paste this script into "Script Editor".
1. Locate the "Script Editor" first by pressing "Command + Space" and typing "Script Editor"

2. Save the script as "iTunes Store Continuous.scpt"

3. Bring up the list you want to have continuous play on itunes store.

4. Toggle back to the script editor and hit "Play" button. (get used to the function by hitting Stop/Play a twice or thrice, just to see example of how it is working)

very important:

5. No need to install the script.

6. Always stop the script in the "script editor" by hitting the red "Stop" button before shutting down your computer or exiting itunes.

Enjoy!

~nirmal

repeat
tell application "iTunes"
next track
playpause
end tell
delay 32
end repeat

Monday, July 13, 2009

sh devLaunchYOUR_APPLICATION_NAME.sh

Voila!!

Finally recalled that invoke the shell command from putty when you are in some server machine is always: sh devLaunch_name_of_your_application.sh

I kept trying to just do:

[blah..blah...date..etc][qualifying_name/blah/blah/my_work_server_name]>devLaunchNAME_OF_APPLICATION.sh

and it won't work. I can't believe I took one hour to finally recall that it is always "sh" then devLaunch_NAME_OF_APPLICATION.sh

So all of you folks if you got here because of this is what you were missing, my pleasure and you are most welcome.

~nirmal

Tuesday, December 30, 2008

TimeSeries chart, JFreeChart

TimeSeries Chart

Time series charts are created using data from the XYDataset, it returns x-values which are of type double, these values are converted by a class called DateAxis which converts the huge double returned from XYDataset into dates and back to the double as necessary. How the double values are converted into dates isn't important for us to know, the DateAxis just does it for us which we can use to create the chart. If you are really interested to find out, then type "number of milliseconds since midnight, 1 January 1970, XYDataset, JFreeChart" in to the Holy Grail of Searches(google ;)), you might find some convincing results.

Charts usually have a domain, a time series as the name of the interface says itself(TimeSerieschart), has a domain which will have a series of times, as a matter of fact it can have values ranging from days to months.

TimeSeries can let you make objects of different times and it lets you add up all of the them and gives a series of times back as one object.
A dataset, TimeSeriesCollection, can be created out of the TimeSeries object by adding the TimeSeries object to the TimeSeriesCollection object. Since, TimeSeriesCollection implements XYDataset, the TimeSeriesCollection becomes a dataset which can be used to create the chart.

A chart is created with default settings but it is highly customizable, for example, a renderer object can be obtained from the plot which can in-turn be obtained from the chart. Now this renderer can be changed to display series shapes at each datas point, in addition to the lines between data points.And secondly, a date format override can be set for the domain axis.

To modify the renderer, first a reference to the renderer is needed and secondly cast of the rendrer into a XYLineAndShapeRenderer is required.

eg. to set the default shape visible and to set default shape filled the following magic will suffice:

XYItemRenderer r = plot.getRenderer();
if(r instanceof XYLineAndShapeRenderer)
{
XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
renderer.setDeafultShapeVisible(true);
renderer.setDefaultShapeFilled(true);
}

In other words, the above snippet of code puts a legend, which is picked for the series, at each data point.

To override the date format of the domain axis the follwing will do:

DateAxis axis =(DateAxis)plot.getDomainAxis();
axis.setDateFormatOverride(new SimpleDateFormat("MM=yyyy"));

Once the above date format override is set,the axis will auto-select a DateTickUnit and will ignore the formatting from the tick unit and use the override format instead.

I am including the following program which also features in the JFreeCharts Developer's Guide. If some of you have gone through the guide, and if you happened to try out
the following code, you will notice that I have excluded the "public static JPanel createDemoPanel()" method from this code snippet because for this example the method doesn't
serve any purpose.

Other points not explained in the guide are:

In the code section where the renderer is being customized this line "renderer.setDefaultShapesFilled(true);" is there but it is not required because the shape that we have picked for
displaying a mark is not hollow type.

The exact code I worked on can't be displayed here because of my company policy but I would refine on somethings which I did different from what appears below:
As you can see below, the timeseries objects are being hand carved one after another, in my case, this done in a for loop based on matching criterion of some of the
persistent properties of POJOs. In other words, I filled up my time series objects with dates from database based on the business requirement. You could do the same, no matter whether you use
Hibernate with Spring and POJOs or some other framework, JFreeChart's TimeSeries isn't meant for one set of implementation and environment.



package name.your.own;

import java.awt.Color;
import java.text.SimpleDateFormat;
import javax.swing.JPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.time.Month;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RectangleInsets;
import org.jfree.ui.RefineryUtilities;

public class TimeSeriesDemo extends ApplicationFrame
{

public TimeSeriesDemo(String title)
{
super(title);
XYDataset dataset = createDataset();
JFreeChart chart = createChart(dataset);
ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
chartPanel.setMouseZoomable(true, false);
setContentPane(chartPanel);
}

private static JFreeChart createChart(XYDataset dataset)
{
JFreeChart chart = ChartFactory.createTimeSeriesChart(
"Legal & General Unit Trust Prices", // title
"Date", // x-axis label
"Price Per Unit", // y-axis label
dataset, // data
true, // create legend?
true, // generate tooltips?
false // generate URLs?
);
chart.setBackgroundPaint(Color.white);
XYPlot plot = (XYPlot) chart.getPlot();
plot.setBackgroundPaint(Color.lightGray);
plot.setDomainGridlinePaint(Color.white);
plot.setRangeGridlinePaint(Color.white);
plot.setDomainCrosshairVisible(true);
plot.setRangeCrosshairVisible(true);
XYItemRenderer r = plot.getRenderer();

if (r instanceof XYLineAndShapeRenderer)
{
XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
renderer.setDefaultShapesVisible(true);
renderer.setDefaultShapesFilled(true);
}

DateAxis axis = (DateAxis) plot.getDomainAxis();
axis.setDateFormatOverride(new SimpleDateFormat("MMM-yyyy"));
return chart;
}

private static XYDataset createDataset()
{
TimeSeries s1 = new TimeSeries("L&G European Index Trust", Month.class);
s1.add(new Month(2, 2001), 181.8);s1.add(new Month(3, 2001), 167.3);s1.add(new Month(4, 2001), 153.8);s1.add(new Month(5, 2001), 167.6);
s1.add(new Month(6, 2001), 158.8);s1.add(new Month(7, 2001), 148.3);s1.add(new Month(8, 2001), 153.9);s1.add(new Month(9, 2001), 142.7);
s1.add(new Month(10, 2001), 123.2);s1.add(new Month(11, 2001), 131.8);s1.add(new Month(12, 2001), 139.6);s1.add(new Month(1, 2002), 142.9);
s1.add(new Month(2, 2002), 138.7);s1.add(new Month(3, 2002), 137.3);s1.add(new Month(4, 2002), 143.9);s1.add(new Month(5, 2002), 139.8);
s1.add(new Month(6, 2002), 137.0);s1.add(new Month(7, 2002), 132.8);

TimeSeries s2 = new TimeSeries("L&G UK Index Trust", Month.class);
s2.add(new Month(2, 2001), 129.6);s2.add(new Month(3, 2001), 123.2);s2.add(new Month(4, 2001), 117.2);s2.add(new Month(5, 2001), 124.1);
s2.add(new Month(6, 2001), 122.6);s2.add(new Month(7, 2001), 119.2);s2.add(new Month(8, 2001), 116.5);s2.add(new Month(9, 2001), 112.7);
s2.add(new Month(10, 2001), 101.5);s2.add(new Month(11, 2001), 106.1);s2.add(new Month(12, 2001), 110.3);s2.add(new Month(1, 2002), 111.7);
s2.add(new Month(2, 2002), 111.0);s2.add(new Month(3, 2002), 109.6);s2.add(new Month(4, 2002), 113.2);s2.add(new Month(5, 2002), 111.6);
s2.add(new Month(6, 2002), 108.8);s2.add(new Month(7, 2002), 101.6);

TimeSeriesCollection dataset = new TimeSeriesCollection();

dataset.addSeries(s1);
dataset.addSeries(s2);

dataset.setDomainIsPointsInTime(true);

return dataset;
}

public static void main(String[] args)
{
TimeSeriesDemo demo = new TimeSeriesDemo("Time Series Demo 1");
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);
}
}


The above examples and composition, entirely have been about still data, JFreeChart has interfaces for developing a chart system for live and streaming data as well, for example the guide talks about a little app for streaming the system resources usage in terms of dynamic charts. But the guide doesn't support it with high jinks because it could be very slow if you are crunching sizable amount of data because each time a dataset is updated, the ChartPanel reacts by redrawing the entire chart.

Saturday, December 27, 2008

Free JFreeCharts Info.

I had to use JFreeCharts all of a sudden, kind of in a rush. I had no previous information about it until I could get hold of a free JFreeCharts Developer Guide, I am lucky that I could use it since my company paid for it.

After accomplishing a few tasks using JFreeCharts, I wanted to summarize what I discovered about JFreeCharts. Well, without any further due I am going to get right into it:
To start with, it is an API to give a "face" to your data, so in simpler terms JFreeCharts helps you turn numbers into diagrams and the output diagrams can be be piped into as a PDF(using iText) or SVG(using batik) file. It fits well in a situation when you as a developer have to convey the meaning of the data in the database to a separate team like business or maybe the architecture team.

We have a tool that we developed in-hosue, the tool basically saves time since it makes querying the database a lot easier. There are tables in the database that tell how many times queries were fired and how many people were accessing the database and doing the four holy things that we always do with the database(add, edit, get, delete). Now, using the JFreeCharts methods I could give a meaningful representation to the logs in these tables, in terms of Pie Charts, Bar Charts, Line Charts, Scatter Plots, Time Series Charts etc.

I will get into details of my accomplishments with JFreeCharts but before thast just for a simple overview, the following is a list of packages into which all of the class libraries are bundled, for a resonoably advanced reader, the hierarchial names should give an initial insight into what can be accomplished with the classes and inturn the methods inside them.

(for brevity I have put everything that can be dotted in the parenthesis)
org.jfree.chart (annotations, axis, block, entity, event, imagemap, labels, needle, plot, renderer, renderer.category, renderer.xy, servlet, title, ui, urls,

(for brevity I have put everything that can be dotted after "data" in parenthesis)
org.jfree.chart.data (category, contour, function, gantt, general, jdbc, statistics, time, xml, xy)

Pie Chart can be generated using data which can be cast to the PieDataset interface and the same chart can be displayed with a 3D effect.

Data which confirms to the CategoryDatset interface can be displayed as Bar Chart and/or Line Chart

Similarly, data that confirms to the XYDataset interface can be used to generate a range of chart types. By default lines are drawn between datasets. So one can give just the X, Y data points and the interface will draw the line to connect them by default. Extentions of XYDataset such as HighLowDataset and IntervalXYDataset can be used to high-low-open-close data and histograms respectively.

Area Charts and Stacked Area Charts can be generated using data of CategoryDataset and XYDataset interface types. The list of kids of Charts that can be generated using JFreeCharts goes on and on, you name it.

There are three clear-cut steps that goes into getting data, presenting data and displaying the data into diagrams, the steps are as follows:

The steps:

1. Create the appropriate dataset using the data in hand(technically in the tables of your database system)

2. "Presenting the Data" created(or cast) in step 1. Involves creating a JFreeChart object which will draw the chart, eg. ChartFactory can draw the data in step 1.

3. The final step is "Displaying Chart" for eg. displaying the chart in a frame on the screen.


// Step 1 (creating the dataset, in other terms casting your data into a JFreeChart Dataset type)
DefaultPieDataset dataset = new DefaultPieDataset();
dataset.setValue("Amar" , 30.4);
dataset.setValue("Akbar" , 19.6);
dataset.setValue("Anthony" , 85.5);

//Step 2 (creating the chart)
JFreeChart chart = ChartFactory.createPieChart("The Chart", dataset, true, true, false);//starting from the frist boolean: legend, tooltips, urls

//Step 3 (creating and displaying a frame)
ChartFrame frame = new ChartFrame("Example", chart);
frame.pack();
frame.setVisible(true);



Once a chart object is created in step 2, a plethora of further customization eg. setting background color, getting the plot object fromt he chart object for further customization and in-turn a "renderer" object can be obtained from the the plot object to customize colors and other like attributes.

Please copy and paste the following for a google search box and click "Google Search" button, to move onto the second of my article on TimeSeriesCharts and how I used it. The text to search for in google is:

Free JFreeCharts Guide, JFreeCharts developer guide, TimeSeries, XYDataSet, Pie Chart, Bar Chart, JFreeCharts API, Premium JFreeCharts

Free Premium JFreeCharts Info.

I had to use JFreeCharts all of a sudden, kind of in a rush. I had no previous information about it until I could get hold of a free JFreeCharts Developer Guide, I am lucky that I could use it since my company paid for it.

After accomplishing a few tasks using JFreeCharts, I wanted to summarize what I discovered about JFreeCharts. Well, without any further due I am going to get right into it:
To start with, it is an API to give a "face" to your data, so in simpler terms JFreeCharts helps you turn numbers into diagrams and the output diagrams can be be piped into as a PDF(using iText) or SVG(using batik) file. It fits well in a situation when you as a developer have to convey the meaning of the data in the database to a separate team like business or maybe the architecture team.

We have a tool that we developed in-hosue, the tool basically saves time since it makes querying the database a lot easier. There are tables in the database that tell how many times queries were fired and how many people were accessing the database and doing the four holy things that we always do with the database(add, edit, get, delete). Now, using the JFreeCharts methods I could give a meaningful representation to the logs in these tables, in terms of Pie Charts, Bar Charts, Line Charts, Scatter Plots, Time Series Charts etc.

I will get into details of my accomplishments with JFreeCharts but before thast just for a simple overview, the following is a list of packages into which all of the class libraries are bundled, for a resonoably advanced reader, the hierarchial names should give an initial insight into what can be accomplished with the classes and inturn the methods inside them.

(for brevity I have put everything that can be dotted in the parenthesis)
org.jfree.chart (annotations, axis, block, entity, event, imagemap, labels, needle, plot, renderer, renderer.category, renderer.xy, servlet, title, ui, urls,

(for brevity I have put everything that can be dotted after "data" in parenthesis)
org.jfree.chart.data (category, contour, function, gantt, general, jdbc, statistics, time, xml, xy)

Pie Chart can be generated using data which can be cast to the PieDataset interface and the same chart can be displayed with a 3D effect.

Data which confirms to the CategoryDatset interface can be displayed as Bar Chart and/or Line Chart

Similarly, data that confirms to the XYDataset interface can be used to generate a range of chart types. By default lines are drawn between datasets. So one can give just the X, Y data points and the interface will draw the line to connect them by default. Extentions of XYDataset such as HighLowDataset and IntervalXYDataset can be used to high-low-open-close data and histograms respectively.

Area Charts and Stacked Area Charts can be generated using data of CategoryDataset and XYDataset interface types. The list of kids of Charts that can be generated using JFreeCharts goes on and on, you name it.

There are three clear-cut steps that goes into getting data, presenting data and displaying the data into diagrams, the steps are as follows:

The steps:

1. Create the appropriate dataset using the data in hand(technically in the tables of your database system)

2. "Presenting the Data" created(or cast) in step 1. Involves creating a JFreeChart object which will draw the chart, eg. ChartFactory can draw the data in step 1.

3. The final step is "Displaying Chart" for eg. displaying the chart in a frame on the screen.


// Step 1 (creating the dataset, in other terms casting your data into a JFreeChart Dataset type)
DefaultPieDataset dataset = new DefaultPieDataset();
dataset.setValue("Amar" , 30.4);
dataset.setValue("Akbar" , 19.6);
dataset.setValue("Anthony" , 85.5);

//Step 2 (creating the chart)
JFreeChart chart = ChartFactory.createPieChart("The Chart", dataset, true, true, false);//starting from the frist boolean: legend, tooltips, urls

//Step 3 (creating and displaying a frame)
ChartFrame frame = new ChartFrame("Example", chart);
frame.pack();
frame.setVisible(true);




Once a chart object is created in step 2, a plethora of further customization eg. setting background color, getting the plot object fromt he chart object for further customization and in-turn a "renderer" object can be obtained from the the plot object to customize colors and other like attributes.

Thanks for reading and Thanks for stopping by!!

~Nirmal

Keep your friends close and your enemies closer.
Sun-Tzu

Wednesday, December 17, 2008

Most Used Eclipse Shortcuts

This list is I believe (becoz i use : ) ), the most used eclipse shortcuts, be it myEclipse, IRAD's eclipse, CFEclipse or any other flavor of eclipse.

These are mostly the ones you use to edit text in the editor and also has the most important ones for searching.

I am sure at least 3 to 4 shortcuts here will be new for every avid shortcut users.

ctrl + shift + t
search for (java) types
you can enter only the uppercase letters of your wanted class or interface. eclipse will bring only such types to the top which contains these uppercase letters inside their names.
i.e. entering BAD finds BaseAccountData or BindAccountDAO etc

ctrl + shift + r
searches for any resources .
the same is true for search with uppercase letters as mentioned above. beside types, eclipse will list any other resources, i.e. jsp, xml, properties, ...

ctrl + o
searches for a method inside a type. let you jump quickly to the beginning of a method.

F3
opens the declaration of a type. let you jump quickly from a type to another type. just place the cursor to the declared type you want to jump to and hit F3. you can alternatively push ctrl and click onto the type you want to open.

alt + arrow left / rigth
lets you jump right back (and forth) to the location (i.e. type declaration) you came from.

ctrl + t
shows the type hierarchy of a type. just place the cursor to the declared type with the wanted hierarchy and hit ctrl + t. now you can scroll through the hierarchy (arrow up / down) and open the desired supertype or subtype (by hitting enter).

ctrl + shift + g
searches for all references of a type or method. just place the cursor the the declaration of the type or method and hit ctrl + shift + g. now you have an overview of all types in workspace which references your class / method.


Ctrl+(shift+)k
-> Searching forward (backward) for the last highlighted text

Ctrl+. -> Go to the next warning / error
Ctrl+, -> Go to the previous warning / error
* works in Javaperspective, not e.g. in phpeclipse

Ctrl+shift+l -> List of many available Shortcuts


Alt + Shift + J, release then press X
runs the program

Ctrl + NumPad - or +
to collapse/uncollapse

Ctrl + NumPad * (multiply key)
To expand all

Ctrl + NumPad / (divide key)
to collapse all

Alt+Shift+Q, B
Show all breakpoints

Alt+Shift+Q, H
Cheat sheets

Alt+Shift+Q, C
Show console

Ctrl+Shift+X
To upper case

Ctrl+Shift+Y
To lower case

Ctrl+Shift+Up
Go to previous member

Ctrl+Shift+Down
Go to next member

Ctrl+Shift+P
Go to matching bracket

Ctrl+Alt+H
Open call hierarchy

Alt + Shift + S
source quick menu

Ctrl + Shift + \ or / or C
comment uncomment block

Ctrl + /
toggle selection comment


Ctrl + L
Shift left

Ctrl + 3
Pretty much lets you search anything and everything

Ctrl + E
Same as ctrl + F6

Saturday, September 13, 2008

Digit to Two Letter Word Converter Utility

/*
* A utility for displaying combinations of letter groups, two at a time.
* The user will enter digits (0-9) on a cell-phone numeric pad, letter groups
* for each digits(eg. "ABC", "WXYX" etc are stored in a map using the letter
* key for each. Keys entered at command line by user, are mapped to their
* corresponding values("letter groups") and are retrieved and saved into
* an String array.
*
* The string arry then is passed along with other info to make the combinations.
*
* There is no definate requirement for this utility, so it servs to give a general
* idea of how user input are mapped to values and how they are combined into meaningful
* two-letter words.
*
* Please feel free to call if you need to.
*
* Assumptions: 1.Combination of two letters are to be displayed
* 2. The order of letter-group to be used for first letter doesn't matter.
* eg. if "ABC" "DEF" are entered this utility could either print:
* AD, AE, AF, BD, BE, BF, CD, CE, CF
* or
* DA, DB, DC, EA, EB, EC, FA, FB, FC
*
*
* Author Date Category
* Nirmal Singh Sep. 13th 2008 General/Utilities
*
*
* note: I can produce a more refined version, depending on input/comments in case
* somebody needs this utility for ceartain use.
*
*
*/

package mine_code;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class TwoLetterCombination
{
public static void main(String[] args)
{

getCommandLineArgsProcess(args);
}

private static void getCommandLineArgsProcess(String[] privateArgs)
{
System.out.println("Please enter digits 0-9 and ");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String s = null;

try
{
s = in.readLine();
String[] strKeys = new String[s.length()];
int[] intKeys = new int[s.length()];

for(int b=0;b {
strKeys[b] = String.valueOf(s.charAt(b));
intKeys[b] = Integer.valueOf(strKeys[b]);
}

callToCopy(strKeys,intKeys, s);
}

catch (IOException e)
{
e.printStackTrace();
}
//System.out.println("Digits entered are: " + s);
}

public static void callToCopy(String[] strArr, int[] intArr, String s)
{
String[] targetArr = new String[strArr.length];
Map myHash = new HashMap();
for(int g=0;g {
targetArr[g] = strArr[g];

switch (intArr[g])
{
case 0: myHash.put(0, " ");break;
case 1: myHash.put(1, " "); break;
case 2: myHash.put(2, "ABC"); break;
case 3: myHash.put(3, "DEF"); break;
case 4: myHash.put(4, "GHI"); break;
case 5: myHash.put(5, "JKL"); break;
case 6: myHash.put(6, "MNO"); break;
case 7: myHash.put(7, "PQRS"); break;
case 8: myHash.put(8, "TUV"); break;
case 9: myHash.put(9, "WXYZ"); break;
}
}
printCombinations(myHash, s);
}

public static void printCombinations(Map myHash, String s)
{
Iterator it = (myHash.keySet()).iterator();
String[] values = new String[myHash.size()];
int arrSize=0;
System.out.println("Digits entered are: " + s);
System.out.println("The following are digits entered and their corresponding letter"+
"groups: ");
System.out.println();

while(it.hasNext())
{
int key = (Integer)it.next();
values[arrSize] = myHash.get(key).toString();
System.out.println(key + " " + values[arrSize]);
arrSize++;
}

int sizeOfArr =arrSize;
System.out.println();
System.out.println("The following are combinations of the letters: ");
System.out.println("Three blank spaces are stored for each 1 and 0 digits "+'\n'+
"and I am displaying the spaces along with the corresponding "+'\n'+
"letters as part of combination. ");
System.out.println();
for(int m=0; m {
for( int k=0;k {
if(m+1 {
for( int j=0;j {
String tempStr;
char firstChar, secondChar;
firstChar = values[m].charAt(k);
secondChar = values[m+1].charAt(j);
tempStr = firstChar+""+secondChar+"";
System.out.println(tempStr);
}
}
}
}
}
}