Menu

Tuesday, December 20, 2011

Send mail From Java using Gmail Server as a SMTP server

package com.mail;

import javax.mail.Authenticator;

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;

public class ApacheHtmlEmail {
    public static void main (String[] args) {
        System.out.println("starts");
        
        String userName = "YourGmailAccount@gmail.com";
        String password = "YourGmailAccountPassword";
        
        HtmlEmail email = new HtmlEmail();
        email.setHostName("smtp.gmail.com");        
        email.setSmtpPort(587);
        email.setTLS(true);
                
        Authenticator authenticator = new DefaultAuthenticator(userName, password);
        email.setAuthenticator(authenticator);
        
        try {
            email.setFrom("YourGmailAccount@gmail.com");
            email.addTo("ToAddress@AnyProvider");
            email.setSubject("Subject");
            email.setTextMsg("Body of the message");
            email.send();
        } catch (EmailException e) {
            e.printStackTrace();
        }
        
        System.out.println("Ends");
    }
}

Tuesday, November 29, 2011

Install LDAP on Linux system using yum



How to install Open LDAP on Linux System?
# yum search openldap-server

The above command will list all the packages that are matched with the “openldap-server”. The version of the package is based on the Linux version installed on the system. 



yum install openldap-servers.i386

The above command will install the LDAP server and its dependencies.




How to start the LDAP server?
Here is the 3 ways to start the LDAP server.
# service ldap start
# /etc/init.d/ldap start
# /sbin/service ldap stop




How to stop the LDAP server?  
Here is the 3 ways to stop the LDAP server.
# service ldap stop  
# /etc/init.d/ldap stop   
# /sbin/service/ldap stop



How to check LDAP server is running on the Linux system?
Here is the 3 ways to check the status of the LDAP server.
# service ldap status  
# /etc/init.d/ldap status   
# /sbin/service/ldap status




What is the default port for the LDAP server?
The default port over TCP is 389. LDAP over SSL is 636.




How to change the default port of the LDAP Server on Linux System?




How to uninstall the LDAP from the Linux system?
yum remove openldap-servers.XXXX  (where XXXX is the version of the LDAP package)
Example: # yum remove openldap-servers.i386

Monday, November 28, 2011

Installing SMTP server - Sendmail on Linux


Simple Mail Transfer Protocol is an international standard to send mails between servers using Internet Protocol (IP). 

“sendmail” is an application on the Linux system which uses SMTP to send mails.

How to install SMTP on Linux?
# yum install sendmail

How to start the SMTP service on Linux?
# service sendmail start    OR /etc/init.d/sendmail start

How to stop the SMTP service on Linux?
# service sendmail stop     OR /etc/init.d/sendmail stop

How to check the status of the SMTP service on Linux?
# service sendmail status   OR /etc/init.d/sendmail status

What is the default port for the SMTP server?
25


How to check the SMTP port is listening or not on Linux?
netstat –nat | grep 25



Linux Tool for system configuration and administration



Here is some important Graphical User Interface and Text Based interface tool on Linux.

# setup
Authentication Configuration
# authconfig-tui

Keyboard Configuration
# system-config-keyboard

Firewall Configuration
# system-config-securitylevel
# system-config-securitylevel-tui

Network Configuration
# system-control-network
# system-config-network-tui

System Services
# system-config-services


Timezone Configuration
# system-config-time

X Configuration
# system-config-display

Sunday, November 27, 2011

Understanding Linux Directory Structure



/bin - It contains all the command line programs that are accessible to the users.  For example ln, mkdir, mount, ping, sync and etc...



/boot - All the files (Like kernel…) which are required to boot up the system are here. 


/devIn Linux, all the devices that are connected to the system will be treated like a directory/file. These virtual directories will be here. For example,  floppy, hard Drive, ram, audio and cdrom.


/etcThe configuration files for the operating system will be here. These are just a text files which can be edited by the user to change the configuration. Binaries files shouldn’t be kept here. For example,  hosts, httpd, cron, passwd and etc…


/homeThe default home directory for a non-root user will be here when a new user is added.  For example, if /home/username, /home/akila


/libShared libraries and kernel modules will be here. These files will be represented by ‘.so’.
It is similar to “DLL” in windows operating system


/lost+foundIf the Linux system is crashed, it will keep the files that it restores.

/media This is the place for mounting removable disks like Floppy, CD-ROM…

/misc This directory is for miscellaneous purposes.

/mntIn Linux everything will be considered a directory/file. To access the external devices, it should be attached to any of the directory in the file system. This is called mounting. The mount points for the each external device will be here.

/net – It is mount point for entire remote file systems.

/opt – The third party software will be stored here.

/proc – It is a virtual directory (doesn’t exist physically) like /dev, contains the process related information. The systems hardware information can be stored here. For example, zoneinfo, meminfo and etc…

 
/root – It is a default home directory for the root user.


/sbin System administrators programs are stored here.


/srv – It contains site-specific data which is served by this system.

/sys – It is similar to /proc. It contains information about the devices that are connected to the system. It is a kernel file system.


/tmp – A directory to keep temporary files used by the programs.

/usr – All user-related programs, libraries and documentations will be stored here.


/var – This directory contains variable data that keeps on changing. For example, logs, mail ..


Wednesday, November 9, 2011

My SQL - Database related commands

  • 1. How to create database?
    • # CREATE DATABASE database_name;
    • Ex: CREATE DATABASE employee;
  • 2. How to give permissions to a user to access the database?
    • # GRANT ALL PRIVILEGES ON database_name.* TO username@server IDENTIFIED BY 'password'
    • Example: # GRANT ALL PRIVILEGES ON database TO 'akila'@'localhost' IDENTIFIED BY 'akila';
  • 3. How to delete a database?
    • #DROP DATABASE database_name;
    • Ex: #DROP DATABASE test;

Wednesday, November 2, 2011

Inject properties file into Bean using spring framework

Step 1: Download the latest spring framework from the official site http://www.springsource.org/download and extract the distribution. The necessary jar files for this example is.

org.springframework.asm-3.1.0.RC1.jar
org.springframework.beans-3.1.0.RC1.jar
org.springframework.context-3.1.0.RC1.jar
org.springframework.core-3.1.0.RC1.jar
org.springframework.expression-3.1.0.RC1.jar
commons-logging-1.1.1.jar

Note: The spring framework jar files will be in spring-framework-distribution/dist folder

Step 2: Create a Java Project named “SimpleSpring”.

File --> New --> Java Project 
    Create config folder to keep all the spring configuration related xml files.
    Create lib folder to keep all the necessary jar files.
    Create src/main folder to keep the java files.
    Create src/resources folder to keep resources related files.

Add these folders and the jar files in the project’s classpath.
To do this, just right click on the project --> Properties --> Java Build Path



   The final Structure of the project is like this.

Step 3: Create default.properties file under the resources folder and add the following. These values will be injected into Bean using Spring Framework.
      username=testuser
      password=testpasswd

Step 4: Create spring-config.xml in the config folder and the following.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
  xmlns:util="http://www.springframework.org/schema/util"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
                           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
  
  <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
      <property name="locations">
        <list>
          <value>classpath:default.properties</value>          
        </list>
      </property>
    <property name="ignoreUnresolvablePlaceholders" value="true"/>
  </bean>
  
  <!-- Inject the properties of default.properties file into appConfig instance -->
  <bean id="appConfig" class="ae.gov.dmi.polopoly.AppConfig">
   <property name="userName" value="${username}"></property>
   <property name="password" value="${password}"></property>
  </bean>  
</beans>


The Spring Framework reads information from the default.properties file and inject into the appConfig instance.

Step 5: Create AppConfig java file
package com.spring.example;

public class AppConfig {
 private String userName;
 private String password;
 
 public String getUserName() {
  return userName;
 }
 
 public void setUserName(String userName) {
  this.userName = userName;
 }
 
 public String getPassword() {
  return password;
 }
 
 public void setPassword(String password) {
  this.password = password;
 } 
} 

Step 6: Create Main class and add the following
package com.spring.example;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
 
 private static final Logger logger = Logger.getLogger(Main.class);
 
 public static void main (String[] args){
  
  logger.info("Starts");
  ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
  
  AppConfig appConfig = (AppConfig) context.getBean("appConfig");
  
  System.out.println(appConfig.getUserName());
  logger.info("Ends");
 }
}


Step 7: Run the Main class. This program outputs the username which is configured in the default.properties.

Wednesday, October 19, 2011

Hibernate with Annotations


In this tutorial, Java Annotation is used to simplify the mapping configuration. This program is same as this example except some small change in the Persistence class and the "hibernate.cfg.xml".


Step 1: Download the latest version of the Hibernate from the official site. http://www.hibernate.org/ and extract the distribution to desired folder. 

Step 2:  
This example program requires the below jar files. These files are in the Hibernate distribution that you have downloaded.

       hibernate-distribution-3.6.7.Final\lib\required\antlr-2.7.6.jar
       hibernate-distribution-3.6.7.Final\lib\required\commons-collections-3.1.jar
       hibernate-distribution-3.6.7.Final\lib\required\dom4j-1.6.1.jar
       hibernate-distribution-3.6.7.Final\lib\required\javassist-3.12.0.GA.jar
       hibernate-distribution-3.6.7.Final\lib\required\jta-1.1.jar
       hibernate-distribution-3.6.7.Final\lib\required\slf4j-api-1.6.1.jar

       hibernate-distribution-3.6.7.Final\lib\jpa\hibernate-jpa-2.0-api-1.0.1.Final.jar

       hibernate-distribution-3.6.7.Final\hibernate3.jar

       Download the latest version of the MySQL connector jar file from http://dev.mysql.com/downloads/connector/j/        mysql-connector-java-5.0.5-bin.jar

Step 3: Create a My SQL database to connect from the hibernate.

      CREATE DATABASE test;
      USE test;
      CREATE TABLE employee (
               id  INT NOT NULL AUTO_INCREMENT   PRIMARY KEY,
               first_name VARCHAR(25) NOT NULL,
               last_name VARCHAR(25) NOT NULL
      );

Step 4: Create a java project in Eclipse IDE
  1. File ----> New ----> Java Project
  2. Enter project name and click finish.
  3. Create a lib folder under the project and add required jar files for hibernate.
  4. Now add these jar files in the class path to avoid compilation errors. To do this, right click on the project ----> Properties ----> Java Build Path ----> Add Jar ----> Go to lib folder ----> Select all the jar files.
Step 5:  First create a Persistence class. The mapping between the Persistence class and Table has been done using Java Annotation.

package com.hibernate.example;

package com.hibernate.example;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table (name="EMPLOYEE")
public class Employee {
 
 @Id 
 @Column (name="ID")
 private int id;
 
 @Column (name="FIRST_NAME")
 private String firstName;
 
 @Column (name="LAST_NAME")
 private String lastName; 

 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getFirstName() {
  return firstName;
 }
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }
 public String getLastName() {
  return lastName;
 }
 public void setLastName(String lastName) {
  this.lastName = lastName;
 } 
}

Step 6:  Create a folder named "config" to keep all the configuration files in one place.

Create xml file "hibernate.cfg.xml" under the config folder.

Add this config folder in the build path. To do this, Right Click on the project ---> Java Build Path ---> Sources Tab ---> Add Folder ---> Select the config folder.

Now the configuration files have been successfully added on the projects build path.




Step 8:  Edit the hibernate.cfg.xml file and add database connectivity details.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
 <session-factory>
  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>
  <property name="hibernate.connection.username">root</property>
  <property name="hibernate.connection.password">akila</property>
  <property name="hibernate.connection.pool_size">10</property>
  <property name="show_sql">true</property>
  <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="hibernate.hbm2ddl.auto">update</property>
  <!-- Map the class file -->
  <mapping class="com.hibernate.example" />
 </session-factory>
</hibernate-configuration>

Step 9: Create a class to insert a record into the employee table using hibernate.
package com.hibernate.example;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

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

  Session session = null;
  try {
   // Open Session
   SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
   session = sessionFactory.openSession();
   // Start Transaction
   Transaction tx = session.beginTransaction();

   System.out.println("Insert");

   Employee employee = new Employee();
   employee.setId(1);
   employee.setFirstName("Akila");
   employee.setLastName("Rajendran");
   
   //Save the session
   session.save(employee);
   tx.commit();

   System.out.println("Done");
  } catch (Exception e) {
   System.out.println(e.getMessage());
  } finally {
   session.flush();
   session.close();
  }
 }
}

Step 10: Run the project and check the database.


You might also like this:
  1. Hibernate simple example

Tuesday, October 18, 2011

Hibernate simple program

Step 1: Download the latest version of the Hibernate from the official site. http://www.hibernate.org/ and extract the distribution to desired folder. 

Step 2: 
This example program requires the below jar files. These files are in the Hibernate distribution that you have downloaded.

       hibernate-distribution-3.6.7.Final\lib\required\antlr-2.7.6.jar
       hibernate-distribution-3.6.7.Final\lib\required\commons-collections-3.1.jar
       hibernate-distribution-3.6.7.Final\lib\required\dom4j-1.6.1.jar
       hibernate-distribution-3.6.7.Final\lib\required\javassist-3.12.0.GA.jar
       hibernate-distribution-3.6.7.Final\lib\required\jta-1.1.jar
       hibernate-distribution-3.6.7.Final\lib\required\slf4j-api-1.6.1.jar

       hibernate-distribution-3.6.7.Final\lib\jpa\hibernate-jpa-2.0-api-1.0.1.Final.jar      
      
       hibernate-distribution-3.6.7.Final\hibernate3.jar
    
       Download the latest version of the MySQL connector jar file from http://dev.mysql.com/downloads/connector/j/        mysql-connector-java-5.0.5-bin.jar

Step 3: Create a My SQL database to connect from the hibernate.

      CREATE DATABASE test;
      USE test;
      CREATE TABLE employee (
               id  INT NOT NULL AUTO_INCREMENT   PRIMARY KEY,
               first_name VARCHAR(25) NOT NULL,
               last_name VARCHAR(25) NOT NULL
      );

Step 4: Create a java project in Eclipse IDE
  1. File ----> New ----> Java Project
  2. Enter project name and click finish.
  3. Create a lib folder under the project and add required jar files for hibernate.
  4. Now add these jar files in the class path to avoid compilation errors. To do this, right click on the project ----> Properties ----> Java Build Path ----> Add Jar ----> Go to lib folder ----> Select all the jar files.
Step 5:  First create a Persistence class.
package com.hibernate.example;

public class Employee { 
 private int id; 
 private String firstName; 
 private String lastName; 

 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getFirstName() {
  return firstName;
 }
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }
 public String getLastName() {
  return lastName;
 }
 public void setLastName(String lastName) {
  this.lastName = lastName;
 } 
}

Step 6:  Create a folder named as "config" to keep all the configuration files in one place.

Create xml files "employee.hbm.xml" and "hibernate.cfg.xml" under the config folder.

Add this config folder in the build path. To do this, Right Click on the project ---> Java Build Path ---> Sources Tab ---> Add Folder ---> Select the config folder.

Now the configuration files have been successfully added on the projects build path. 


Step 7: Map the Employee Persistence class to the Employee table in hibernate mapping file (employee.hbm.xml).
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
 <class name="com.hibernate.example.Employee" table="Employee">
  <id name="id" type="int" column="id">
   <generator class="increment"></generator>
  </id>

  <property name="firstName">
   <column name="first_name" />
  </property>
  <property name="lastName">
   <column name="last_name" />
  </property>
 </class>
</hibernate-mapping>

Step 8:  Create hibernate configuration file where we have to enter all the necessary information to connect to the data base. The configuration file should be named as "hibernate.cfg.xml".
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
 <session-factory>
  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>
  <property name="hibernate.connection.username">root</property>
  <property name="hibernate.connection.password">akila</property>
  <property name="hibernate.connection.pool_size">10</property>
  <property name="show_sql">true</property>
  <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="hibernate.hbm2ddl.auto">update</property>
  <!-- Mapping files -->
  <mapping resource="employee.hbm.xml" />
 </session-factory>
</hibernate-configuration>

Step 9: Create a class to insert a record into the employee table using hibernate.
package com.hibernate.example;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

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

  Session session = null;
  try {
   // Open Session
   SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
   session = sessionFactory.openSession();
   // Start Transaction
   Transaction tx = session.beginTransaction();

   System.out.println("Insert");

   Employee employee = new Employee();
   employee.setId(1);
   employee.setFirstName("Akila");
   employee.setLastName("Rajendran");
   
   //Save the session
   session.save(employee);
   tx.commit();

   System.out.println("Done");
  } catch (Exception e) {
   System.out.println(e.getMessage());
  } finally {
   session.flush();
   session.close();
  }
 }
}

Step 10: Run the project and check the database.


You may also like this:

  1. Hibernate with Annotations


Wednesday, August 17, 2011

Submit Blog in Yahoo


This tutorial explains on how to submit your site and its feed in Yahoo.

Step 1: Login to https://siteexplorer.search.yahoo.com/ using your yahoo id. If you don’t have, create it.

Step 2: Enter your site and then Click Add My Site.


Step 3: There are two ways to verify your site. The simplest way is to add the Meta tag generated for you in your blog under the head tag. And then click the Read to Authenticate.


Step 4: After the site has been verified, go to the site that you added and then click the Feeds link. Enter the sitemap xml and click Add Feed.

Submit Blog Sitemap in Bing


Step 1: Login to http://www.bing.com/toolbox/webmaster/ . If you don’t have id, create it.  Click on the “Add Site” button which is on the homepage of the webmaster. Enter your site URL in the pop up and then click submit.

Step 2: To verify the ownership of the site, just copy the Meta tag which is given in the “Option 2”. Go to your blog and Edit the html and paste it under the head tag. Once you added the Meta tag, click Verify.
This will take some time to crawl your site.




Step 4: once you successfully added your site, go to Crawl tab and then click Add Feed which will pop up a window. Enter your sitemap xml URL and submit it.
That’s all. You have successfully submitted your blog sitemap in Bing.



Submit Blog in Google


This tutorial explains on how to submit your blog and its feed in Google.


Step 1: Log into Google webmaster with your Google account. If you don’t have Google account, create it. https://www.google.com/webmasters/tools/

Step 2: Click on the Add a site button and then add your site.


Step 3: Verify the ownership of your blog by following any one the method explained. Simple way is to copy paste the Meta tag on your blog.  Once you added the Meta tag, click on the verify button.



Step 4:  After your site has been verified, click on the Sitemaps link under the Site configuration.  Click on the Submit a Sitemap button and then add your sitemap URL.

That’s all. You have successfully added your sitemap. Wait for Google webmaster to crawl your website.


Related Articles:

Submit Blog in Ask.com

Tuesday, August 16, 2011

Submit Blog in Technorati

This tutorial explains on how to submit your blog in the Technorati Site.

My Technorati claim token: U8YUHZB4P55Y

Step 1: Log into http://technorati.com/. If you haven’t an account, create it.

Step 2: Go to your account http://technorati.com/account. At the bottom of the page, you can find a section to add your blog. Enter your blog URL and click Claim.


Step 3: Enter all the necessary information to claim the blog and click “Proceed to next step” which will be at the bottom of the page.



Step 4: The Technorati will send you mail about the claim Token. Create a post on your blog and add this token in the body of the post.  Once you complete this, go to your Technorati account, and click the “Check Claim” button.

That’s all. You have successfully submitted your blog in Technorati.