<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:blogger='http://schemas.google.com/blogger/2008' xmlns:georss='http://www.georss.org/georss' xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-1889673847048308806</id><updated>2024-11-08T07:41:05.490-08:00</updated><category term="Groovy &amp; Grails"/><category term="Core Java"/><category term="Advanced Java"/><category term="Hosting"/><category term="JDBC"/><category term="Java Script"/><category term="Spock"/><category term="angular2"/><category term="ionic2"/><title type='text'>Jagadeesh Manne</title><subtitle type='html'></subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://jagadeeshmanne.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default'/><link rel='alternate' type='text/html' href='http://jagadeeshmanne.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/09122533940640970927</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>19</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-1889673847048308806.post-6346653757948506795</id><published>2017-08-17T21:55:00.001-07:00</published><updated>2017-08-17T21:57:06.272-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="angular2"/><category scheme="http://www.blogger.com/atom/ns#" term="ionic2"/><title type='text'>ionic 2 angular maxlength issue in android devices</title><content type='html'>In Ionic 2, the maxlength property is working as expected in ios devices and on some android devices. But it doesn&#39;t work if the device is using native keyboard. 
This is the custom directive to make it work in all the devices. In ios, it uses the native maxlength property and in android, it uses custom maxlength property. 
&lt;br/&gt;&lt;br/&gt;
&lt;pre class=&quot;brush:javascript&quot;&gt;
import { Directive, EventEmitter, HostListener, Input, Output } from &#39;@angular/core&#39;;
import { Platform } from &quot;ionic-angular&quot;;

@Directive({
    selector: &#39;[cMaxLength]&#39;
})
export class MaxLengthDirective {

  @Input(&#39;cMaxLength&#39;) cMaxLength:any;
  @Output() ngModelChange:EventEmitter&lt;any&gt; = new EventEmitter();

  constructor(public platform: Platform) {
  }

  //keypress event doesn&#39;t work in ionic android. the keydown event will work but the value doesn&#39;t effect until this event has finished. hence using keyup event. 
  @HostListener(&#39;keyup&#39;,[&#39;$event&#39;]) onKeyup(event) {
    const element = event.target as HTMLInputElement;
    const limit = this.cMaxLength;
    if (this.platform.is(&#39;android&#39;)) {
      const value = element.value.substr(0, limit);
      if (value.length &lt;= limit) {
        element.value = value;
      } else {
        element.value = value.substr(0, limit-1);
      }
      this.ngModelChange.emit(element.value);
    }
  }

  @HostListener(&#39;focus&#39;,[&#39;$event&#39;]) onFocus(event) {
    const element = event.target as HTMLInputElement;
    if (!this.platform.is(&#39;android&#39;)) {
      element.setAttribute(&#39;maxlength&#39;, this.cMaxLength)
    }
  }
}
&lt;/pre&gt;
&lt;br/&gt;
&lt;br/&gt;
&lt;b&gt;Usage:&lt;/b&gt;

Include the above directive in shared module to make use of this in entire application.

&lt;pre class=&quot;brush:javascript&quot;&gt;
 &lt;ion-input type=&quot;text&quot; [(ngModel)]=&quot;name&quot; cMaxLength=&quot;20&quot;&gt;&lt;/ion-input&gt;
&lt;/pre&gt;

&lt;br/&gt;
&lt;br/&gt;</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/6346653757948506795'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/6346653757948506795'/><link rel='alternate' type='text/html' href='http://jagadeeshmanne.blogspot.com/2017/08/ionic-2-angular-maxlength-issue-in.html' title='ionic 2 angular maxlength issue in android devices'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/09122533940640970927</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author></entry><entry><id>tag:blogger.com,1999:blog-1889673847048308806.post-2050720297007728726</id><published>2016-11-06T23:49:00.000-08:00</published><updated>2016-11-06T23:49:25.217-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Groovy &amp; Grails"/><title type='text'>Creating Simple Audit Log using grails, Spring Security Listeners, Hibernate Listeners </title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;&lt;br /&gt;&lt;br /&gt;
&lt;b&gt;Simple Audit Log using Grails and Hibernate event listeners&lt;/b&gt;
&lt;br /&gt;
&lt;b&gt;Providing following functionality&lt;/b&gt;
1. Loging Insert, Update, Delete of objects
2. Logging Login, Logout events
3. Logging Login Attempt failed event
4. Logging which screen is accessed

&lt;b&gt;1. Create AuditLog domain. &lt;/b&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;
class AuditLog {
    static transient escapeLogAction = true

    User user
    AuditLogType auditLogType // To find which type of action it is. like login, logout, screen access etc
    String value
    Date timeStamp
    String IPAddress
    Date dateCreated
    Date lastUpdated
    AuditLogSource source // To find what is the source of request. like web or system. Some times we run the cron jobs to insert the data. in that case it is &quot;System&quot;

    static constraints = {
        user (nullable: true)
        IPAddress (nullable: true)
        source (nullable: true)
    }
}
&lt;/pre&gt;
&lt;br/&gt;
&lt;b&gt;2. Create AuditLogType enum in src/groovy folder &lt;/b&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;
enum AuditLogType {
    LOG_IN,
    LOG_OUT,
    FAILED_ATTEMPT,
    SCREEN_ACCESS,
    DATA_CHANGE
}
&lt;/pre&gt;
&lt;br/&gt;
&lt;b&gt;4. Create AuditLogSource enum in src/groovy folder &lt;/b&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;
enum AuditLogSource {
   WEB,
   SYSTEM
}
&lt;/pre&gt;
&lt;br/&gt;
&lt;b&gt;3. Create AuditLogListener(src/groovy folder) to log insert/update/delete actions )&lt;/b&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;
import org.hibernate.event.PostDeleteEvent
import org.hibernate.event.PostDeleteEventListener
import org.hibernate.event.PostInsertEvent
import org.hibernate.event.PostInsertEventListener
import org.hibernate.event.PostUpdateEvent
import org.hibernate.event.PostUpdateEventListener
import org.springframework.web.context.request.NativeWebRequest
import org.springframework.web.context.request.RequestAttributes
import org.springframework.web.context.request.RequestContextHolder

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpSession

class AuditLogListener implements PostInsertEventListener, PostUpdateEventListener, PostDeleteEventListener {

    def springSecurityService

    @Override
    void onPostDelete(PostDeleteEvent postDeleteEvent) {
        logAction(postDeleteEvent.entity)
    }

    @Override
    void onPostInsert(PostInsertEvent postInsertEvent) {
        logAction(postInsertEvent.entity)
    }

    @Override
    void onPostUpdate(PostUpdateEvent postUpdateEvent) {
        logAction(postUpdateEvent.entity)
    }

    private void logAction(Object entity) {
 
  //declaring escapeAuditLog = true in a domain will skip the audit log for that domain.
        if (entity.metaClass.hasProperty(entity,&#39;escapeAuditLog&#39;) &amp;&amp; entity.&#39;escapeAuditLog&#39;) {
            return
        }
        HttpServletRequest request = getHttpServletRequest()
        HttpSession session = request?.getSession()
        AuditLog auditLog = new AuditLog()
        auditLog.timeStamp = new Date()
        auditLog.actionType = ActionType.DATA_CHANGE
        auditLog.user = springSecurityService.currentUser
        auditLog.value = entity.getClass().getName()
        auditLog.IPAddress = getRemoteAddress(request)
        auditLog.source = request ? AuditLogSource.WEB : AuditLogSource.SYSTEM
        auditLog.withNewSession {
            auditLog.save(flush: true)
        }
    }

    private HttpServletRequest getHttpServletRequest() {
        RequestAttributes attribs = RequestContextHolder.getRequestAttributes()
        if (attribs instanceof NativeWebRequest) {
            HttpServletRequest request = (HttpServletRequest) ((NativeWebRequest) attribs).getNativeRequest()
            return request
        }
    }
 
 private String getRemoteAddress(HttpServletRequest request) {
        if (!request) return null
        String ipAddress = request.getHeader(&quot;X-Forwarded-For&quot;)  // X-Forwarded-For: clientIpAddress, proxy1, proxy2
        if (!ipAddress) {
            ipAddress = request.remoteAddr
        }
        return ipAddress.split(&quot;,&quot;)[0]
    }
}
&lt;/pre&gt;

&lt;b&gt;5. Create LoggingSecurityEventListener(in src/groovy folder) to log the Login, Logout events &lt;/b&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;
import org.apache.log4j.Logger
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.ApplicationListener
import org.springframework.security.authentication.event.AuthenticationSuccessEvent
import org.springframework.security.core.Authentication
import org.springframework.security.web.authentication.logout.LogoutHandler

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

class LoggingSecurityEventListener implements ApplicationListener&lt;AuthenticationSuccessEvent&gt;, LogoutHandler {
    private static final log = Logger.getLogger(this)
    def userService

    @Autowired
    HttpServletRequest httpServletRequest // Injected and limited to the current thread per usage

    void onApplicationEvent(AuthenticationSuccessEvent event) {
        event.authentication.with {
            def userName = principal.hasProperty(&#39;username&#39;)?.getProperty(principal) ?: principal
            log.info(&quot;Login success from ${getRemoteAddress(httpServletRequest)} using username $userName&quot;)
            logAction(userName, ActionType.LOG_IN, getRemoteAddress(httpServletRequest))
        }
    }

    void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        authentication?.with {
            def username = principal.hasProperty(&#39;username&#39;)?.getProperty(principal) ?: principal
            logAction(username, ActionType.LOG_OUT, getRemoteAddress(request))
        }
    }

    private void logAction(def userName, ActionType actionType, String ipAddress) {
        AuditLog auditLog = new AuditLog()
        auditLog.source = ActionLogSource.WEB
        auditLog.actionType = actionType
        auditLog.value = userName
        auditLog.timeStamp = new Date()
        auditLog.user = User.findByUserName(userName) // modify to get the logged in user
        auditLog.IPAddress = ipAddress
        auditLog.save(flush: true)
    }
 
 private String getRemoteAddress(HttpServletRequest request) {
        if (!request) return null
        String ipAddress = request.getHeader(&quot;X-Forwarded-For&quot;)  // X-Forwarded-For: clientIpAddress, proxy1, proxy2
        if (!ipAddress) {
            ipAddress = request.remoteAddr
        }
        return ipAddress.split(&quot;,&quot;)[0]
    }
}
&lt;/pre&gt;

&lt;b&gt;6. Create LoginFailedAuthEventListener(in src/groovy folder) to log login failed attempts &lt;/b&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;
import org.apache.log4j.Level
import org.apache.log4j.Logger
import org.springframework.context.ApplicationListener
import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent

class LoginFailedAuthEventListener implements ApplicationListener&lt;AbstractAuthenticationFailureEvent&gt; {
    private static final log = Logger.getLogger(this)
    def actionLogService

    void onApplicationEvent(AbstractAuthenticationFailureEvent event) {
        log.setLevel(Level.WARN)
        def userName = event.authentication.principal
        log.warn(&quot;Failed login attempt from $event.source.details.remoteAddress using username $userName&quot;)
        AuditLog auditLog = new AuditLog()
        auditLog.source = ActionLogSource.WEB
        auditLog.actionType = ActionType.FAILED_ATTEMPT
        auditLog.value = userName
        auditLog.timeStamp = new Date()
        auditLog.IPAddress = event.source.details.remoteAddress
        auditLog.save(flush: true)
    }
}
&lt;/pre&gt;

&lt;b&gt;7. Register all these listners in resources.groovy &lt;/b&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;
import AuditLogListener
import LoggingSecurityEventListener
import LoginFailedAuthEventListener
import org.codehaus.groovy.grails.orm.hibernate.HibernateEventListeners

// Place your Spring DSL code here
beans = {
    loginFailedAuthEventListener(LoginFailedAuthEventListener)

    securityEventListener(LoggingSecurityEventListener)

    auditLogListner(AuditLogListener) {
        springSecurityService = ref(&quot;springSecurityService&quot;)
    }

    hibernateEventListeners(HibernateEventListeners) {
          listenerMap = [&#39;post-insert&#39;:auditLogListner,
                         &#39;post-update&#39;:auditLogListner,
                         &#39;post-delete&#39;:auditLogListner]
    }
}

&lt;/pre&gt;

&lt;b&gt;8. Create BaseController(in controllers folder) to log Screen Access and extend this controller from every controller &lt;/b&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;
class BaseController {
    def springSecurityService

    def beforeInterceptor = {
        if (!request.xhr) {
            AuditLog auditLog = new AuditLog()
            auditLog.source = ActionLogSource.WEB
            auditLog.timeStamp = new Date()
            auditLog.actionType = ActionType.SCREEN_ACCESS
            auditLog.user = User.get(springSecurityService.principal.id)
            auditLog.IPAddress = getRemoteAddress(request)
            auditLog.value = actionUri
            auditLog.save(flush: true)
        }
        return true
    }
 
 private String getRemoteAddress(HttpServletRequest request) {
        if (!request) return null
        String ipAddress = request.getHeader(&quot;X-Forwarded-For&quot;)  // X-Forwarded-For: clientIpAddress, proxy1, proxy2
        if (!ipAddress) {
            ipAddress = request.remoteAddr
        }
        return ipAddress.split(&quot;,&quot;)[0]
    }
}
&lt;/pre&gt;

&lt;/div&gt;

</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/2050720297007728726'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/2050720297007728726'/><link rel='alternate' type='text/html' href='http://jagadeeshmanne.blogspot.com/2016/11/creating-simple-audit-log-using-grails.html' title='Creating Simple Audit Log using grails, Spring Security Listeners, Hibernate Listeners '/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/09122533940640970927</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author></entry><entry><id>tag:blogger.com,1999:blog-1889673847048308806.post-4921953553651092246</id><published>2016-06-17T10:53:00.003-07:00</published><updated>2016-06-17T10:55:54.496-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Groovy &amp; Grails"/><title type='text'>Forgot Password, Change Password, Reset Password functionality using grails</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;&lt;br /&gt;&lt;br /&gt;
&lt;b&gt;Forgot Password, Change Password, Reset Password functionality using grails&lt;/b&gt;
&lt;br /&gt;
&lt;b&gt;1. Install grails mail plugin. And configure the mail plugin to email reset password link&lt;/b&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;
compile &quot;org.grails.plugins:mail:1.0.7&quot;
&lt;/pre&gt;
&lt;br/&gt;
&lt;b&gt;2. Create a domain Token.groovy to generate random token to send reset password link to user email
&lt;/b&gt; &lt;br/&gt;
&lt;b&gt;MongoPersistanceListener.groovy&gt;&lt;/b&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;
import java.util.UUID

class Token {
    String email
    String value = UUID.randomUUID().toString().replaceAll(&#39;-&#39;, &#39;&#39;)
    Date dateCreated

    static mapping = {
        version false
    }

    static constraints = {
    }
}
&lt;/pre&gt;
&lt;b&gt;3. Create a UserService.groovy to send send generate token and send email&lt;/b&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;
class UserService {

    def emailService;

 void sendResetPasswordEmail(User user){
        def token = Token.findByEmail(user.email)
        if(!token) {
            token = new Token(email: user.email)
            token.save(flush: true);
        }
        emailService.sendResetPasswordEmail(user, token)
    }

}

&lt;/pre&gt;

&lt;b&gt;3. Create a EmailService.groovy to send email&lt;/b&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;
import grails.plugin.asyncmail.AsynchronousMailService
import grails.plugin.mail.MailService

class EmailService {

    MailService mailService
    def groovyPageRenderer
    def grailsApplication

 /**
  * Sends the email to given email id
  */
    def sendMail(MailDTO mailDTO) {

        log.info &quot;Sending Mail To ==== ${mailDTO?.toMailId}&quot;

        mailService.sendMail {
            async true
            to mailDTO?.toMailId
            subject mailDTO.subject
            html mailDTO.content
        }
    }

 
 /*
     * Sends the reset password email
     */
    def sendResetPasswordEmail(User user, Token token) {
        MailDTO mailDTO = new MailDTO()
        mailDTO.with {
            toMailId = user?.email
            subject = &quot;Password reset on Mobile Career Index&quot;
            content = groovyPageRenderer.render(template: &#39;/mail/resetPassword&#39;, model: [user: user,token:token])
        }
        sendMail(mailDTO)
    }
}
&lt;/pre&gt;

&lt;b&gt;3. Create MailDTO.groovy in src/groovy folder&lt;/b&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;
class MailDTO {
    String toMailId
    List&lt;String&gt; ccMailIds
    String subject
    String content
}
&lt;/pre&gt;

&lt;b&gt;3. Create UserController.groovy&lt;/b&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;

import org.codehaus.groovy.grails.plugins.springsecurity.SpringSecurityUtils
import grails.plugins.springsecurity.Secured
import org.codehaus.groovy.grails.validation.Validateable

class UserController {

    def userService

    def forgotPassword = {

        requireLogout()

        if (request.get) {
            render view: &quot;/user/forgotPassword&quot;
            return;
        }

        String email = params.email
        if (!email) {
            flash.error = message(code: &#39;spring.security.forgotPassword.username.missing&#39;)
            redirect action: &#39;forgotPassword&#39;
            return
        }

        def user = User.findByEmail(email);
        if (!user) {
            flash.error = message(code: &#39;spring.security.forgotPassword.user.notFound&#39;)
            redirect action: &#39;forgotPassword&#39;
            return
        }

        userService.sendResetPasswordEmail(user);
        flash.message = message(code: &#39;spring.security.forgotPassword.sent&#39;)
        render view: &quot;/user/forgotPassword&quot;
    }

 @Secured([&#39;IS_AUTHENTICATED_ANONYMOUSLY&#39;])
    def resetPassword = { ResetPasswordCommand command -&gt;

        requireLogout();
        flash.message = null;
        String tokenValue = params.token

        def token = tokenValue ? Token.findByValue(tokenValue) : null
        if (!token) {
            flash.error = message(code: &#39;spring.security.resetPassword.badCode&#39;)
            redirect controller: &quot;home&quot;
            return
        }

        if (request.get) {
            render view: &quot;/user/resetPassword&quot; , model:[token: token, command: new ResetPasswordCommand()]
            return
        }

        command.email = token.email
        command.validate()

        if (command.hasErrors()) {
            flash.error = message(code: &#39;spring.security.resetPassword.badCode&#39;)
            render view: &quot;/user/resetPassword&quot; , model:[token: token, command: command]
            return
        }

        Token.withTransaction { status -&gt;
            def user = User.findByEmail(token.email);
            user.password = command.password
            user.save(flush: true)
            token.delete(flush: true)  ;
        }

        springSecurityService.reauthenticate token.email

        flash.message = message(code: &#39;spring.security.resetPassword.success&#39;)
        def config = SpringSecurityUtils.securityConfig
        redirect uri: config.successHandler.defaultTargetUrl
        return
    }

    @Secured([&#39;IS_AUTHENTICATED_FULLY&#39;])
    def editPassword = { EditPasswordCommand command -&gt;

        flash.message = null;

        if (request.get) {
            render view: &quot;/user/editPassword&quot; , model:[command: new EditPasswordCommand()]
            return
        }

        command.validate()

        if (command.hasErrors()) {
            render view: &quot;/user/editPassword&quot; , model:[command: command]
            return
        }
        User user = springSecurityService.currentUser;
        String encodedPassword = springSecurityService.encodePassword(command.currentPassword)
        if (encodedPassword != (user.password)) {
            flash.error = message(code: &#39;command.password.error.invalid&#39;)
            render view: &quot;/user/editPassword&quot; , model:[command: new EditPasswordCommand()]
            return;
        }
        user.password = command.password
        user.save(flush: true);

        flash.message = message(code: &#39;spring.security.resetPassword.success&#39;)
        render view: &quot;/user/editPassword&quot; , model:[command: new EditPasswordCommand()]
    }
}

@Validateable
class ResetPasswordCommand {
    String email
    String password
    String password2

    static constraints = {
        email nullable: false, email: true
        password blank: false, nullable: false
        password2 validator: password2Validator
    }

    static final password2Validator = { value, command -&gt;
        if (command.password != command.password2) {
            return &#39;command.password2.error.mismatch&#39;
        }
    }
}

@Validateable
class EditPasswordCommand {

    String currentPassword
    String password
    String password2

    static constraints = {
        currentPassword blank: false, nullable: false
        password blank: false, nullable: false
        password2 validator: password2Validator
    }

    static final password2Validator = { value, command -&gt;
        if (command.password != command.password2) {
            return &#39;command.password2.error.mismatch&#39;
        }
    }
}

&lt;/pre&gt;

&lt;b&gt; I have used parsley.js to validate the forms&lt;/b&gt;

&lt;b&gt;Create forgotPassword.gsp in views/user folder&lt;/b&gt;
&lt;pre class=&quot;brush:html&quot;&gt;
 
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;meta name=&quot;layout&quot; content=&quot;main&quot;&gt;
    &lt;title&gt;Forgot Password&lt;/title&gt;
&lt;/head&gt;

&lt;body&gt;
&lt;div class=&quot;shell&quot;&gt;
    &lt;section&gt;

        &lt;article class=&quot;common-view no-background center-form&quot;&gt;
            &lt;h1 align=&quot;center&quot;&gt;Reset Password&lt;/h1&gt;&lt;br/&gt;
            &lt;h4&gt;&lt;g:message code=&#39;spring.security.forgotPassword.description&#39;/&gt;&lt;/h4&gt;
            &lt;g:form controller=&quot;user&quot; action=&#39;forgotPassword&#39; parsley-validate=&quot;true&quot; class=&quot;forgot-pwd-form custom-form&quot;&gt;
                &lt;br/&gt;
                &lt;span class=&quot;inputwrapper email-icon&quot; style=&quot;padding-bottom:10px&quot;&gt;
                    &lt;g:textField name=&quot;email&quot; id=&quot;email&quot; placeholder=&quot;Enter your email&quot; class=&quot;no-space&quot;
                                     parsley-type=&quot;email&quot; parsley-required=&quot;true&quot; parsley-error-message= &#39;Please enter your email.&#39;/&gt;
                &lt;/span&gt;
                &lt;br/&gt;
                &lt;button type=&quot;submit&quot; id=&quot;forgot-pwd-btn&quot; style=&quot;display: none;&quot;&gt;Submit&lt;/button&gt;
                &lt;a href=&quot;javascript:void(0)&quot; class=&quot;innerbtn&quot;  id=&quot;forgot-btn&quot;&gt;Submit&lt;/a&gt;
            &lt;/g:form&gt;
        &lt;/article&gt;
    &lt;/section&gt;
&lt;/div&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
    jQuery(&#39;#forgot-btn&#39;).live(&#39;click&#39;,function(){
        var isValid = $(&#39;.forgot-pwd-form&#39;).parsley(&#39;validate&#39;);
        if(isValid){
            jQuery(&#39;#forgot-pwd-btn&#39;).click();
        }
    });
    jQuery(&quot;input&quot;).bind(&quot;keydown&quot;, function(event) {
        var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
        if (keycode == 13) {
            jQuery(&#39;#reset-pwd-btn&#39;).click();
            return false;
        } else  {
            return true;
        }
    });
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

&lt;/pre&gt;

&lt;b&gt;Create resetPassword.gsp in views/user folder&lt;/b&gt;
&lt;pre class=&quot;brush:html&quot;&gt;
 
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;meta name=&quot;layout&quot; content=&quot;main&quot;&gt;
    &lt;title&gt;Reset Password&lt;/title&gt;
&lt;/head&gt;

&lt;body&gt;

&lt;div class=&quot;shell&quot;&gt;
    &lt;section&gt;

        &lt;article class=&quot;common-view no-background center-form&quot;&gt;
            &lt;h1 align=&quot;center&quot;&gt;Reset Password&lt;/h1&gt;
            &lt;g:form controller=&quot;user&quot; action=&#39;resetPassword&#39; parsley-validate=&quot;true&quot; class=&quot;reset-pwd-form custom-form&quot;&gt;
                &lt;g:hiddenField name=&#39;token&#39; value=&#39;${token.value}&#39;/&gt;
                &lt;span class=&quot;inputwrapper password-icon&quot; style=&quot;padding-bottom:10px&quot;&gt;
                    &lt;g:passwordField name=&quot;password&quot; id=&quot;password&quot; placeholder=&quot;Password&quot; class=&quot;no-space&quot;
                                     parsley-required=&quot;true&quot; parsley-error-message= &#39;Please enter password.&#39;/&gt;
                &lt;/span&gt;
                &lt;br/&gt;
                &lt;span class=&quot;inputwrapper password-icon&quot; style=&quot;padding-bottom:10px&quot;&gt;
                    &lt;g:passwordField name=&quot;password2&quot; placeholder=&quot;Re-enter Password&quot; class=&quot;no-space&quot;
                                     parsley-equalto=&quot;#password&quot; parsley-required=&quot;true&quot; parsley-error-message= &#39;Please Re-enter password.&#39;/&gt;
                &lt;/span&gt;
                &lt;br/&gt;
                &lt;button type=&quot;submit&quot; id=&quot;reset-pwd-btn&quot; style=&quot;display: none;&quot;&gt;Submit&lt;/button&gt;
                &lt;a href=&quot;javascript:void(0)&quot; class=&quot;innerbtn&quot;
                   onclick=&quot;document.getElementById(&#39;reset-pwd-btn&#39;).click();&quot; id=&quot;reset-btn&quot;&gt;Submit&lt;/a&gt;
            &lt;/g:form&gt;
        &lt;/article&gt;
    &lt;/section&gt;
    &lt;g:render template=&quot;/web/footer&quot;/&gt;
&lt;/div&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
    jQuery(&#39;#reset-btn&#39;).live(&#39;click&#39;,function(){
        var isValid = $(&#39;.reset-pwd-form&#39;).parsley(&#39;validate&#39;);
        if(isValid){
            jQuery(&#39;#reset-pwd-btn&#39;).click();
        }
    });
    jQuery(&quot;input&quot;).bind(&quot;keydown&quot;, function(event) {
        var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
        if (keycode == 13) {
            jQuery(&#39;#reset-pwd-btn&#39;).click();
            return false;
        } else  {
            return true;
        }
    });
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

&lt;/pre&gt;

&lt;b&gt;Create editPassword.gsp in views/user folder&lt;/b&gt;
&lt;pre class=&quot;brush:html&quot;&gt;
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;meta name=&quot;layout&quot; content=&quot;main&quot;&gt;
    &lt;title&gt;Change Password&lt;/title&gt;
&lt;/head&gt;

&lt;body&gt;

&lt;div class=&quot;shell&quot;&gt;
    &lt;section&gt;

        &lt;article class=&quot;common-view no-background center-form&quot;&gt;
            &lt;h1 align=&quot;center&quot;&gt;Change Password&lt;/h1&gt;
            &lt;g:form controller=&quot;account&quot; action=&quot;editPassword&quot; parsley-validate=&quot;true&quot; class=&quot;reset-pwd-form custom-form&quot;&gt;
                &lt;span class=&quot;inputwrapper password-icon&quot; style=&quot;padding-bottom:10px&quot;&gt;
                    &lt;g:passwordField name=&quot;currentPassword&quot;  placeholder=&quot;Current password&quot; class=&quot;no-space&quot;
                                     parsley-required=&quot;true&quot; parsley-error-message= &#39;Please enter current password.&#39;/&gt;
                &lt;/span&gt;  &lt;br/&gt;
                &lt;span class=&quot;inputwrapper password-icon&quot; style=&quot;padding-bottom:10px&quot;&gt;
                        &lt;g:passwordField name=&quot;password&quot;  placeholder=&quot;New password&quot; class=&quot;no-space&quot;  id=&quot;password&quot;
                                     parsley-required=&quot;true&quot; parsley-error-message= &#39;Please enter new password.&#39;/&gt;
                &lt;/span&gt;  &lt;br/&gt;
                &lt;span class=&quot;inputwrapper password-icon&quot; style=&quot;padding-bottom:10px&quot;&gt;
                    &lt;g:passwordField name=&quot;password2&quot;  placeholder=&quot;Re-enter new password&quot; class=&quot;no-space&quot;
                                     parsley-equalto=&quot;#password&quot;   parsley-required=&quot;true&quot; parsley-error-message= &#39;Please Re-enter new password.&#39;/&gt;
                &lt;/span&gt;  &lt;br/&gt;

                &lt;button type=&quot;submit&quot; id=&quot;reset-pwd-btn&quot; style=&quot;display: none;&quot;&gt;Submit&lt;/button&gt;
                &lt;g:link controller=&quot;dashBoard&quot;action=&quot;reports&quot; class=&quot;cancel-btn&quot;&gt;Cancel&lt;/g:link&gt;
                &lt;a href=&quot;javascript:void(0)&quot; class=&quot;innerbtn&quot; id=&quot;reset-btn&quot; style=&quot;margin-left: -130px;top: 8px;&quot;&gt;Update&lt;/a&gt;
            &lt;/g:form&gt;
        &lt;/article&gt;
    &lt;/section&gt;
&lt;/div&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
    jQuery(&#39;#reset-btn&#39;).live(&#39;click&#39;,function(){
        var isValid = $(&#39;.reset-pwd-form&#39;).parsley(&#39;validate&#39;);
        if(isValid){
            jQuery(&#39;#reset-pwd-btn&#39;).click();
        }
    });
    jQuery(&quot;input&quot;).bind(&quot;keydown&quot;, function(event) {
        var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
        if (keycode == 13) {
            jQuery(&#39;#reset-pwd-btn&#39;).click();
            return false;
        } else  {
            return true;
        }
    });
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;


&lt;/pre&gt;
&lt;/div&gt;
</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/4921953553651092246'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/4921953553651092246'/><link rel='alternate' type='text/html' href='http://jagadeeshmanne.blogspot.com/2016/06/forgot-password-change-password-reset.html' title='Forgot Password, Change Password, Reset Password functionality using grails'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/09122533940640970927</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author></entry><entry><id>tag:blogger.com,1999:blog-1889673847048308806.post-6574304738817958615</id><published>2016-06-13T11:03:00.000-07:00</published><updated>2016-06-13T11:03:03.680-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Groovy &amp; Grails"/><title type='text'>Custom Persistence Listener in Mongodb Grails plugin</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;&lt;br /&gt;&lt;br /&gt;
&lt;b&gt;Mongodb grails persistance listeners to assign default properties&lt;/b&gt;
&lt;br /&gt;
Mongodb doesn&#39;t support extending the base class to assign values to common properties like updatedOn, createdOn etc. &lt;br/&gt;
Hibernate has support to extend the class to a domain and assign the properties. In grails mongodb we can acheive this using
Grails persistance listeners.&lt;br/&gt;

&lt;b&gt;1. Install mongodb plugin in grails (BuildConfig.groovy). &lt;/b&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;
compile &quot;org.grails.plugins:mongodb:5.0.7.RELEASE&quot;
&lt;/pre&gt;
&lt;br/&gt;
&lt;b&gt;2. Now Create Perstitance Listener by extending AbstractPersistenceEventListener in src/groovy. AbstractPersistenceEventListener will provide onPersistenceEvent and
we can capture PreInsert, PreUpdate ... events
&lt;/b&gt; &lt;br/&gt;
&lt;b&gt;MongoPersistanceListener.groovy&gt;&lt;/b&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;
import org.grails.datastore.mapping.core.Datastore
import org.grails.datastore.mapping.engine.event.AbstractPersistenceEvent
import org.grails.datastore.mapping.engine.event.AbstractPersistenceEventListener
import org.grails.datastore.mapping.engine.event.PreDeleteEvent
import org.springframework.context.ApplicationEvent

import org.grails.datastore.mapping.engine.event.EventType

class MongoPersistanceListener extends AbstractPersistenceEventListener  {

    def springSecurityService

    public MongoPersistanceListener(final Datastore datastore, def springSecurityService) {
        super(datastore)
        this.springSecurityService = springSecurityService
    }
    @Override
    protected void onPersistenceEvent(final AbstractPersistenceEvent event) {
        def entity = event.entityObject
        switch(event.eventType) {
            case EventType.PreInsert:
                initDefaults(entity)
                break
            case EventType.PostInsert:
                break
            case EventType.PreUpdate:
                def currentUser = springSecurityService.getCurrentUser()
                event.entityObject.updatedBy = currentUser ? currentUser.id : 0;
                event.entityObject.updatedOn = new Date();
                break;
            case EventType.PostUpdate:
                break;
            case PreDeleteEvent:
                break;
            case EventType.PostDelete:
                break;
            case EventType.PreLoad:
                break;
            case EventType.PostLoad:
                break;
            case EventType.Validation:
                initDefaults(entity)
                break;
        }
    }

    @Override
    public boolean supportsEventType(Class&lt;? extends ApplicationEvent&gt; eventType) {
        return true
    }

    void initDefaults(entity) {
        def currentUser = springSecurityService.getCurrentUser()
        if (entity.createdBy == null) {
            entity.createdBy = currentUser? currentUser.id : 0;
        }
        if (entity.createdOn == null) {
            entity.createdOn = new Date();
        }
        if (entity.updatedBy == null) {
            entity.updatedBy = currentUser? currentUser.id : 0;
        }
        if (entity.updatedOn == null) {
            entity.updatedOn = new Date();
        }
    }
}

&lt;/pre&gt;
&lt;b&gt;3. Register this listener in Bootstrap.groovy init method&lt;/b&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;
class BootStrap {

 def springSecurityService

    def init = { servletContext -&gt;
        def ctx = Holders.grailsApplication.mainContext
        ctx.getBeansOfType(Datastore).values().each { Datastore d -&gt;
            ctx.addApplicationListener( new MongoPersistanceListener(d, springSecurityService))
        }
    }
    def destroy = {
    }
}
&lt;/pre&gt;

&lt;/div&gt;

This listener will be invoked when database event is triggered.</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/6574304738817958615'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/6574304738817958615'/><link rel='alternate' type='text/html' href='http://jagadeeshmanne.blogspot.com/2016/06/custom-persistence-listener-in-mongodb.html' title='Custom Persistence Listener in Mongodb Grails plugin'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/09122533940640970927</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author></entry><entry><id>tag:blogger.com,1999:blog-1889673847048308806.post-6148375570891075283</id><published>2016-04-15T03:39:00.001-07:00</published><updated>2016-04-15T04:40:05.320-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Groovy &amp; Grails"/><category scheme="http://www.blogger.com/atom/ns#" term="Hosting"/><title type='text'>Hosting grails application in openshift</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
Hosting a grails application on free hosting provider (openshift) 1. Create account in https://www.openshift.com/ 2. Login to openshift web console 3. click on add application&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhNfTVGfrSN4oLt4DhXjnRokjDi8C0oeEVVwe8y3GTdt4Vjf3LS0t87MkUl4VmwnSh1CwE_VtVMIayp_87q4jcM2L8eK2eM9odOYP76NQEoXGfm57UBsFtHQTnAHcfoD9ZdEs1pcE5G5L4/s1600/webconsole.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;100%&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhNfTVGfrSN4oLt4DhXjnRokjDi8C0oeEVVwe8y3GTdt4Vjf3LS0t87MkUl4VmwnSh1CwE_VtVMIayp_87q4jcM2L8eK2eM9odOYP76NQEoXGfm57UBsFtHQTnAHcfoD9ZdEs1pcE5G5L4/s1600/webconsole.png&quot; width=&quot;100%&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
4. Select Tomcat 7 (JBoss EWS 2.0) from the list of applications&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhpB0_q_TRS2Y3S5TWjFW6TnaswJb6ilFHirx1-w7cB5CqWtwI2Hek-alj4ncTj8V49_UBOASw5V4iV_YMflRiL-gjfMhIzdirE3kYd9EnffeGwoRQ6OkK7RRQh9JGSiDPCWYs1Gq3Fwdk/s1600/download.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhpB0_q_TRS2Y3S5TWjFW6TnaswJb6ilFHirx1-w7cB5CqWtwI2Hek-alj4ncTj8V49_UBOASw5V4iV_YMflRiL-gjfMhIzdirE3kYd9EnffeGwoRQ6OkK7RRQh9JGSiDPCWYs1Gq3Fwdk/s1600/download.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
5. Enter public url and select other configuration and create application. Leave blank in git hub url.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjSLPCRqbbav4dPTZr93dtq1T_vKbwZlbB1GnV0VXnhR-UkZ49qtNCWCO5Chknb2fW6lYEXJPxudH0VaL3SPHRDCk1la8rBHjhauM9tSDf9_KLHKcYpfOyw8S_vQ8zkSMAGHzRI5NzZapU/s1600/screenshot-openshift.redhat.com+2016-04-15+15-27-05.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjSLPCRqbbav4dPTZr93dtq1T_vKbwZlbB1GnV0VXnhR-UkZ49qtNCWCO5Chknb2fW6lYEXJPxudH0VaL3SPHRDCk1la8rBHjhauM9tSDf9_KLHKcYpfOyw8S_vQ8zkSMAGHzRI5NzZapU/s1600/screenshot-openshift.redhat.com+2016-04-15+15-27-05.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
6. Go to applications page -&amp;gt; go to the application that you have created -&amp;gt; add mysql to the application.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiFGQL1oc9DsEhYeatM7-B7WJqRam6xK_TnOXZgAhxgprSRTXE0Pb_O-DEkGxCMLoYTMq4dub6g8_a-S2n7f5WfSp1DpTJbGc92Em3sR-meeckwFA0buS1sjJomBXuLeZevpLczVBXMVdQ/s1600/screenshot-openshift.redhat.com+2016-04-15+15-35-40.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiFGQL1oc9DsEhYeatM7-B7WJqRam6xK_TnOXZgAhxgprSRTXE0Pb_O-DEkGxCMLoYTMq4dub6g8_a-S2n7f5WfSp1DpTJbGc92Em3sR-meeckwFA0buS1sjJomBXuLeZevpLczVBXMVdQ/s1600/screenshot-openshift.redhat.com+2016-04-15+15-35-40.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
7. Click on add Cartridge&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhQFdoEQdVSBwAM1sK6nxpKLrfilqYJHBO-seaf-AR4lHWWIte4Wp3J9qL1a7nLN-h9gRIvMh__Ixlo1tWzuJ5JmvRI1QAIZkg_KXIm2pPcPYsHuSpZJoRSEl7Ap9LPkClIYkN8bxMp7YQ/s1600/download.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhQFdoEQdVSBwAM1sK6nxpKLrfilqYJHBO-seaf-AR4lHWWIte4Wp3J9qL1a7nLN-h9gRIvMh__Ixlo1tWzuJ5JmvRI1QAIZkg_KXIm2pPcPYsHuSpZJoRSEl7Ap9LPkClIYkN8bxMp7YQ/s1600/download.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
8. Now add phpmyadmin catridge to the application by selecting clicking on phpmyadmin&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgA4b6tJ5Mk6GWw8lnhyphenhyphen-RF7lntedTe3-7lzn4huJpL_Jgr4AC0mtViV0YJsPFb_Amd_Io3ZRQMyHdolThaYQf-tc2n7Lf0Zet1hbZ3OMuTmHNhN20Cvgd541PwDGeVnljvSs45NnrZMFc/s1600/download.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgA4b6tJ5Mk6GWw8lnhyphenhyphen-RF7lntedTe3-7lzn4huJpL_Jgr4AC0mtViV0YJsPFb_Amd_Io3ZRQMyHdolThaYQf-tc2n7Lf0Zet1hbZ3OMuTmHNhN20Cvgd541PwDGeVnljvSs45NnrZMFc/s1600/download.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEglbSCoOWW04t4a88pdxh6rJcPEGQ7PCToNDIE6Xwclfuoi-81uPkPukzBCD7Y2nP-qGBl7r4K3T7kcHJvhlX-OHSZXaLMsufWACWTe7pFuN0KfwFIVnVx-TNOcDs1YwjHwHYo6D3wSKlo/s1600/screenshot-openshift.redhat.com+2016-04-15+15-39-54.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEglbSCoOWW04t4a88pdxh6rJcPEGQ7PCToNDIE6Xwclfuoi-81uPkPukzBCD7Y2nP-qGBl7r4K3T7kcHJvhlX-OHSZXaLMsufWACWTe7pFuN0KfwFIVnVx-TNOcDs1YwjHwHYo6D3wSKlo/s1600/screenshot-openshift.redhat.com+2016-04-15+15-39-54.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
9. &lt;b&gt;Database Setup&lt;/b&gt; : Go to the application details page and find database username and password in mysql section&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhUdGQ0UpvEgsGY7nRH1nXMxQcbr-ZS3OS4-741Kr5rIeO9DNIlbOs-qjFKpsBfMSSXWfFj9ZJeFd6RHroOF9PRkUE1xEn2cU8l7wFqErC-sGAu7qn1k-oTVfQroJjyIlUa55V_A_fNva4/s1600/screenshot-openshift.redhat.com+2016-04-15+15-39-54.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhUdGQ0UpvEgsGY7nRH1nXMxQcbr-ZS3OS4-741Kr5rIeO9DNIlbOs-qjFKpsBfMSSXWfFj9ZJeFd6RHroOF9PRkUE1xEn2cU8l7wFqErC-sGAu7qn1k-oTVfQroJjyIlUa55V_A_fNva4/s1600/screenshot-openshift.redhat.com+2016-04-15+15-39-54.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
10. Launch phpmyadmin by using the mysql usernamd and password provided in the application details page to add or modify database and mysql users.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgQ5sncqLp7X-SDBA9reNlN4EgvK8WnGDE5JplLHbZNvIVqkPSoQnOtH5-N7xye0A29uUn0oJA7my_uC11yj9Ge6wMLaImv-DPyht-xd_fB_L1En58YeI_mUNrz_CVxjQf-7vkXcJYUGAI/s1600/screenshot-openshift.redhat.com+2016-04-15+15-39-54.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgQ5sncqLp7X-SDBA9reNlN4EgvK8WnGDE5JplLHbZNvIVqkPSoQnOtH5-N7xye0A29uUn0oJA7my_uC11yj9Ge6wMLaImv-DPyht-xd_fB_L1En58YeI_mUNrz_CVxjQf-7vkXcJYUGAI/s1600/screenshot-openshift.redhat.com+2016-04-15+15-39-54.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
11. Note the server ip address to configure our grails application with mysql database&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhisO1BUVCIvOvivDPdP9rEdHWAwcgfmXs1QcEU51iwaLvEFissNptLhvDHmn0ZejgHYnL0nv4QY4Klw98_rTIRVDYGUcFESzepH_FgVOdd1FFXkPptwS5clhV1hKQrGxfMhPjdW_r_mbY/s1600/screenshot-openshift.redhat.com+2016-04-15+15-39-54.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhisO1BUVCIvOvivDPdP9rEdHWAwcgfmXs1QcEU51iwaLvEFissNptLhvDHmn0ZejgHYnL0nv4QY4Klw98_rTIRVDYGUcFESzepH_FgVOdd1FFXkPptwS5clhV1hKQrGxfMhPjdW_r_mbY/s1600/screenshot-openshift.redhat.com+2016-04-15+15-39-54.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
12. Login to SSH by reading instructions on https://developers.openshift.com/managing-your-applications/remote-connection.html&lt;br /&gt; Make sure to add your public key in openshift account settings.
&amp;nbsp;13. Generate war file for grails application using war command.&lt;br /&gt;
&amp;nbsp;14. Download https://winscp.net/eng/download.php and connect to ssh to upload war file. 13. Upload war file to the path app-root/runtime/dependencies/jbossews/webapps using WinSCP 14. Now we need to restart the tomcat server from ssh. After connecting to ssh run the command &quot;gear start --cart jbossews-2.0&quot;&lt;br /&gt;
&amp;nbsp;15. Now the grails application will be running on openshift server that any one can access&lt;/div&gt;
</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/6148375570891075283'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/6148375570891075283'/><link rel='alternate' type='text/html' href='http://jagadeeshmanne.blogspot.com/2016/04/hosting-grails-application-in-openshift.html' title='Hosting grails application in openshift'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/09122533940640970927</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhNfTVGfrSN4oLt4DhXjnRokjDi8C0oeEVVwe8y3GTdt4Vjf3LS0t87MkUl4VmwnSh1CwE_VtVMIayp_87q4jcM2L8eK2eM9odOYP76NQEoXGfm57UBsFtHQTnAHcfoD9ZdEs1pcE5G5L4/s72-c/webconsole.png" height="72" width="72"/></entry><entry><id>tag:blogger.com,1999:blog-1889673847048308806.post-7602944009565187030</id><published>2016-04-12T02:30:00.003-07:00</published><updated>2016-04-12T02:30:29.980-07:00</updated><title type='text'>Loading spinner using jquery spin js and blockui plugin</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
Loading spinner using jquery spin.js and jquery block ui plug-ins. We can have multiple loaders in same page. Spinner will display inside the element. 
we need to adjust css settings to align the spinner. we can remove  block ui related code in spinner to make the other areas in the page is click-able. &lt;br/&gt;
1. Include jquery&lt;br/&gt;
2. Include spin js http://fgnass.github.io/spin.js/ &lt;br/&gt;
3. Include block ui http://malsup.com/jquery/block/ &lt;br/&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:html&quot;&gt;&lt;script type=&quot;text/javascript&quot;&gt;
 var APP = APP || {};
 APP.UI = (function(){
  function showLoader(el) {
   var opts = {
    lines: 13,
    length: 7,
    width: 4,
    radius: 10,
    corners: 1,
    rotate: 0,
    color: &#39;#000&#39;,
    speed: 1,
    trail: 60,
    shadow: false,
    hwaccel: false,
    className: &#39;spinner&#39;,
    zIndex: 2e9,
    top: &#39;50%&#39;,
    left: &#39;50%&#39;,
    visibility: true
   };
   el.spin(opts);
   $.blockUI({message: null});
  }
  function hideLoader(el) {
   el.spin(false);
   $.unblockUI();
  }

  return {showLoader:showLoader, hideLoader: hideLoader}
 })();
&lt;/script&gt;
&lt;/pre&gt;
To display loader
&lt;br /&gt;
&lt;pre class=&quot;brush:html&quot;&gt;APP.UI.showLoader($(&#39;jquery-selector&#39;));
&lt;/pre&gt;
To hide loader
&lt;br /&gt;
&lt;pre class=&quot;brush:html&quot;&gt;APP.UI.hideLoader($(&#39;jquery-selector&#39;));
&lt;/pre&gt;
you can have multiple loaders in same page, by using different jquery selectors.&lt;/div&gt;
</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/7602944009565187030'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/7602944009565187030'/><link rel='alternate' type='text/html' href='http://jagadeeshmanne.blogspot.com/2016/04/loading-spinner-using-jquery-spin-js_12.html' title='Loading spinner using jquery spin js and blockui plugin'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/09122533940640970927</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author></entry><entry><id>tag:blogger.com,1999:blog-1889673847048308806.post-2799456552271714564</id><published>2015-10-01T23:06:00.003-07:00</published><updated>2015-10-01T23:11:10.770-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Groovy &amp; Grails"/><category scheme="http://www.blogger.com/atom/ns#" term="Spock"/><title type='text'>Grails Spock Testing Where Block Passing Dynamic Objects</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Grails Spock testing passing dynamic objects in where block&lt;/b&gt;
&lt;br /&gt;
To fix  &quot;Only @Shared and static fields may be accessed from here&quot; issue in spock integration test with where block
we need to use @Shared annotation while declaring variables and need to initialize them in setupSpec() method&lt;br/&gt;
&lt;b&gt;Sample implementation&lt;/b&gt; 
&lt;br /&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;@TestMixin(IntegrationTestMixin)
class SpockExampleIntegrationTests  extends Specification {
    @Shared String email1
    @Shared String email2
 
    void setup() {
          email1 = &quot;mannejkumar@gmail.com&quot;
          email2 = &quot;jk.manne@yahoo.com&quot;
    }
 
    def testGetEmployeeById() {
  
        setup:
        Employee employee
  
        when:
        employee = employeeService.getEmployeeById(employeeId)

        then:
        employee.email == result

        where:
        sno |   employeeId     |     result     
        1   |   1              |     email1
        2   |   2              |     email2
   }
}
&lt;/pre&gt;
&lt;/div&gt;
</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/2799456552271714564'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/2799456552271714564'/><link rel='alternate' type='text/html' href='http://jagadeeshmanne.blogspot.com/2015/10/grails-spock-testing-where-block.html' title='Grails Spock Testing Where Block Passing Dynamic Objects'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/09122533940640970927</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author></entry><entry><id>tag:blogger.com,1999:blog-1889673847048308806.post-6193407075547577822</id><published>2014-03-21T22:12:00.000-07:00</published><updated>2014-03-21T22:12:50.291-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Groovy &amp; Grails"/><title type='text'>Adding properties to domain classes on the fly using groovy propertyMissing feature</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;&lt;br /&gt;&lt;br /&gt;
&lt;b&gt;Adding properties to domain classes on the fly using groovy propertyMissing feature&lt;/b&gt;
&lt;br /&gt;
Some times we need to add properties to domain classes on the fly. &lt;br/&gt;
Groovy supports propertyMissing for dealing with property resolution attempts. 
Steps to added dynamic properties to domain classes. &lt;br/&gt;

&lt;b&gt;1. Create Entity.groovy class in src/groovy folder and use groovy propertyMissing feature in Entity class&lt;/b&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;
class Entity {
   def dynamicProperties= [:]
   //setter
   def propertyMissing(String name, value) { dynamicProperties= [name] = value }
   //getter
   def propertyMissing(String name) { dynamicProperties= [name] }
}
&lt;/pre&gt;
&lt;br/&gt;
&lt;b&gt;2. Now extend Entity class from your domain class&lt;/b&gt; &lt;br/&gt;
&lt;b&gt;User.groovy&gt;&lt;/b&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;
class User extends Entity{
   String firstName
   String lastName
   
}
&lt;/pre&gt;
&lt;b&gt;Address.groovy&lt;/b&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;
class Address extends Entity{
   String country   
}
&lt;/pre&gt;
&lt;br/&gt;
&lt;b&gt;3. Testing the dynamic properties&lt;/b&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;
class DynamicPropertyTester {

   static void main(String[] args) {

 User user = new User();
        user.firstName = &quot;Jagadeesh&quot;;
        user.lastName = &quot;Manne&quot;;
        user.name = &quot;$user.firstName $user.lastName&quot;; //adding dynamic property &quot;name&quot; that doesnt exist in User domain
        println &quot;Name : $user.name&quot;; 
        //out put 
        //Name : Jagadeesh Manne
        
        Address address = new Address();
        address.country = &quot;India&quot;;
        address.state = &quot;AP&quot;;      //dynamic property
        address.city = &quot;Vijayawada&quot;; // dynamic property
        println &quot;Country : $address.country, State : $address.state, City: $address.city&quot; 
        //out put
        // Country : India, State : AP, City: Vijayawada
 
   }
   
}
&lt;/pre&gt;

&lt;/div&gt;</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/6193407075547577822'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/6193407075547577822'/><link rel='alternate' type='text/html' href='http://jagadeeshmanne.blogspot.com/2014/03/adding-properties-to-domain-classes-on.html' title='Adding properties to domain classes on the fly using groovy propertyMissing feature'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/09122533940640970927</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author></entry><entry><id>tag:blogger.com,1999:blog-1889673847048308806.post-892703244579912252</id><published>2014-03-12T21:35:00.000-07:00</published><updated>2014-03-12T21:37:37.312-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Core Java"/><category scheme="http://www.blogger.com/atom/ns#" term="JDBC"/><title type='text'>Connection Pool in Java &amp; JDBC</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
Connection Pooling in JDBC

In software engineering, a connection pool is a cache of database connections maintained so that the connections can be reused when future requests to the database are required. Connection pools are used to enhance the performance of executing commands on a database. Opening and maintaining a database connection for each user, especially requests made to a dynamic database-driven website application, is costly and wastes resources. In connection pooling, after a connection is created, it is placed in the pool and it is used over again so that a new connection does not have to be established. If all the connections are being used, a new connection is made and is added to the pool. Connection pooling also cuts down on the amount of time a user must wait to establish a connection to the database.(source :wikipedia)&lt;br /&gt;
&lt;br /&gt;
Steps to create connection pool in jdbc&lt;br /&gt;
&lt;b&gt;1. Create Configuration class that holds Database Configuration &lt;/b&gt;&lt;br /&gt;
&lt;b&gt;2. Create JdbcConnectionPool class that Creating and managing the connections &lt;/b&gt;&lt;br /&gt;
&lt;b&gt;3. Create DataSource class to get connection and returning the connection to connection pool &lt;/b&gt;&lt;br /&gt;
&lt;b&gt;&lt;br /&gt;&lt;/b&gt;
&lt;b&gt;1. Configuration Class (Configuration.java) &lt;/b&gt;&lt;br /&gt;
&lt;b&gt;a. Make the configuration class as singleton&lt;/b&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;public class Configuration {
 private static Configuration configuration = new Configuration();
 
 public static Configuration getInstance(){ 
  return configuration;
 }
}
&lt;/pre&gt;
&lt;br /&gt;
b.&lt;b&gt; Create initialize method that sets the database configuration properties
&lt;/b&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;public class Configuration {

 public String DB_USER_NAME ;
 
 public String DB_PASSWORD ;
 
 public String DB_URL;
 
 public String DB_DRIVER;
 
 public Integer DB_MAX_CONNECTIONS;
 
 private void init() {
  DB_USER_NAME = &quot;root&quot;
  DB_PASSWORD = &quot;root&quot;
  DB_URL = &quot;jdbc:mysql://localhost:3306/jmanne&quot;
  DB_DRIVER = &quot;com.mysql.jdbc.Driver&quot;
  DB_MAX_CONNECTIONS = 5
 }
 
}
&lt;/pre&gt;
&lt;br /&gt;
&lt;b&gt;c. Call the init method in the constructor
&lt;/b&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt; public Configuration(){
  init();
 }
&lt;/pre&gt;
&lt;br /&gt;
Finally Configuration.java
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;public class Configuration {
 
 public String DB_USER_NAME ;
 
 public String DB_PASSWORD ;
 
 public String DB_URL;
 
 public String DB_DRIVER;
 
 public Integer DB_MAX_CONNECTIONS;
 
 public Configuration(){
  init();
 }
 
 private static Configuration configuration = new Configuration();
 
 public static Configuration getInstance(){ 
  return configuration;
 }
 
 private void init() {
  DB_USER_NAME = &quot;root&quot;
  DB_PASSWORD = &quot;root&quot;
  DB_URL = &quot;jdbc:mysql://localhost:3306/jmanne&quot;
  DB_DRIVER = &quot;com.mysql.jdbc.Driver&quot;
  DB_MAX_CONNECTIONS = 5
 }
}
&lt;/pre&gt;
&lt;br /&gt;
&lt;b&gt;2. Creating JDBCConnectionPool.java&amp;nbsp;&lt;/b&gt;&lt;br /&gt;
&lt;b&gt;&lt;br /&gt;&lt;/b&gt;
&lt;b&gt;a. Create an empty array list to hold the connections
&lt;/b&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;public class JdbcConnectionPool {
 List&lt;connection&gt; availableConnections = new ArrayList&lt;connection&gt;();
}
&lt;/connection&gt;&lt;/connection&gt;&lt;/pre&gt;
&lt;br /&gt;
&lt;b&gt;b. Get the database configuration from Configuration.java and Create a new Connection 
&lt;/b&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;private Connection createNewConnectionForPool() {
    // get the configuraiton object to get the database configuration
 Configuration config = Configuration.getInstance();
 try {
     //load the Database driver using Class.forName
  Class.forName(config.DB_DRIVER);
  // Create connection by using DriverManager
  Connection connection = (Connection) DriverManager.getConnection(
    config.DB_URL, config.DB_USER_NAME, config.DB_PASSWORD);
  return connection;
 } catch (ClassNotFoundException e) {
  e.printStackTrace();
 } catch (SQLException e) {
  e.printStackTrace();
 }
 return null;
 
}
&lt;/pre&gt;
&lt;br /&gt;
&lt;b&gt;c. Initialize the connection pool and check the connection pool is full and if connection pool is empty then add new connection
&lt;/b&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;private void initializeConnectionPool()
{
 while(!checkIfConnectionPoolIsFull())
 {
  availableConnections.add(createNewConnectionForPool());
 }
} 
private synchronized boolean checkIfConnectionPoolIsFull() {
 final int MAX_POOL_SIZE = Configuration.getInstance().DB_MAX_CONNECTIONS;
 // check the connections size in the available connections
 if(availableConnections.size() &amp;lt; MAX_POOL_SIZE)
 {
  return false;
 }

 return true;
}
&lt;/pre&gt;
&lt;br /&gt;
&lt;b&gt;d. Get the connection from connection  pool
&lt;/b&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt; 
public synchronized Connection getConnectionFromPool() {
 Connection connection = null;
 if(availableConnections.size() &amp;gt; 0)
 {
  connection = (Connection) availableConnections.get(0);
  availableConnections.remove(0);
 }
 return connection;
}
&lt;/pre&gt;
&lt;br /&gt;
&lt;b&gt;e. Return the connection to connection pool
&lt;/b&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;  
public synchronized void returnConnectionToPool(Connection connection) {
 availableConnections.add(connection);
}
&lt;/pre&gt;
&lt;br /&gt;
&lt;b&gt;f. initialize the connection pool in the constructor
&lt;/b&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;public JdbcConnectionPool() {
 initializeConnectionPool();
}
&lt;/pre&gt;
&lt;br /&gt;
&lt;b&gt;3. Creating DataSource class to get the connection and return the connection
&lt;/b&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;import java.sql.SQLException;
import com.mysql.jdbc.Connection;

public class DataSource {
 
 static JdbcConnectionPool pool = new JdbcConnectionPool();
 
 public static Connection getConnection() throws ClassNotFoundException, SQLException{
  Connection connection = pool.getConnectionFromPool();
  return connection;
 }
 
 public static void returnConnection(Connection connection) {
  pool.returnConnectionToPool(connection);
 }
}
 &lt;/pre&gt;
Now We can use DataSource class to get the connection
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;Connection connection = DataSource.getConnection();
&lt;/pre&gt;
&lt;br /&gt;
Final Source code&lt;br /&gt;
&lt;b&gt;1. Configuration.java
&lt;/b&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package com.jmanne.utils;

public class Configuration {
 
 public String DB_USER_NAME ;
 
 public String DB_PASSWORD ;
 
 public String DB_URL;
 
 public String DB_DRIVER;
 
 public Integer DB_MAX_CONNECTIONS;
 
 public Configuration(){
  init();
 }
 
 private static Configuration configuration = new Configuration();
 
 public static Configuration getInstance(){ 
  return configuration;
 }
 
 private void init(){
  DB_USER_NAME = &quot;root&quot;
  DB_PASSWORD = &quot;root&quot;
  DB_URL = &quot;jdbc:mysql://localhost:3306/jmanne&quot;
  DB_DRIVER = &quot;com.mysql.jdbc.Driver&quot;
  DB_MAX_CONNECTIONS = 5
 }

}
&lt;/pre&gt;
&lt;br /&gt;
&lt;b&gt;2. JdbcConnectionPool.java
&lt;/b&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package com.jmanne.db;

import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.jmanne.utils.Configuration;
import com.mysql.jdbc.Connection;

public class JdbcConnectionPool {
 
 List&lt;connection&gt; availableConnections = new ArrayList&lt;connection&gt;();

 public JdbcConnectionPool()
 {
  initializeConnectionPool();
 }

 private void initializeConnectionPool()
 {
  while(!checkIfConnectionPoolIsFull())
  {
   availableConnections.add(createNewConnectionForPool());
  }
 }

 private synchronized boolean checkIfConnectionPoolIsFull()
 {
  final int MAX_POOL_SIZE = Configuration.getInstance().DB_MAX_CONNECTIONS;

  if(availableConnections.size() &amp;lt; MAX_POOL_SIZE)
  {
   return false;
  }

  return true;
 }

 //Creating a connection
 private Connection createNewConnectionForPool()
 {
  Configuration config = Configuration.getInstance();
  try {
   Class.forName(config.DB_DRIVER);
   Connection connection = (Connection) DriverManager.getConnection(
     config.DB_URL, config.DB_USER_NAME, config.DB_PASSWORD);
   return connection;
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  } catch (SQLException e) {
   e.printStackTrace();
  }
  return null;
  
 }

 public synchronized Connection getConnectionFromPool()
 {
  Connection connection = null;
  if(availableConnections.size() &amp;gt; 0)
  {
   connection = (Connection) availableConnections.get(0);
   availableConnections.remove(0);
  }
  return connection;
 }

 public synchronized void returnConnectionToPool(Connection connection)
 {
  availableConnections.add(connection);
 }
}

&lt;/pre&gt;
&lt;b&gt;3. DataSource.java
&lt;/b&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package com.jmanne.db;

import java.sql.SQLException;

import com.mysql.jdbc.Connection;

public class DataSource {
 
 static JdbcConnectionPool pool = new JdbcConnectionPool();
 
 public static Connection getConnection() throws ClassNotFoundException, SQLException{
  Connection connection = pool.getConnectionFromPool();
  return connection;
 }
 
 public static void returnConnection(Connection connection) {
  pool.returnConnectionToPool(connection);
 }
}
&lt;/pre&gt;
&lt;br /&gt;&lt;/div&gt;
</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/892703244579912252'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/892703244579912252'/><link rel='alternate' type='text/html' href='http://jagadeeshmanne.blogspot.com/2014/03/connection-pool-in-java-jdbc.html' title='Connection Pool in Java &amp; JDBC'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/09122533940640970927</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author></entry><entry><id>tag:blogger.com,1999:blog-1889673847048308806.post-8650466636418531897</id><published>2014-03-06T21:02:00.001-08:00</published><updated>2014-03-07T00:50:30.378-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Groovy &amp; Grails"/><title type='text'>checking the website is responsive or not using selenium and groovy, grails and java</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;checking the website is responsive or not using selenium and groovy, grails and java&lt;/b&gt;
&lt;br /&gt;
Here i am providing the way to find the given website is responsive or not using selnium and grails. We can acheive this in multiple ways&lt;br /&gt;
&lt;b&gt;1. Screenshot comparison&lt;/b&gt; : Using selenium webdriver go to the given website url and change the browser to different sizes and compare the 
screenshots.If both screenshots are same then the given website is not responsive.If both screenshots are different then given website is 
responsive. This method is not good because Lets assume if slideshows are present in given website while taking the screenshots of that website, 
the slideshow images present in the given website may change and we will get different screenshots so if we compare the screenshots 
we will get result as both screenshots are different and we may get response as the given site is responsive&lt;br /&gt;
&lt;b&gt;&lt;br /&gt;&lt;/b&gt;
&lt;b&gt;2. The document width&lt;/b&gt; : Using selenium webdriver go to the given website url and change the browser to mobile device size and execute 
the javascript to get document width. If width is less than mobile devices maximum width we can assume that the given website is responsive&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;3. Screenshot width&lt;/b&gt; : Using selenium webdriver go to the given website url and change the browser to mobile device size and take the screenshot 
and get the width of the screenshot image. If width is less than mobile devices maximum width we can assume that the given website is responsive.
I tested multiple sites with this approach and got the expected result

Steps to check given site is responsive or not&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;1. Add selenium dependencies in BuildConig.groovy&lt;/b&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;compile &#39;org.seleniumhq.selenium:selenium-support:2.15.0&#39;
compile &#39;org.seleniumhq.selenium:selenium-htmlunit-driver:2.25.0&#39;
runtime(&#39;org.seleniumhq.selenium:selenium-java:2.29.1&#39;){
 excludes &quot;selenium-htmlunit-driver&quot;
}
&lt;/pre&gt;
&lt;b&gt;&lt;br /&gt;&lt;/b&gt;
&lt;b&gt;2. Create firefoxprofile 
&lt;/b&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt; DesiredCapabilities capabilities = new DesiredCapabilities(&quot;firefox&quot;, &quot;3.6.&quot;, Platform.LINUX);
 FirefoxProfile profile = new FirefoxProfile();
&lt;/pre&gt;
&lt;b&gt;&lt;br /&gt;&lt;/b&gt;
&lt;b&gt;3. Create Remote Web Driver by specifying selenium server url
&lt;/b&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;driver = new RemoteWebDriver(new java.net.URL(&quot;http://127.0.0.1:4444//wd/hub&quot;), capabilities);
&lt;/pre&gt;
&lt;b&gt;&lt;br /&gt;&lt;/b&gt;
&lt;b&gt;4. Set the window size to mobile device size
&lt;/b&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;driver.manage().window().setSize(new Dimension(320, 480))
&lt;/pre&gt;
&lt;b&gt;&lt;br /&gt;&lt;/b&gt;
&lt;b&gt;5. Open the url 
&lt;/b&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt; driver.get(urlString)
&lt;/pre&gt;
&lt;b&gt;&lt;br /&gt;&lt;/b&gt;
&lt;b&gt;6. Method 1&lt;/b&gt; : Take the Screenshot and get the width of the screenshot. RemoteDriver doesnt implement the TAkeScreenShot class. 
If the driver does have the Capabilities to take a screenshot.Then Augmenter will add the TakesScreenshot methods to the instance
&lt;br /&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;File screenShot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
BufferedImage bufferedImage = ImageIO.read(screenShot);
int width = bufferedImage?.width
&lt;/pre&gt;
&lt;b&gt;&lt;br /&gt;&lt;/b&gt;
&lt;b&gt;Method 2&lt;/b&gt; : Execute the javascript and get the document width
&lt;br /&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt; JavascriptExecutor js = (JavascriptExecutor)driver;
 int width = js.executeScript(&quot;return \$(document).width()&quot;)
&lt;/pre&gt;
&lt;b&gt;&lt;br /&gt;&lt;/b&gt;
&lt;b&gt;7. Compare the width with mobile device maximum width
&lt;/b&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;//Asuming mobile device width is 480
boolean isResponsive = (width &amp;lt;= 480)
&lt;/pre&gt;
&lt;b&gt;&lt;br /&gt;&lt;/b&gt;
&lt;b&gt;8. run the selenium server
&lt;/b&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt; java -jar seleniumserver.jar
&lt;/pre&gt;
&lt;b&gt;Getting all together in one groovy class called MobileUtils.groovy&lt;/b&gt;. Make sure that you have given valid url otherwise validate the given url and
show the error message if the given url is invalid
&lt;br /&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;class MobileUtils {
 import org.openqa.selenium.Platform
 import org.openqa.selenium.WebDriver
 import org.openqa.selenium.firefox.FirefoxDriver
 import org.openqa.selenium.firefox.FirefoxProfile
 import org.openqa.selenium.remote.DesiredCapabilities
 import org.openqa.selenium.remote.RemoteWebDriver
 import org.openqa.selenium.remote.Augmenter
 import org.openqa.selenium.Dimension
 import org.openqa.selenium.TakesScreenshot
 import org.openqa.selenium.OutputType
 import org.openqa.selenium.io.TemporaryFilesystem
 import java.awt.image.BufferedImage
 import javax.imageio.ImageIO

 //by taking screenshot and comparing width
 boolean isResponsiveByJs(String url) {
  WebDriver driver = null
  boolean isResponsive = false
  try {
   DesiredCapabilities capabilities = 
   new DesiredCapabilities(&quot;firefox&quot;, &quot;3.6.&quot;, Platform.LINUX);
   FirefoxProfile profile = new FirefoxProfile();
   capabilities.setCapability(FirefoxDriver.PROFILE, profile);
   driver = 
 new RemoteWebDriver(new java.net.URL(&quot;http://127.0.0.1:4444//wd/hub&quot;), capabilities);
   driver = new Augmenter().augment(driver);
   driver.manage().window().setSize(new Dimension(320, 480))
   driver.get(url)
   JavascriptExecutor js = (JavascriptExecutor)driver;
            int width = js.executeScript(&quot;return \$(document).width()&quot;)
   isResponsive = (bufferedImage?.width &amp;lt;= 480);
  } finally {
      //delete the temporary files created by selenium firefox profile
   TemporaryFilesystem.getDefaultTmpFS().deleteTemporaryFiles()
   driver?.quit()
  }
  return isResponsive
    }
 
 // by executing javascript
 boolean isResponsiveByScreenshot(String url) {
  WebDriver driver = null
  boolean isResponsive = false
  try {
   DesiredCapabilities capabilities = 
   new DesiredCapabilities(&quot;firefox&quot;, &quot;3.6.&quot;, Platform.LINUX);
   FirefoxProfile profile = new FirefoxProfile();
   capabilities.setCapability(FirefoxDriver.PROFILE, profile);
   driver = new RemoteWebDriver(new java.net.URL(&quot;http://127.0.0.1:4444//wd/hub&quot;), capabilities);
   driver = new Augmenter().augment(driver);
   driver.manage().window().setSize(new Dimension(320, 480))
   driver.get(url)
   File screenShot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
   BufferedImage bufferedImage = ImageIO.read(screenShot);
   int width = bufferedImage.width
   isResponsive = (bufferedImage?.width &amp;lt;= 480);
   
  } finally {
      //delete the temporary files created by selenium firefox profile
   TemporaryFilesystem.getDefaultTmpFS().deleteTemporaryFiles()
   driver?.quit()
  }
  return isResponsive
 }
}
&lt;/pre&gt;
If you have better idea than these methods please let me know in comments.
&lt;/div&gt;
</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/8650466636418531897'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/8650466636418531897'/><link rel='alternate' type='text/html' href='http://jagadeeshmanne.blogspot.com/2014/03/checking-website-is-responsive-or-not.html' title='checking the website is responsive or not using selenium and groovy, grails and java'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/09122533940640970927</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author></entry><entry><id>tag:blogger.com,1999:blog-1889673847048308806.post-251737930474780130</id><published>2014-02-19T17:53:00.002-08:00</published><updated>2014-02-19T17:55:46.543-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Groovy &amp; Grails"/><title type='text'>grails mobile device detection using spring mobile and adding different views for mobile and web</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;&lt;br /&gt;&lt;br /&gt;
&lt;b&gt;grails mobile device detection using spring mobile and adding different views for mobile and web&lt;/b&gt;
&lt;br /&gt;
Recently i worked on a project that has to generate different views for mobile and tab and web. we can design website as responsive but i have different designs for mobile and web and tablet. so i went through &lt;a href=&quot;http://grails.org/plugin/spring-mobile&quot;&gt;spring mobile plugin for grails&lt;/a&gt;. The plugin adds dynamic methods to your controllers to determine what type of client is accessing the app:&lt;br/&gt;
&lt;b&gt;isMobile()&lt;/b&gt; will be true if the client is a mobile phone.&lt;br/&gt;

&lt;b&gt;isTablet()&lt;/b&gt; will be true if the client is a tablet.&lt;br/&gt;

&lt;b&gt;isNormal()&lt;/b&gt; will be true if the client is not a mobile phone or tablet.&lt;br/&gt;

Additionally, you can run code conditionally, with access to the current org.springframework.mobile.device.Device instance, with this method:
&lt;br /&gt;
&lt;b&gt;withMobileDevice(Closure closure)&lt;/b&gt;

&lt;br /&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;
def list() {
   def view = &quot;list&quot;
   withMobileDevice { device -&gt;
      view = &quot;mobileList&quot;
   }
   render(view: view, model: [list: listInstance])
}
&lt;/pre&gt;
But we don&#39;t have &lt;b&gt;withTabletDevice&lt;/b&gt; closure to generate views for tablets device. &lt;br/&gt;
for small application it is okay to use this closure to generate views. What about if we have many controllers with many actions?&lt;br/&gt;
Here is the way to implement single place to handle device specific views.&lt;br/&gt;&lt;br/&gt;

1. &lt;b&gt;Install grails spring mobile plugin&lt;/b&gt;&lt;br/&gt;
2. &lt;b&gt;Create A BaseController&lt;/b&gt;&lt;br/&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;
class BaseController {

 String prefix = &quot;/web&quot;;
 
 def beforeInterceptor = {
  if(isMobile()){
   prefix = &quot;/mobile&quot;
  } else if(isTablet()){
   prefix = &quot;/tablet&quot;
  }
 }
 
 def afterInterceptor = { model, modelAndView -&gt;
  if(modelAndView) {
   modelAndView.viewName = prefix + modelAndView.viewName
  }
 }
}
&lt;/pre&gt;
&lt;b&gt;&lt;b&gt;&lt;a href=&quot;http://grails.org/doc/2.3.x/ref/Controllers/beforeInterceptor.html&quot;&gt;beforeInterceptor&lt;/a&gt;&lt;/b&gt;&lt;/b&gt; : Allows the interception of an action before it is executed. A beforeInterceptor can optionally halt execution of the action. &lt;br/&gt;&lt;br/&gt;
&lt;b&gt;&lt;a href=&quot;http://grails.org/doc/2.3.x/ref/Controllers/afterInterceptor.html&quot;&gt;afterInterceptor&lt;/a&gt;&lt;/b&gt; : Allows interception of actions after they have executed, but before the view is rendered.&lt;br/&gt;&lt;br/&gt;

3.&lt;b&gt;Extend the basecontroller&lt;/b&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;
class UserController extends BaseController{

       def list() {
       render(view: view, model: [list: listInstance])
   }
}
&lt;/pre&gt;

4.&lt;b&gt;create device specific views under views folder&lt;/b&gt; &lt;br/&gt;
&lt;pre class=&quot;brush:text&quot;&gt;
   views
       -&gt; mobile
           -&gt;mobileviews
       -&gt; tablet
           -&gt;tabletviews
       -&gt; web
           -&gt;webviews
&lt;/pre&gt; 
Thats it. Now check your application in different devices

&lt;/div&gt;</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/251737930474780130'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/251737930474780130'/><link rel='alternate' type='text/html' href='http://jagadeeshmanne.blogspot.com/2014/02/grails-mobile-device-detection-using.html' title='grails mobile device detection using spring mobile and adding different views for mobile and web'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/09122533940640970927</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author></entry><entry><id>tag:blogger.com,1999:blog-1889673847048308806.post-5863965478730689009</id><published>2014-02-18T23:54:00.000-08:00</published><updated>2014-02-19T16:33:48.463-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Groovy &amp; Grails"/><title type='text'>could not parse date unparseable date grails domain save</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;&lt;br /&gt;&lt;br /&gt;
could not parse date unparseable date grails domain save
&lt;br /&gt;
I ran into a little problem with Grails and validation today. I was parsing a date from a web post and kept getting a validation error.
&lt;br /&gt;
My original code was as follows:

&lt;br /&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;
def job = new Job(params)
if (params?.expiryDate) {
    job.expiryDate = new Date().parse(&quot;MM/dd/yyyy&quot;, params.expiryDate)
} else {
    job.expiryDate = null
}
job.validate()
if (!job.hasErrors()){
    job.save(failOnError:true)
}
&lt;/pre&gt;
When i am trying to save job i am getting validation error &lt;b&gt;&quot;Failed to convert property value of type java.lang.String to required 
type java.sql.Date for property ; nested exception is 
java.lang.IllegalArgumentException: Could not parse date: Unparseable 
date: &quot;&lt;/b&gt;&lt;br /&gt;
When I got the validation errors, I realized the date format was wrong and tried multiple ways to convert string to date object.&lt;br /&gt;
Seemed simple enough. But I kept getting validation errors on the date.&lt;br /&gt;
My domain clearly had a Date property, a I was creating a valid date and setting it.
Answer nothing was wrong with with the value I parsed and set. Problem was in creating the application object in the first place. This chunk of code:
&lt;/div&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;
def job = new Job(params)
&lt;/pre&gt;
is implicitly calling validate and populating the errors object. Even though I was setting a valid value and calling validate later, the errors object had already been set and was not getting cleared.&lt;br /&gt;
Solution: 
&lt;br /&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;
job.clearErrors()
&lt;/pre&gt;
Thats it . It works like a champ now!&lt;br /&gt;
Here is the full code : 
&lt;br /&gt;
&lt;pre class=&quot;brush:groovy&quot;&gt;
def job = new Job(params)
job.clearErrors();
if (params?.expiryDate) {
    job.expiryDate = new Date().parse(&quot;MM/dd/yyyy&quot;, params.expiryDate)
} else {
    job.expiryDate = null
}
job.validate()
if (!job.hasErrors()){
    job.save(failOnError:true)
}
&lt;/pre&gt;
Source : &lt;a href=&quot;http://jts-blog.com/&quot;&gt;http://jts-blog.com/&lt;/a&gt; (Thanks to JT for saving my time)
&lt;/div&gt;
</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/5863965478730689009'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/5863965478730689009'/><link rel='alternate' type='text/html' href='http://jagadeeshmanne.blogspot.com/2014/02/could-not-parse-date-unparseable-date.html' title='could not parse date unparseable date grails domain save'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/09122533940640970927</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author></entry><entry><id>tag:blogger.com,1999:blog-1889673847048308806.post-8038045460518185106</id><published>2012-08-23T02:02:00.000-07:00</published><updated>2012-08-23T02:02:41.746-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Advanced Java"/><title type='text'>Solution for Java.Lang.OutOfMemoryError: PermGen Space in Tomcat</title><content type='html'>Java.Lang.OutOfMemoryError: PermGen Space in Tomcat is usually happened when the Tomcat start and stop few times. By default, Tomcat assigned very little memory for the running process, you should increase the memory by make change in catalina.bat file.

Solution : 
find the catalina.bat file located at tomcat\bin directory. and open it with text editor. find set JAVA_OPTS after this line add the following 
set JAVA_OPTS=-XX:PermSize=256m -Xms128m -Xmx1024m %JAVA_OPTS% </content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/8038045460518185106'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/8038045460518185106'/><link rel='alternate' type='text/html' href='http://jagadeeshmanne.blogspot.com/2012/08/solution-for-javalangoutofmemoryerror.html' title='Solution for Java.Lang.OutOfMemoryError: PermGen Space in Tomcat'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/09122533940640970927</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author></entry><entry><id>tag:blogger.com,1999:blog-1889673847048308806.post-5660571088781387148</id><published>2011-12-22T00:34:00.000-08:00</published><updated>2011-12-22T01:28:24.681-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Java Script"/><title type='text'>Rate widget using Java Script</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;This is the code i have done to display five star rate widget using javascript. this is only to display start widget and rate it. i didnt integrate or save in server.&lt;br /&gt;
&lt;br /&gt;
&lt;/div&gt;&lt;pre class=&quot;brush:html&quot;&gt;&amp;lt;html&amp;gt;
 &amp;lt;head&amp;gt;
  &lt;title&gt; Rate widget using javascript&lt;/title&gt;
  &lt;style&gt;
 span{
  font-size : 30pt;
  cursor:pointer;
 }
  
&lt;/style&gt;
  &lt;script type=&quot;text/javascript&quot;&gt;
var isRated = false;
var i = 0;
function displayRateWidget(id)
{
 var container = document.getElementById(id);
 for(var i = 0; i &lt; 5; i++){  
  var spanElement = document.createElement(&#39;span&#39;);
  spanElement.id = i;
  container.appendChild(spanElement);
  var starSymbol = document.createTextNode(&#39;*&#39;);
  spanElement.appendChild(starSymbol);
  var changeColor = function(){
   isRated = false;
   for(var i = 0; i &lt;container.childNodes.length; i++){
    if(container.childNodes[i].nodeType == 1) {
     container.childNodes[i].style.color = &#39;red&#39;;
     if(container.childNodes[i].id == this.id)
      break;
    }
   }
  }
  var removeColor = function(){
   if(isRated == false){
    for(var i = 0; i &lt;container.childNodes.length; i++){ 
       if(container.childNodes[i].nodeType == 1) {
      container.childNodes[i].style.color = &#39;&#39;;
     }
    }
   }
  }
  spanElement.onclick= function(){
   i = this.id
   isRated = true;
  }
  spanElement.onmouseover = changeColor;
  spanElement.onmouseout = removeColor;

 }
}
&lt;/script&gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt; onload=&quot;displayRateWidget(&#39;rateWidget&#39;)&quot;&amp;gt;
  &lt;div id=&quot;rateWidget&quot;&gt;

&lt;/div&gt;&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;

&lt;/pre&gt;&lt;/div&gt;&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;b&gt;Result of the above program:&lt;/b&gt;
&lt;/div&gt;&lt;iframe frameborder=&quot;0&quot; scrolling=&quot;no&quot; src=&quot;http://jsfiddle.net/mannejkumar/yC5Yq/embedded/result/&quot; style=&quot;height: 90px; overflow: hidden; width: 100%;&quot;&gt;&lt;/iframe&gt;&lt;/div&gt;</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/5660571088781387148'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/5660571088781387148'/><link rel='alternate' type='text/html' href='http://jagadeeshmanne.blogspot.com/2011/12/rate-widget-using-java-script.html' title='Rate widget using Java Script'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/09122533940640970927</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author></entry><entry><id>tag:blogger.com,1999:blog-1889673847048308806.post-8135594905787953578</id><published>2011-12-19T07:07:00.000-08:00</published><updated>2011-12-20T23:15:38.258-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Core Java"/><title type='text'>Core Java: Reading and Writing Object to a File (IOStreams and Exceptions)</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;IOStreams example: write an employee to a file and read employees from file using java io streams.in this example i also used user defined exceptions. I am providing download link to this example. if free hosing site deletes that file drop your mail id to get this example&lt;br /&gt;
&lt;br /&gt;
&lt;a href=&quot;http://www.mediafire.com/?9q92pm9oy4f3c46&quot; target=&quot;_blank&quot;&gt;download Reading and Writing Object to a file using Serializable and IOStreams&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Package structure&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a class=&quot;lightbox&quot; href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh5VPAlS4XAejb11_onkMawdc4vt66xD80npqhi_AgA94A9Ef4-JpCCsNPVPBCbnD0xAwy-EtqKK_nWuvDeai3FKB5W4SXyaG8CzGAvlmR7SO2ajdTHqUUfCdIlrc9jUUt712IzfW9K78s/s1600/iostreams.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;320&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh5VPAlS4XAejb11_onkMawdc4vt66xD80npqhi_AgA94A9Ef4-JpCCsNPVPBCbnD0xAwy-EtqKK_nWuvDeai3FKB5W4SXyaG8CzGAvlmR7SO2ajdTHqUUfCdIlrc9jUUt712IzfW9K78s/s320/iostreams.png&quot; width=&quot;264&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Employee.java&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package com.jagadeesh.domain;

public interface Employee {

    public Integer getId();

    public void setId(Integer id);

    public String getFirstName();

    public void setFirstName(String firstName);
    
    public String getLastName();

    public void setLastName(String lastName);
    
    public void setEmail(String email);
    
    public String getEmail();

    public int getPriority();

    public void setPriority(int priority);
    
    public String getDesignation();

    public void setDesignation(String designation);

    public String toDisplayString();


}

&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;EmployeeImpl.java&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package com.jagadeesh.domain.impl;

import java.io.Serializable;

import com.jagadeesh.domain.Employee;
import com.jagadeesh.utils.EmployeeIO;

public class EmployeeImpl extends EmployeeIO 
 implements Employee,Serializable   {
    
    private static final long serialVersionUID = 1L;
   
    private Integer id;
    private String firstName;
    private String lastName;
    private String email;
    private int priority;
    private String designation;
   
    @Override
    public Integer getId() {
        return id;
    }
    
    @Override
    public void setId(Integer id) {
        this.id = id;
    }

    @Override
    public String getFirstName() {
        return firstName;
    }
    
    @Override
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    
    @Override
    public String getLastName() {
        return lastName;
    }
    
    @Override
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String getEmail() {
        return email;
    }

    @Override
    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public int getPriority() {
        return priority;
    }

    @Override
    public void setPriority(int priority) {
        this.priority = priority;
    }

    @Override
    public String getDesignation() {
        return designation;
    }

    @Override
    public void setDesignation(String designation) {
        if(&quot;CEO&quot;.equalsIgnoreCase(designation)){
            setPriority(1);
        }else if(&quot;MD&quot;.equalsIgnoreCase(designation)){
            setPriority(2);
        }else if(&quot;HR&quot;.equalsIgnoreCase(designation)){
            setPriority(3);
        }else{
            setPriority(4);
        }
        this.designation = designation;
    }
  
    @Override
    public String toString() {
        StringBuffer buffer = new StringBuffer();
        buffer.append(&quot;EmployeeImpl [id=&quot;);
        buffer.append(id);
        buffer.append(&quot;, firstName=&quot;);
        buffer.append(firstName);
        buffer.append(&quot;, lastName=&quot;);
        buffer.append(lastName);
        buffer.append(&quot;, email=&quot;);
        buffer.append(email);
        buffer.append(&quot;, priority=&quot;);
        buffer.append(priority);
        buffer.append(&quot;, designation=&quot;);
        buffer.append(designation);
        buffer.append(&quot;]&quot;);
        return buffer.toString();
    }
 
    @Override
    public boolean equals(Object object){
        if (object == null) return false;
        if (object == this) return true;
        if (this.getClass() != object.getClass())return false;
        Employee employee = (Employee)object;
        if(this.id.equals(employee.getId())
            &amp;amp;&amp;amp; this.firstName.equalsIgnoreCase( employee.getFirstName())
            &amp;amp;&amp;amp; this.lastName.equalsIgnoreCase( employee.getLastName())
            &amp;amp;&amp;amp; this.email.equalsIgnoreCase( employee.getEmail())
            &amp;amp;&amp;amp; this.designation.equalsIgnoreCase(employee.getDesignation()))
            return true;
       return false;
    }

    @Override
    public String toDisplayString() {
        StringBuffer buffer = new StringBuffer();
        buffer.append(this.getId());
        buffer.append(&quot;\t&quot;);
        buffer.append(this.getFirstName());
        buffer.append(&quot;\t&quot;);
        buffer.append(this.getLastName());
        buffer.append(&quot;\t&quot;);
        buffer.append(this.getEmail());
        buffer.append(&quot;\t&quot;);
        buffer.append(this.getDesignation());
        return buffer.toString();
    }    
}

&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;EmployeeService.java&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package com.jagadeesh.service;

import java.util.List;

import com.jagadeesh.domain.Employee;
import com.jagadeesh.exceptions.DuplicateIdException;
import com.jagadeesh.exceptions.PersistenceException;

public interface EmployeeService {

    List&amp;lt;Employee&amp;gt; getAll();
    
    List&amp;lt;Employee&amp;gt; readFromFile() throws PersistenceException;

    void addEmployee(Employee employee) throws DuplicateIdException,
            PersistenceException;

}

&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;EmployeeServiceImpl.java&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package com.jagadeesh.service.impl;

import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.jagadeesh.domain.Employee;
import com.jagadeesh.exceptions.DuplicateIdException;
import com.jagadeesh.exceptions.PersistenceException;
import com.jagadeesh.service.EmployeeService;

public class EmployeeServiceImpl implements EmployeeService {
    private List&amp;lt;Employee&amp;gt; employees = new ArrayList&amp;lt;Employee&amp;gt;();

    private List&amp;lt;Employee&amp;gt; employeesFromFile = new ArrayList&amp;lt;Employee&amp;gt;();

    public EmployeeServiceImpl() throws PersistenceException {
        this.employees = readFromFile();
    }

    @Override
    public List&amp;lt;Employee&amp;gt; getAll() {
        List&amp;lt;Employee&amp;gt; employees = new ArrayList&amp;lt;Employee&amp;gt;(this.employees);
        return Collections.unmodifiableList(employees);
    }

    @Override
    public void addEmployee(Employee employee) throws DuplicateIdException,
            PersistenceException {
        for (Employee emp : employees) {
            if (emp.getId() == employee.getId())
                throw new DuplicateIdException(employee.getId());
        }
        // saving employee object to file
        writeToFile(employee);
        this.employees.add(employee);
    }

    @Override
    public List&amp;lt;Employee&amp;gt; readFromFile() throws PersistenceException {
        ObjectInputStream objectInputStream = null;
        try {
            File file = new File(&quot;c://employees.txt&quot;);
            if (!file.exists()) {
                file.createNewFile();
            }
            objectInputStream = new ObjectInputStream(new FileInputStream(file));
            while (true) {
                Employee emp = (Employee) objectInputStream.readObject();
                employeesFromFile.add(emp);
            }
        } catch (EOFException e) {

        } catch (FileNotFoundException e) {
            throw new PersistenceException(e);
        } catch (IOException e) {
            throw new PersistenceException(e);
        } catch (ClassNotFoundException e) {
            throw new PersistenceException(e);
        } finally {
            if (objectInputStream != null) {
                try {
                    objectInputStream.close();
                } catch (IOException e) {
                    throw new PersistenceException(e);
                }
            }
        }
        return employeesFromFile;
    }


    private void writeToFile(Employee employee) throws PersistenceException {
        ObjectOutputStream objectOutputStream = null;
        try {
            File outFile = new File(&quot;c://employees.txt&quot;);
            objectOutputStream = getObjectStream(new FileOutputStream(outFile,
                    true), this.employees.isEmpty());
            objectOutputStream.writeObject(employee);
        } catch (FileNotFoundException e) {
            throw new PersistenceException(e);
        } catch (IOException e) {
            throw new PersistenceException(e);
        } finally {
            if (objectOutputStream != null) {
                try {
                    objectOutputStream.close();
                } catch (IOException e) {
                    throw new PersistenceException(e);
                }
            }
        }
    }
    
    private static ObjectOutputStream getObjectStream(OutputStream out,
            final boolean isNew) throws IOException {
        return new ObjectOutputStream(out) {
            @Override
            protected void writeStreamHeader() throws IOException {
                if (isNew) {
                    super.writeStreamHeader();
                }
            }
        };
    }

}

&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;EmployeeIO.java&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package com.jagadeesh.utils;

import java.util.List;

import com.jagadeesh.domain.Employee;
import com.jagadeesh.domain.impl.EmployeeImpl;


public class EmployeeIO {

    public static Employee read() {
        Employee employee = new EmployeeImpl();
        employee.setId(KeyBoard.readInt(&quot;Enter Id :&quot;));
        employee.setFirstName(KeyBoard.read(&quot;Enter First Name :&quot;));
        employee.setLastName(KeyBoard.read(&quot;Enter Last Name :&quot;));
        employee.setEmail(KeyBoard.read(&quot;Enter Email :&quot;));
        employee.setDesignation(KeyBoard.read(&quot;Enter Designation :&quot;));        
        return employee;
    }
    
    public static void out(List&amp;lt;Employee&amp;gt; employees) {
        StringBuilder builder = new StringBuilder();
        builder.append(&quot;Id\t\tFirst Name\t\tLast Name\t\tEmail\ttDesignation\n&quot;);
        for(int i = 0; i &amp;lt; employees.size(); i++) {
            builder.append(employees.get(i).toDisplayString());
            builder.append(&quot;\n&quot;);
        }
        System.out.println(builder);
    }
}

&lt;/pre&gt;&lt;b&gt;KeyBoard.java&lt;/b&gt;  &lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package com.jagadeesh.utils;

import java.util.Scanner;

public class KeyBoard {
  
    public static int readInt(String message) {
        System.out.print(message);
        Scanner scanner = new Scanner(System.in);
        try {
            int number = Integer.parseInt(scanner.next());
            return number;
        }
        catch(NumberFormatException e) {
            System.out.println(&quot;Invalid Number&quot;);
            return readInt(message);
        }            
    }
    
    public static String read(String message) {
        System.out.print(message);
        Scanner scanner = new Scanner(System.in);
        return scanner.nextLine();
    }    
}

&lt;/pre&gt;&lt;b&gt;DuplicateIdException.java&lt;/b&gt;  &lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package com.jagadeesh.exceptions;

public class DuplicateIdException extends Exception {

 private static final long serialVersionUID = 1L;

 private int id;

 public DuplicateIdException(int id) {
  this.id = id;
 }

 public String toString() {
  return &quot;Duplicate Employee Id.. &quot; + id;
 }
}
&amp;nbsp;&lt;/pre&gt;&lt;b&gt;PersistanceException.java&lt;/b&gt;  &lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package com.jagadeesh.exceptions;

public class PersistenceException extends Exception {
    
    private static final long serialVersionUID = 1L;

    public PersistenceException() {
        super();
    }
    public PersistenceException(Exception e) {
        super(e);
    }
    public PersistenceException(String message, Exception e) {
        super(message, e);
    }
    
}

&lt;/pre&gt;&lt;b&gt;EmployeeMain.java&lt;/b&gt;  &lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package com.jagadeesh.main;

import com.jagadeesh.domain.Employee;
import com.jagadeesh.exceptions.DuplicateIdException;
import com.jagadeesh.exceptions.PersistenceException;
import com.jagadeesh.service.EmployeeService;
import com.jagadeesh.service.impl.EmployeeServiceImpl;
import com.jagadeesh.utils.EmployeeIO;
import com.jagadeesh.utils.KeyBoard;


public class EmployeeMain {

    public static void main(String[] args) throws PersistenceException {
        int option = 1;
        EmployeeService empService = new EmployeeServiceImpl();
        do {
            Employee employee = EmployeeIO.read();
            try{
                empService.addEmployee(employee);
            }catch(DuplicateIdException e){
                System.out.println(&quot;Duplicate Id&quot;);
            } catch (PersistenceException e) {
               System.out.println(&quot;Persistence error&quot;);
            }
            option = KeyBoard.readInt(
                    &quot;Do you want add another employee(1/0) :&quot;);
            
        } while(option == 1);
        System.out.println(&quot;Reading from file&quot;);
        EmployeeIO.out(empService.getAll());
    }
}
&lt;/pre&gt;&lt;b&gt;Output of the programe&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
When we run this program first time it creates employees file and all employees will be stored into that file&lt;br /&gt;
&lt;pre class=&quot;brush:text&quot;&gt;Enter Id :1
Enter First Name :jagadeesh
Enter Last Name :kumar
Enter Email :mannejkumar@gmail.com
Enter Designation :developer
Do you want add another employee(1/0) :1
Enter Id :2
Enter First Name :kumar
Enter Last Name :jagadeesh
Enter Email :k.manne@yahoo.com
Enter Designation :developer
Do you want add another employee(1/0) :0
Reading from file
Id  First Name  Last Name  Email tDesignation
1 jagadeesh kumar mannejkumar@gmail.com developer
2 kumar jagadeesh k.manne@yahoo.com developer

&lt;/pre&gt;when we run this program second time we read all employee objects from file in EmployeeServiceImpl constructor.after that we will add new employees to that file.&lt;br /&gt;
we will get following output when we add one more employee.&lt;br /&gt;
&lt;pre class=&quot;brush:text&quot;&gt;Enter Id :3
Enter First Name :myrmidons
Enter Last Name :co.in
Enter Email :mannejkumar@gmail.com
Enter Designation :developer
Do you want add another employee(1/0) :0

Reading from file
Id  First Name  Last Name  Email tDesignation
1 jagadeesh kumar mannejkumar@gmail.com developer
2 kumar jagadeesh k.manne@yahoo.com developer
3 myrmidons co.in mannejkumar@gmail.com developer
&lt;/pre&gt;&lt;/div&gt;</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/8135594905787953578'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/8135594905787953578'/><link rel='alternate' type='text/html' href='http://jagadeeshmanne.blogspot.com/2011/12/core-java-reading-and-writing-object-to.html' title='Core Java: Reading and Writing Object to a File (IOStreams and Exceptions)'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/09122533940640970927</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh5VPAlS4XAejb11_onkMawdc4vt66xD80npqhi_AgA94A9Ef4-JpCCsNPVPBCbnD0xAwy-EtqKK_nWuvDeai3FKB5W4SXyaG8CzGAvlmR7SO2ajdTHqUUfCdIlrc9jUUt712IzfW9K78s/s72-c/iostreams.png" height="72" width="72"/></entry><entry><id>tag:blogger.com,1999:blog-1889673847048308806.post-2163113750540545470</id><published>2011-12-03T22:04:00.000-08:00</published><updated>2011-12-20T23:15:57.031-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Core Java"/><title type='text'>Core java: Sorting List elements using Comparator example</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;Comparator example using Map and HashMap and List: adding employees and displaying employees in sorting order. Here i am providing download link for this example. If free hosting site deletes that file drop your mail id to get this example.&lt;br /&gt;
&lt;br /&gt;
&lt;a href=&quot;http://www.mediafire.com/?vczsu69lxd3o84g&quot; target=&quot;_blank&quot;&gt;download Sorting List of Ojbects using Comparator example&lt;/a&gt;&amp;nbsp;open it with eclipse and execute main method&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjBCMlptkCBYGJJWtFjsRA3jaQwqIojSfalM9A0_7a9zvFRF4ZJcjHh1r8x8ogP2MpD4cSwkcUXTr3HVJqsaYZEk0sBGxL18now25BPJJKyFMwiJSxaaYkKQZUa5IO4x36iMIO-MLHeUKw/s1600/comparator.png&quot; imageanchor=&quot;1&quot; rel=&quot;lightbox&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;320&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjBCMlptkCBYGJJWtFjsRA3jaQwqIojSfalM9A0_7a9zvFRF4ZJcjHh1r8x8ogP2MpD4cSwkcUXTr3HVJqsaYZEk0sBGxL18now25BPJJKyFMwiJSxaaYkKQZUa5IO4x36iMIO-MLHeUKw/s320/comparator.png&quot; width=&quot;297&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Employee.java&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package domain;

public interface Employee {

    public Integer getId();

    public void setId(Integer id);

    public String getFirstName();

    public void setFirstName(String firstName);
    
    public String getLastName();

    public void setLastName(String lastName);
    
    public void setEmail(String email);
    
    public String getEmail();

    public int getPriority();

    public void setPriority(int priority);
    
    public String getDesignation();

    public void setDesignation(String designation);

    public String toDisplayString();

}

&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;EmployeeImpl.java&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package domain.impl;

import utils.EmployeeIO;
import domain.Employee;

public class EmployeeImpl extends EmployeeIO implements Employee{
    
    private Integer id;
    private String firstName;
    private String lastName;
    private String email;
    private int priority;
    private String designation;
  
    @Override
    public Integer getId() {
        return id;
    }
    
    @Override
    public void setId(Integer id) {
        this.id = id;
    }

    @Override
    public String getFirstName() {
        return firstName;
    }
    
    @Override
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    
    @Override
    public String getLastName() {
        return lastName;
    }
    
    @Override
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String getEmail() {
        return email;
    }

    @Override
    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public int getPriority() {
        return priority;
    }

    @Override
    public void setPriority(int priority) {
        this.priority = priority;
    }

    @Override
    public String getDesignation() {
        return designation;
    }

    @Override
    public void setDesignation(String designation) {
        if(&quot;CEO&quot;.equalsIgnoreCase(designation)){
            setPriority(1);
        }else if(&quot;MD&quot;.equalsIgnoreCase(designation)){
            setPriority(2);
        }else if(&quot;HR&quot;.equalsIgnoreCase(designation)){
            setPriority(3);
        }else{
            setPriority(4);
        }
        this.designation = designation;
    }
  
    @Override
    public String toString() {
        StringBuffer buffer = new StringBuffer();
        buffer.append(&quot;EmployeeImpl [id=&quot;);
        buffer.append(id);
        buffer.append(&quot;, firstName=&quot;);
        buffer.append(firstName);
        buffer.append(&quot;, lastName=&quot;);
        buffer.append(lastName);
        buffer.append(&quot;, email=&quot;);
        buffer.append(email);
        buffer.append(&quot;, priority=&quot;);
        buffer.append(priority);
        buffer.append(&quot;, designation=&quot;);
        buffer.append(designation);
        buffer.append(&quot;]&quot;);
        return buffer.toString();
    }
   
    @Override
    public boolean equals(Object object){
        if (object == null) return false;
        if (object == this) return true;
        if (this.getClass() != object.getClass())return false;
        Employee employee = (Employee)object;
        if(this.id.equals(employee.getId())
            &amp;amp;&amp;amp; this.firstName.equalsIgnoreCase( employee.getFirstName())
            &amp;amp;&amp;amp; this.lastName.equalsIgnoreCase( employee.getLastName())
            &amp;amp;&amp;amp; this.email.equalsIgnoreCase( employee.getEmail())
            &amp;amp;&amp;amp; this.designation.equalsIgnoreCase(employee.getDesignation()))
            return true;
        if(this.hashCode()== employee.hashCode())return true;
       return false;
    }

    @Override
    public String toDisplayString() {
        StringBuffer buffer = new StringBuffer();
        buffer.append(this.getId());
        buffer.append(&quot;\t&quot;);
        buffer.append(this.getFirstName());
        buffer.append(&quot;\t&quot;);
        buffer.append(this.getLastName());
        buffer.append(&quot;\t&quot;);
        buffer.append(this.getEmail());
        buffer.append(&quot;\t&quot;);
        buffer.append(this.getDesignation());
        return buffer.toString();
    }    
}

&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;EmployeeService.java&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package service;

import java.util.List;

import domain.Employee;

public interface EmployeeService {

    List&amp;lt;Employee&amp;gt; getAll();

    void addEmployee(Employee employee);
 
    List&amp;lt;Employee&amp;gt; getAll(String sortBy);

}
&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;EmployeeServiceImpl.java&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import service.EmployeeService;
import domain.Employee;

public class EmployeeServiceImpl implements EmployeeService {
    private List&amp;lt;Employee&amp;gt; employees = new ArrayList&amp;lt;Employee&amp;gt;();

    private static Map&amp;lt;String, Comparator&amp;lt;Employee&amp;gt;&amp;gt; 
   COMPARATORS = new HashMap&amp;lt;String, Comparator&amp;lt;Employee&amp;gt;&amp;gt;();

    static {
        COMPARATORS.put(&quot;firstName&quot;, new Comparator&amp;lt;Employee&amp;gt;() {
            public int compare(Employee emp1, Employee emp2) {
                return emp1.getFirstName().compareTo(emp2.getFirstName());
            }
        });
        COMPARATORS.put(&quot;lastName&quot;, new Comparator&amp;lt;Employee&amp;gt;() {
            public int compare(Employee emp1, Employee emp2) {
                return emp1.getLastName().compareTo(emp2.getLastName());
            }
        });
        COMPARATORS.put(&quot;email&quot;, new Comparator&amp;lt;Employee&amp;gt;() {
            public int compare(Employee emp1, Employee emp2) {
                return emp1.getEmail().compareTo(emp2.getEmail());
            }
        });
        COMPARATORS.put(&quot;designation&quot;, new Comparator&amp;lt;Employee&amp;gt;() {
            public int compare(Employee emp1, Employee emp2) {
                return emp1.getPriority() - emp2.getPriority();
            }
        });
        COMPARATORS.put(&quot;id&quot;, new Comparator&amp;lt;Employee&amp;gt;() {
            public int compare(Employee emp1, Employee emp2) {
                return emp1.getId() - emp2.getId();
            }
        });
    }

   @Override
    public List&amp;lt;Employee&amp;gt; getAll() {
        List&amp;lt;Employee&amp;gt; employees = new ArrayList&amp;lt;Employee&amp;gt;(this.employees);
        return Collections.unmodifiableList(employees);
    }

    @Override
    public List&amp;lt;Employee&amp;gt; getAll(String sortBy) {
        Comparator&amp;lt;Employee&amp;gt; comparator = COMPARATORS.get(sortBy);
        if (comparator == null) {
            throw new IllegalArgumentException(&quot;Invalid sortBy option: &quot;
                    + sortBy);
        }
        List&amp;lt;Employee&amp;gt; sortedEmployees = new ArrayList&amp;lt;Employee&amp;gt;(this.employees);
        Collections.sort(sortedEmployees, comparator);
        return sortedEmployees;
    }

    @Override
 public void addEmployee(Employee employee) {
  if (employees.contains(employee)) {
   System.out.println(&quot;Employee already exists&quot;);
  } else {
   this.employees.add(employee);
  }
 }
}

&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;EmployeeIO.java&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package utils;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import domain.Employee;
import domain.impl.EmployeeImpl;

public class EmployeeIO {

 public static Employee read() {
  Employee employee = new EmployeeImpl();
  employee.setId(KeyBoard.readInt(&quot;Enter Id :&quot;));
  employee.setFirstName(KeyBoard.read(&quot;Enter First Name :&quot;));
  employee.setLastName(KeyBoard.read(&quot;Enter Last Name :&quot;));
  employee.setEmail(KeyBoard.read(&quot;Enter Email :&quot;));
  employee.setDesignation(KeyBoard.read(&quot;Enter Designation :&quot;));
  return employee;
 }

 public static void out(List&amp;lt;Employee&amp;gt; employees) {
  StringBuilder builder = new StringBuilder();
  builder.append(&quot;Id\t\tFirst Name\t\tLast Name\t\tEmail\ttDesignation\n&quot;);
  for (int i = 0; i &amp;lt; employees.size(); i++) {
   builder.append(employees.get(i).toDisplayString());
   builder.append(&quot;\n&quot;);
  }
  System.out.println(builder);
 }
 
 public static String sortOptions(){
        Map&amp;lt;String, String&amp;gt; sortOptions = 
            new LinkedHashMap&amp;lt;String, String&amp;gt;();
        sortOptions.put(&quot;firstName&quot;, &quot;Sort by First Name&quot;);
        sortOptions.put(&quot;lastName&quot;, &quot;Sort by Last Name&quot;);
        sortOptions.put(&quot;email&quot;, &quot;Sort by Email&quot;);
        sortOptions.put(&quot;designation&quot;, &quot;Sort by Designation&quot;);
        sortOptions.put(&quot;id&quot;, &quot;Sort by id&quot;);
        return options(sortOptions);
    }
    
    public static String options(Map&amp;lt;String, String&amp;gt; options) {
        StringBuilder builder = new StringBuilder();
        Map&amp;lt;Integer, String&amp;gt; myOptions = new HashMap&amp;lt;Integer,String&amp;gt;();
        
        Set&amp;lt;Entry&amp;lt;String,String&amp;gt;&amp;gt; entrySet = options.entrySet();
        int i = 0;
        for (Entry&amp;lt;String, String&amp;gt; entry : entrySet) {
            builder.append(++i).append(&quot;. &quot;).append(entry.getValue());
            builder.append(&quot;\n&quot;);
            myOptions.put(i, entry.getKey());
        }
        System.out.print(builder.toString());
        int option = KeyBoard.readInt(&quot;Enter your Choice:&quot;);
        return myOptions.get(option);
    }
   
}


&lt;/pre&gt;&lt;b&gt;KeyBoard.java&lt;/b&gt;  &lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package utils;

import java.util.Scanner;

public class KeyBoard {
  
    public static int readInt(String message) {
        System.out.print(message);
        Scanner scanner = new Scanner(System.in);
        try {
            int number = Integer.parseInt(scanner.next());
            return number;
        }
        catch(NumberFormatException e) {
            System.out.println(&quot;Invalid Number&quot;);
            return readInt(message);
        }            
    }
    
    public static String read(String message) {
        System.out.print(message);
        Scanner scanner = new Scanner(System.in);
        return scanner.nextLine();
    }    
}

&lt;/pre&gt;&lt;b&gt;EmployeeMain.java&lt;/b&gt;  &lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package main;

import service.EmployeeService;
import service.impl.EmployeeServiceImpl;
import utils.EmployeeIO;
import utils.KeyBoard;
import domain.Employee;

public class EmployeeMain {

    public static void main(String[] args){
        int option = 1;
        EmployeeService empService = new EmployeeServiceImpl();
        do {
            Employee employee = EmployeeIO.read();
            empService.addEmployee(employee);
            option = KeyBoard.readInt(
                    &quot;Do you want add another employee(1/0) :&quot;);
            
        } while(option == 1);
        System.out.println(&quot;Reading from file&quot;);
        EmployeeIO.out(empService.getAll());
        String sortBy = EmployeeIO.sortOptions();
        try{
            EmployeeIO.out(empService.getAll(sortBy));
        }catch(IllegalArgumentException e){
            System.out.println(&quot;Invalid sort option: &quot;+sortBy);
        }
    }
}

&lt;/pre&gt;&lt;b&gt;Output of the programe&lt;/b&gt;&lt;br /&gt;
&lt;pre class=&quot;brush:text&quot;&gt;Enter Id :1
Enter First Name :eeee
Enter Last Name :ffff
Enter Email :eeff@gmail.com
Enter Designation :developer
Do you want add another employee(1/0) :1
Enter Id :bbbb
Invalid Number
Enter Id :6
Enter First Name :bbbb
Enter Last Name :dddd
Enter Email :ddbb@gmail.com
Enter Designation :hr
Do you want add another employee(1/0) :1
Enter Id :3
Enter First Name :hhhh
Enter Last Name :llll
Enter Email :hlhl@gmail.com
Enter Designation :ceo
Do you want add another employee(1/0) :1
Enter Id :8
Enter First Name :kkkkk
Enter Last Name :aaaa
Enter Email :kaka@gmail.com
Enter Designation :pm
Do you want add another employee(1/0) :0
Reading from file
Id First Name Last Name Email Designation
1 eeee ffff eeff@gmail.com developer
6 bbbb dddd ddbb@gmail.com hr
3 hhhh llll hlhl@gmail.com ceo
8 kkkkk aaaa kaka@gmail.com pm

1. Sort by First Name
2. Sort by Last Name
3. Sort by Email
4. Sort by Designation
5. Sort by id
Enter your Choice:2
Id First Name Last Name Email Designation
8 kkkkk aaaa kaka@gmail.com pm
6 bbbb dddd ddbb@gmail.com hr
1 eeee ffff eeff@gmail.com developer
3 hhhh llll hlhl@gmail.com ceo
&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;/div&gt;</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/2163113750540545470'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/2163113750540545470'/><link rel='alternate' type='text/html' href='http://jagadeeshmanne.blogspot.com/2011/12/core-java-sorting-list-elements-using.html' title='Core java: Sorting List elements using Comparator example'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/09122533940640970927</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjBCMlptkCBYGJJWtFjsRA3jaQwqIojSfalM9A0_7a9zvFRF4ZJcjHh1r8x8ogP2MpD4cSwkcUXTr3HVJqsaYZEk0sBGxL18now25BPJJKyFMwiJSxaaYkKQZUa5IO4x36iMIO-MLHeUKw/s72-c/comparator.png" height="72" width="72"/></entry><entry><id>tag:blogger.com,1999:blog-1889673847048308806.post-1507074338535177792</id><published>2011-12-03T06:44:00.000-08:00</published><updated>2011-12-20T23:16:11.044-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Core Java"/><title type='text'>Core Java : Map and HashMap example</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;Map and HashMap Example: adding employees to map by designation. and getting employees&lt;br /&gt;
by designation. I am providing downloading link for this example. If file is deleted from hosting site drop your mail id to get this example&lt;br /&gt;
&lt;br /&gt;
&lt;a href=&quot;http://www.mediafire.com/?3u1p1qpq52lh8y4&quot; target=&quot;_blank&quot;&gt;download Map and HashMap example&lt;/a&gt;&amp;nbsp;open it with eclipse and run main method to execute&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhMfdn2dNrQKQbMHDmZhD-iMCInL6MjUmzy3w9E2mGqOYmHou9aDSWr6MGdXKOap8P5VROov4-s1ufO32Q8S1h-V9RHyirjA5gT392lp4aZUnRqDHoxTYKO_Dp-rgkEtNvJB8Rhs3_h_O8/s1600/hashmap.png&quot; imageanchor=&quot;1&quot; rel=&quot;lightbox&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;320&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhMfdn2dNrQKQbMHDmZhD-iMCInL6MjUmzy3w9E2mGqOYmHou9aDSWr6MGdXKOap8P5VROov4-s1ufO32Q8S1h-V9RHyirjA5gT392lp4aZUnRqDHoxTYKO_Dp-rgkEtNvJB8Rhs3_h_O8/s320/hashmap.png&quot; width=&quot;310&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Employee.java&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package domain;

public interface Employee {

    public Integer getId();

    public void setId(Integer id);

    public String getFirstName();

    public void setFirstName(String firstName);
    
    public String getLastName();

    public void setLastName(String lastName);
    
    public void setEmail(String email);
    
    public String getEmail();

    public int getPriority();

    public void setPriority(int priority);
    
    public String getDesignation();

    public void setDesignation(String designation);

    public String toDisplayString();

}

&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;EmployeeImpl.java&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package domain.impl;

import java.io.Serializable;

import utils.EmployeeIO;
import domain.Employee;

public class EmployeeImpl extends EmployeeIO implements Employee{
    
    private static final long serialVersionUID = 1L;
   
    private Integer id;
    private String firstName;
    private String lastName;
    private String email;
    private int priority;
    private String designation;

    @Override
    public Integer getId() {
        return id;
    }
    
    @Override
    public void setId(Integer id) {
        this.id = id;
    }

    @Override
    public String getFirstName() {
        return firstName;
    }
    
    @Override
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    
    @Override
    public String getLastName() {
        return lastName;
    }
    
    @Override
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String getEmail() {
        return email;
    }

    @Override
    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public int getPriority() {
        return priority;
    }

    @Override
    public void setPriority(int priority) {
        this.priority = priority;
    }

    @Override
    public String getDesignation() {
        return designation;
    }

    @Override
    public void setDesignation(String designation) {
        if(&quot;CEO&quot;.equalsIgnoreCase(designation)){
            setPriority(1);
        }else if(&quot;MD&quot;.equalsIgnoreCase(designation)){
            setPriority(2);
        }else if(&quot;HR&quot;.equalsIgnoreCase(designation)){
            setPriority(3);
        }else{
            setPriority(4);
        }
        this.designation = designation;
    }
  
    @Override
    public String toString() {
        StringBuffer buffer = new StringBuffer();
        buffer.append(&quot;EmployeeImpl [id=&quot;);
        buffer.append(id);
        buffer.append(&quot;, firstName=&quot;);
        buffer.append(firstName);
        buffer.append(&quot;, lastName=&quot;);
        buffer.append(lastName);
        buffer.append(&quot;, email=&quot;);
        buffer.append(email);
        buffer.append(&quot;, priority=&quot;);
        buffer.append(priority);
        buffer.append(&quot;, designation=&quot;);
        buffer.append(designation);
        buffer.append(&quot;]&quot;);
        return buffer.toString();
    }

    @Override
    public boolean equals(Object object){
        if (object == null) return false;
        if (object == this) return true;
        if (this.getClass() != object.getClass())return false;
        Employee employee = (Employee)object;
        if(this.id.equals(employee.getId())
            &amp;amp;&amp;amp; this.firstName.equalsIgnoreCase( employee.getFirstName())
            &amp;amp;&amp;amp; this.lastName.equalsIgnoreCase( employee.getLastName())
            &amp;amp;&amp;amp; this.email.equalsIgnoreCase( employee.getEmail())
            &amp;amp;&amp;amp; this.designation.equalsIgnoreCase(employee.getDesignation()))
            return true;
       return false;
    }

    @Override
    public String toDisplayString() {
        StringBuffer buffer = new StringBuffer();
        buffer.append(this.getId());
        buffer.append(&quot;\t&quot;);
        buffer.append(this.getFirstName());
        buffer.append(&quot;\t&quot;);
        buffer.append(this.getLastName());
        buffer.append(&quot;\t&quot;);
        buffer.append(this.getEmail());
        buffer.append(&quot;\t&quot;);
        buffer.append(this.getDesignation());
        return buffer.toString();
    }    
}

&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;EmployeeService.java&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package service;

import java.util.List;

import domain.Employee;

public interface EmployeeService {

    List&amp;lt;Employee&amp;gt; getAll();

    List&amp;lt;Employee&amp;gt; getByDesignation(String designation);

    void addEmployee(Employee employee);

}
&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;EmployeeServiceImpl.java&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import service.EmployeeService;

import domain.Employee;

public class EmployeeServiceImpl implements EmployeeService {
 private List&amp;lt;Employee&amp;gt; employees = new ArrayList&amp;lt;Employee&amp;gt;();

 private Map&amp;lt;String, List&amp;lt;Employee&amp;gt;&amp;gt; employeesByDesig 
     = new HashMap&amp;lt;String, List&amp;lt;Employee&amp;gt;&amp;gt;();

 @Override
 public List&amp;lt;Employee&amp;gt; getAll() {
  List&amp;lt;Employee&amp;gt; employees = new ArrayList&amp;lt;Employee&amp;gt;(this.employees);
  return Collections.unmodifiableList(employees);
 }

 @Override
 public List&amp;lt;Employee&amp;gt; getByDesignation(String designation) {
  List&amp;lt;Employee&amp;gt; empsByDesig = employeesByDesig.get(designation);
  if (empsByDesig == null) {
   throw new IllegalArgumentException(&quot;Invalid Designation: &quot;
     + designation);
  }
  return empsByDesig;
 }

 @Override
 public void addEmployee(Employee employee) {
  if (employees.contains(employee)) {
   System.out.println(&quot;Employee already exists&quot;);
  } else {
   this.employees.add(employee);
   saveEmployeesbyDesig(employee);
  }

 }

 private void saveEmployeesbyDesig(Employee employee) {
  String designation = employee.getDesignation();
  List&amp;lt;Employee&amp;gt; employeesList = this.employeesByDesig.get(designation);
  if (employeesList == null) {
   employeesList = new ArrayList&amp;lt;Employee&amp;gt;();
  }
  employeesList.add(employee);
  this.employeesByDesig.put(designation, employeesList);
 }

}

&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;EmployeeIO.java&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package utils;

import java.util.List;

import domain.Employee;
import domain.impl.EmployeeImpl;

public class EmployeeIO {

 public static Employee read() {
  Employee employee = new EmployeeImpl();
  employee.setId(KeyBoard.readInt(&quot;Enter Id :&quot;));
  employee.setFirstName(KeyBoard.read(&quot;Enter First Name :&quot;));
  employee.setLastName(KeyBoard.read(&quot;Enter Last Name :&quot;));
  employee.setEmail(KeyBoard.read(&quot;Enter Email :&quot;));
  employee.setDesignation(KeyBoard.read(&quot;Enter Designation :&quot;));
  return employee;
 }

 public static void out(List&amp;lt;Employee&amp;gt; employees) {
  StringBuilder builder = new StringBuilder();
  builder.append(&quot;Id\t\tFirst Name\t\tLast Name\t\tEmail\ttDesignation\n&quot;);
  for (int i = 0; i &amp;lt; employees.size(); i++) {
   builder.append(employees.get(i).toDisplayString());
   builder.append(&quot;\n&quot;);
  }
  System.out.println(builder);
 }

}

&lt;/pre&gt;&lt;b&gt;KeyBoard.java&lt;/b&gt;  &lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package utils;

import java.util.Scanner;

public class KeyBoard {
  
    public static int readInt(String message) {
        System.out.print(message);
        Scanner scanner = new Scanner(System.in);
        try {
            int number = Integer.parseInt(scanner.next());
            return number;
        }
        catch(NumberFormatException e) {
            System.out.println(&quot;Invalid Number&quot;);
            return readInt(message);
        }            
    }
    
    public static String read(String message) {
        System.out.print(message);
        Scanner scanner = new Scanner(System.in);
        return scanner.nextLine();
    }    
}

&lt;/pre&gt;&lt;b&gt;EmployeeMain.java&lt;/b&gt;  &lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package utils;

package main;

import service.EmployeeService;
import service.impl.EmployeeServiceImpl;
import utils.EmployeeIO;
import utils.KeyBoard;
import domain.Employee;

public class EmployeeMain {

 public static void main(String[] args) {
  int option = 1;
  EmployeeService empService = new EmployeeServiceImpl();
  do {
   Employee employee = EmployeeIO.read();
   empService.addEmployee(employee);
   option = KeyBoard
     .readInt(&quot;Do you want add another employee(1/0) :&quot;);

  } while (option == 1);
  System.out.println(&quot;Employees list :&quot;);
  EmployeeIO.out(empService.getAll());
  String byDesig = KeyBoard.read(&quot;Enter Designation : &quot;);
  try {
   EmployeeIO.out(empService.getByDesignation(byDesig));
  } catch (IllegalArgumentException e) {
   System.out.println(&quot;Invalid designation : &quot; + byDesig);
  }
 }
}



&lt;/pre&gt;&lt;b&gt;Output of the programe&lt;/b&gt; &lt;br /&gt;
&lt;pre class=&quot;brush:text&quot;&gt;Enter Id :1
Enter First Name :jagadeesh
Enter Last Name :kumar
Enter Email :mannejkumar@gmail.com
Enter Designation :developer
Do you want add another employee(1/0) :1
Enter Id :1
Enter First Name :jagadeesh
Enter Last Name :kumar
Enter Email :mannejkumar@gmail.com
Enter Designation :developer
Employee already exists
Do you want add another employee(1/0) :1
Enter Id :2
Enter First Name :jagadeesh
Enter Last Name :kumar
Enter Email :admin@myrmidons.co.in
Enter Designation :hr
Do you want add another employee(1/0) :1
Enter Id :3
Enter First Name :kumar
Enter Last Name :jagadeesh
Enter Email :jk.manne@yahoo.com
Enter Designation :programmer
Do you want add another employee(1/0) :1
Enter Id :4
Enter First Name :jagadeesh
Enter Last Name :kumar
Enter Email :admin@myrmidons.co.in
Enter Designation :ceo
Do you want add another employee(1/0) :1
Enter Id :5
Enter First Name :anil
Enter Last Name :kumar
Enter Email :testtest@gmail.com
Enter Designation :hr
Do you want add another employee(1/0) :1
Enter Id :6
Enter First Name :kumar
Enter Last Name :anil
Enter Email :test@gmail.com
Enter Designation :hr
Do you want add another employee(1/0) :0
Employees list :
Id First Name Last Name Email                Designation
1 jagadeesh kumar         mannejkumar@gmail.com developer
2 jagadeesh kumar         admin@myrmidons.co.in hr
3 kumar        jagadeesh jk.manne@yahoo.com programmer
4 jagadeesh kumar         admin@myrmidons.co.in ceo
5 anil         kumar         testtest@gmail.com hr
6 kumar         anil         test@gmail.com         hr

Enter Designation : hr
Id First Name Last Name Email                 Designation
2 jagadeesh kumar         admin@myrmidons.co.in hr
5 anil         kumar         testtest@gmail.com hr
6 kumar         anil         test@gmail.com         hr
&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;/div&gt;</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/1507074338535177792'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/1507074338535177792'/><link rel='alternate' type='text/html' href='http://jagadeeshmanne.blogspot.com/2011/12/core-java-map-and-hashmap-example.html' title='Core Java : Map and HashMap example'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/09122533940640970927</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhMfdn2dNrQKQbMHDmZhD-iMCInL6MjUmzy3w9E2mGqOYmHou9aDSWr6MGdXKOap8P5VROov4-s1ufO32Q8S1h-V9RHyirjA5gT392lp4aZUnRqDHoxTYKO_Dp-rgkEtNvJB8Rhs3_h_O8/s72-c/hashmap.png" height="72" width="72"/></entry><entry><id>tag:blogger.com,1999:blog-1889673847048308806.post-5419951622307613517</id><published>2011-12-01T06:24:00.000-08:00</published><updated>2011-12-20T23:16:25.391-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Core Java"/><title type='text'>Core Java : Set and HashSet example</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;Set and HashSet Example: adding employees to set and removing duplicates&amp;nbsp;from set. While adding verify the same employee already exists or not by&amp;nbsp;calling contains method and overriding the equals method and hashcode method.&amp;nbsp;contains method calls equals method internally. equals method calls hashcode method.&lt;br /&gt;
if name, id, designation, email everthing same then i am treating it as duplicate. &lt;br /&gt;
&lt;br /&gt;
&lt;a href=&quot;http://www.mediafire.com/?x6yxrndlev8ap1x&quot; target=&quot;_blank&quot;&gt;download Set and HashSet example&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhnCZ1Bh06Ld2gVLkPBJn88qVxorsbpOOjqPlKu-htUfTqUnep5l0rDJ-4K2x_8XYjz4u5XC6mD9q1_9hC8h2Xy18w1RcFPMZ5xjJmgcj5T3MTdmcqilXXQHBhmcHZs7sAzmOeCGb2lwrE/s1600/Hashset.png&quot; imageanchor=&quot;1&quot; rel=&quot;lightbox&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhnCZ1Bh06Ld2gVLkPBJn88qVxorsbpOOjqPlKu-htUfTqUnep5l0rDJ-4K2x_8XYjz4u5XC6mD9q1_9hC8h2Xy18w1RcFPMZ5xjJmgcj5T3MTdmcqilXXQHBhmcHZs7sAzmOeCGb2lwrE/s1600/Hashset.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Employee.java&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package com.jagadeesh.domain;

public interface Employee {

    public Integer getId();

    public void setId(Integer id);

    public String getFirstName();

    public void setFirstName(String firstName);
    
    public String getLastName();

    public void setLastName(String lastName);
    
    public void setEmail(String email);
    
    public String getEmail();

    public int getPriority();

    public void setPriority(int priority);
    
    public String getDesignation();

    public void setDesignation(String designation);

    public String toDisplayString();
}
&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;EmployeeImpl.java&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package com.jagadeesh.domain.impl;

import java.io.Serializable;

import com.jagadeesh.domain.Employee;
import com.jagadeesh.utils.EmployeeIO;

public class EmployeeImpl extends EmployeeIO implements Employee {

 private static final long serialVersionUID = 5058287999709032283L;

 private Integer id;
 private String firstName;
 private String lastName;
 private String email;
 private int priority;
 private String designation;

 @Override
 public Integer getId() {
  return id;
 }

 @Override
 public void setId(Integer id) {
  this.id = id;
 }

 @Override
 public String getFirstName() {
  return firstName;
 }

 @Override
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 @Override
 public String getLastName() {
  return lastName;
 }

 @Override
 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 @Override
 public String getEmail() {
  return email;
 }

 @Override
 public void setEmail(String email) {
  this.email = email;
 }

 @Override
 public int getPriority() {
  return priority;
 }

 @Override
 public void setPriority(int priority) {
  this.priority = priority;
 }

 @Override
 public String getDesignation() {
  return designation;
 }

 @Override
 public void setDesignation(String designation) {
  if (&quot;CEO&quot;.equalsIgnoreCase(designation)) {
   setPriority(1);
  } else if (&quot;MD&quot;.equalsIgnoreCase(designation)) {
   setPriority(2);
  } else if (&quot;HR&quot;.equalsIgnoreCase(designation)) {
   setPriority(3);
  } else {
   setPriority(4);
  }
  this.designation = designation;
 }

 @Override
 public String toString() {
  StringBuffer buffer = new StringBuffer();
  buffer.append(&quot;EmployeeImpl [id=&quot;);
  buffer.append(id);
  buffer.append(&quot;, firstName=&quot;);
  buffer.append(firstName);
  buffer.append(&quot;, lastName=&quot;);
  buffer.append(lastName);
  buffer.append(&quot;, email=&quot;);
  buffer.append(email);
  buffer.append(&quot;, priority=&quot;);
  buffer.append(priority);
  buffer.append(&quot;, designation=&quot;);
  buffer.append(designation);
  buffer.append(&quot;]&quot;);
  return buffer.toString();
 }

 @Override
 public boolean equals(Object object) {
  Employee employee = (Employee) object;
  if (this.hashCode() == employee.hashCode())
   return true;
  return false;
 }
 
  @Override
  public int hashCode(){
        StringBuffer buffer = new StringBuffer();
        buffer.append(this.id);
        buffer.append(this.firstName.hashCode());
        buffer.append(this.lastName.hashCode());
        buffer.append(this.email.hashCode());
        buffer.append(this.designation.hashCode());
        System.out.println(Integer.parseInt(buffer.toString()));
        return Integer.parseInt(buffer.toString()); 
  }

 @Override
 public String toDisplayString() {
  StringBuffer buffer = new StringBuffer();
  buffer.append(this.getId());
  buffer.append(&quot;\t&quot;);
  buffer.append(this.getFirstName());
  buffer.append(&quot;\t&quot;);
  buffer.append(this.getLastName());
  buffer.append(&quot;\t&quot;);
  buffer.append(this.getEmail());
  buffer.append(&quot;\t&quot;);
  buffer.append(this.getDesignation());
  return buffer.toString();
 }
}
&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;EmployeeService.java&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package com.jagadeesh.service;

import java.util.Set;

import com.jagadeesh.domain.Employee;

public interface EmployeeService {

    Set&amp;lt;Employee&amp;gt; getAll();

    void addEmployee(Employee employee);

}
&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;EmployeeServiceImpl.java&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package com.jagadeesh.service.impl;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import com.jagadeesh.domain.Employee;
import com.jagadeesh.service.EmployeeService;


public class EmployeeServiceImpl implements EmployeeService {
 private Set&amp;lt;Employee&amp;gt; employees = new HashSet&amp;lt;Employee&amp;gt;();

 @Override
 public Set&amp;lt;Employee&amp;gt; getAll() {
  Set&amp;lt;Employee&amp;gt; employees = new HashSet&amp;lt;Employee&amp;gt;(this.employees);
  return Collections.unmodifiableSet(employees);
 }

 @Override
 public void addEmployee(Employee employee) {
  if (employees.contains(employee)) {
   System.out.println(&quot;Employee already exists&quot;);
  } else {
   this.employees.add(employee);
  }
 }
}


&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;EmployeeIO.java&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package com.jagadeesh.utils;

import java.util.Set;

import com.jagadeesh.domain.Employee;
import com.jagadeesh.domain.impl.EmployeeImpl;


public class EmployeeIO {

 public static Employee read() {
  Employee employee = new EmployeeImpl();
  employee.setId(KeyBoard.readInt(&quot;Enter Id :&quot;));
  employee.setFirstName(KeyBoard.read(&quot;Enter First Name :&quot;));
  employee.setLastName(KeyBoard.read(&quot;Enter Last Name :&quot;));
  employee.setEmail(KeyBoard.read(&quot;Enter Email :&quot;));
  employee.setDesignation(KeyBoard.read(&quot;Enter Designation :&quot;));
  return employee;
 }

 public static void out(Set&amp;lt;Employee&amp;gt; employees) {
  StringBuilder builder = new StringBuilder();
  builder.append(&quot;Id\t\tFirst Name\t\tLast Name\t\tEmail\ttDesignation\n&quot;);
  for (Employee employee : employees) {
   System.out.println(employee.toDisplayString());
  }
  System.out.println(builder);
  builder.append(&quot;\n&quot;);
 }

}

&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;KeyBoard.java&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package com.jagadeesh.utils;

import java.util.Scanner;

public class KeyBoard {
  
    public static int readInt(String message) {
        System.out.print(message);
        Scanner scanner = new Scanner(System.in);
        try {
            int number = Integer.parseInt(scanner.next());
            return number;
        }
        catch(NumberFormatException e) {
            System.out.println(&quot;Invalid Number&quot;);
            return readInt(message);
        }            
    }
    
    public static String read(String message) {
        System.out.print(message);
        Scanner scanner = new Scanner(System.in);
        return scanner.nextLine();
    }    
}

&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;EmployeeMain.java&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package com.jagadeesh.main;

import com.jagadeesh.domain.Employee;
import com.jagadeesh.service.EmployeeService;
import com.jagadeesh.service.impl.EmployeeServiceImpl;
import com.jagadeesh.utils.EmployeeIO;
import com.jagadeesh.utils.KeyBoard;

public class EmployeeMain {
    public static void main(String[] args) throws Exception {
        int option = 1;
        EmployeeService empService = new EmployeeServiceImpl();
        do {
            Employee employee = EmployeeIO.read();
            empService.addEmployee(employee);
            option = KeyBoard.readInt(
                    &quot;Do you want add another employee(1/0) :&quot;);
            
        } while(option == 1);
        System.out.println(&quot;Reading from Set&quot;);
        EmployeeIO.out(empService.getAll());
    }
}

&lt;/pre&gt;&lt;b&gt;Out put of the program&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:text&quot;&gt;Enter Id :1
Enter First Name :jagadeesh
Enter Last Name :kumar
Enter Email :mannejkumar@gmail.com
Enter Designation :developer
Do you want add another employee(1/0) :1
Enter Id :2
Enter First Name :jagadeesh
Enter Last Name :kumar
Enter Email :mannejkumar@gmail.com
Enter Designation :developer
Do you want add another employee(1/0) :1
Enter Id :1
Enter First Name :jagadeesh
Enter Last Name :kumar
Enter Email :mannejkumar@gmail.com
Enter Designation :developer
Employee already exists
Do you want add another employee(1/0) :testing invalid option
Invalid Number
Do you want add another employee(1/0) :1
Enter Id :3
Enter First Name :jagadeesh
Enter Last Name :kumar
Enter Email :admin@myrmidons.co.in
Enter Designation :developer
Do you want add another employee(1/0) :0
Reading from List
Id First Name Last Name Email  Designation
1 jagadeesh kumar mannejkumar@gmail.com developer
2 jagadeesh kumar mannejkumar@gmail.com developer
3 jagadeesh kumar admin@myrmidons.co.in developer

&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;/div&gt;</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/5419951622307613517'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/5419951622307613517'/><link rel='alternate' type='text/html' href='http://jagadeeshmanne.blogspot.com/2011/12/core-java-set-and-hashset-example.html' title='Core Java : Set and HashSet example'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/09122533940640970927</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhnCZ1Bh06Ld2gVLkPBJn88qVxorsbpOOjqPlKu-htUfTqUnep5l0rDJ-4K2x_8XYjz4u5XC6mD9q1_9hC8h2Xy18w1RcFPMZ5xjJmgcj5T3MTdmcqilXXQHBhmcHZs7sAzmOeCGb2lwrE/s72-c/Hashset.png" height="72" width="72"/></entry><entry><id>tag:blogger.com,1999:blog-1889673847048308806.post-4245182393945183512</id><published>2011-11-28T07:36:00.000-08:00</published><updated>2011-12-20T23:16:46.218-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Core Java"/><title type='text'>Core Java:  List and ArrayList Example</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;List and ArrayList Example: Hi friends this is my first post on core java. I think you know the basics of Collections. I am not explaining basics here. When i am learning java I saw so &amp;nbsp;many sites are giving examples only on Collections to add integer or string or float.&amp;nbsp;Little bit&amp;nbsp;sites only giving example on adding objects and&amp;nbsp;retrieving&amp;nbsp; then from Collections. this is my first example using java.util.List and java.util.Arraylist. i am not explaining anything about this example.I think you can understand by seeing this example.&lt;br /&gt;
&lt;br /&gt;
the usage of this example is understanding List and ArrayList and contains method. we are adding employee to a list and avoiding duplicates while adding to list by overriding equals method. and&amp;nbsp;retrieving&amp;nbsp;all employees and displaying them from List. have any questions contact me or post a comment below.&lt;br /&gt;
&lt;br /&gt;
here is the download link for this example. if you free hosting site is deleted this file you can drop your mail id to get this example&lt;br /&gt;
&lt;br /&gt;
&lt;a href=&quot;http://www.mediafire.com/?1tt8tlgrn9l2h7a&quot; target=&quot;_blank&quot;&gt;Download List and ArrayList Example&lt;/a&gt;&amp;nbsp;and open it with eclipse and execute main method&lt;br /&gt;
&lt;b&gt;&lt;br /&gt;
&lt;/b&gt;&lt;br /&gt;
&lt;b&gt;Package structure:&lt;/b&gt;&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEheB7WlOm_uDrz6imh9TTA4hH5sbZKCkgdilzM4514jLy3LZbFcrh97KbgSOfbwYo8tSKUI4mepjZgvdAhx6sFUDMlI-igza4wjvyw6OUGP-LkvJgCZDh1FD705IwEHmr0R7YSfvxL0JUY/s1600/List.png&quot; imageanchor=&quot;1&quot; rel=&quot;lytebox&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;320&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEheB7WlOm_uDrz6imh9TTA4hH5sbZKCkgdilzM4514jLy3LZbFcrh97KbgSOfbwYo8tSKUI4mepjZgvdAhx6sFUDMlI-igza4wjvyw6OUGP-LkvJgCZDh1FD705IwEHmr0R7YSfvxL0JUY/s320/List.png&quot; width=&quot;291&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;b&gt;&lt;br /&gt;
&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Employee.java&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package com.jagadeesh.domain;

public interface Employee {

    public Integer getId();

    public void setId(Integer id);

    public String getFirstName();

    public void setFirstName(String firstName);
    
    public String getLastName();

    public void setLastName(String lastName);
    
    public void setEmail(String email);
    
    public String getEmail();

    public int getPriority();

    public void setPriority(int priority);
    
    public String getDesignation();

    public void setDesignation(String designation);

    public String toDisplayString();
}
&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;EmployeeImpl.java&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package com.jagadeesh.domain.impl;

import java.io.Serializable;

import com.jagadeesh.domain.Employee;
import com.jagadeesh.utils.EmployeeIO;

public class EmployeeImpl extends EmployeeIO 
             implements Employee {

 private static final long serialVersionUID = 5058287999709032283L;

 private Integer id;
 private String firstName;
 private String lastName;
 private String email;
 private int priority;
 private String designation;

 @Override
 public Integer getId() {
  return id;
 }

 @Override
 public void setId(Integer id) {
  this.id = id;
 }

 @Override
 public String getFirstName() {
  return firstName;
 }

 @Override
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 @Override
 public String getLastName() {
  return lastName;
 }

 @Override
 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 @Override
 public String getEmail() {
  return email;
 }

 @Override
 public void setEmail(String email) {
  this.email = email;
 }

 @Override
 public int getPriority() {
  return priority;
 }

 @Override
 public void setPriority(int priority) {
  this.priority = priority;
 }

 @Override
 public String getDesignation() {
  return designation;
 }

 @Override
 public void setDesignation(String designation) {
  if (&quot;CEO&quot;.equalsIgnoreCase(designation)) {
   setPriority(1);
  } else if (&quot;MD&quot;.equalsIgnoreCase(designation)) {
   setPriority(2);
  } else if (&quot;HR&quot;.equalsIgnoreCase(designation)) {
   setPriority(3);
  } else {
   setPriority(4);
  }
  this.designation = designation;
 }

 @Override
 public String toString() {
  StringBuffer buffer = new StringBuffer();
  buffer.append(&quot;EmployeeImpl [id=&quot;);
  buffer.append(id);
  buffer.append(&quot;, firstName=&quot;);
  buffer.append(firstName);
  buffer.append(&quot;, lastName=&quot;);
  buffer.append(lastName);
  buffer.append(&quot;, email=&quot;);
  buffer.append(email);
  buffer.append(&quot;, priority=&quot;);
  buffer.append(priority);
  buffer.append(&quot;, designation=&quot;);
  buffer.append(designation);
  buffer.append(&quot;]&quot;);
  return buffer.toString();
 }

 @Override
 public boolean equals(Object object) {
  if (object == null)
   return false;
  if (object == this)
   return true;
  if (this.getClass() != object.getClass())
   return false;
  Employee employee = (Employee) object;
  if (this.id.equals(employee.getId())
    &amp;amp;&amp;amp; this.firstName.equalsIgnoreCase(employee.getFirstName())
    &amp;amp;&amp;amp; this.lastName.equalsIgnoreCase(employee.getLastName())
    &amp;amp;&amp;amp; this.email.equalsIgnoreCase(employee.getEmail())
    &amp;amp;&amp;amp; this.designation.equalsIgnoreCase(employee.getDesignation()))
   return true;
  return false;
 }

 @Override
 public String toDisplayString() {
  StringBuffer buffer = new StringBuffer();
  buffer.append(this.getId());
  buffer.append(&quot;\t&quot;);
  buffer.append(this.getFirstName());
  buffer.append(&quot;\t&quot;);
  buffer.append(this.getLastName());
  buffer.append(&quot;\t&quot;);
  buffer.append(this.getEmail());
  buffer.append(&quot;\t&quot;);
  buffer.append(this.getDesignation());
  return buffer.toString();
 }
}
&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;EmployeeService.java&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package com.jagadeesh.service;

import java.util.List;

import com.jagadeesh.domain.Employee;

public interface EmployeeService {

    List&amp;lt;Employee&amp;gt; getAll();

    void addEmployee(Employee employee);

}

&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;EmployeeServiceImpl.java&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package com.jagadeesh.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.jagadeesh.domain.Employee;
import com.jagadeesh.service.EmployeeService;

public class EmployeeServiceImpl implements EmployeeService {
 private List&amp;lt;Employee&amp;gt; employees = new ArrayList&amp;lt;Employee&amp;gt;();

 @Override
 public List&amp;lt;Employee&amp;gt; getAll() {
  List&amp;lt;Employee&amp;gt; employees = new ArrayList&amp;lt;Employee&amp;gt;(this.employees);
  return Collections.unmodifiableList(employees);
 }

 @Override
 public void addEmployee(Employee employee) {
  if (employees.contains(employee)) {
   System.out.println(&quot;Employee already exists&quot;);
  } else {
   this.employees.add(employee);
  }
 }
}

&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;EmployeeIO.java&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package com.jagadeesh.utils;

import java.util.List;

import com.jagadeesh.domain.Employee;
import com.jagadeesh.domain.impl.EmployeeImpl;


public class EmployeeIO {

 public static Employee read() {
  Employee employee = new EmployeeImpl();
  employee.setId(KeyBoard.readInt(&quot;Enter Id :&quot;));
  employee.setFirstName(KeyBoard.read(&quot;Enter First Name :&quot;));
  employee.setLastName(KeyBoard.read(&quot;Enter Last Name :&quot;));
  employee.setEmail(KeyBoard.read(&quot;Enter Email :&quot;));
  employee.setDesignation(KeyBoard.read(&quot;Enter Designation :&quot;));
  return employee;
 }

 public static void out(List&amp;lt;Employee&amp;gt; employees) {
  StringBuilder builder = new StringBuilder();
  builder.append(&quot;Id\t\tFirst Name\t\tLast Name\t\tEmail\ttDesignation\n&quot;);
  for (int i = 0; i &amp;lt; employees.size(); i++) {
   builder.append(employees.get(i).toDisplayString());
   builder.append(&quot;\n&quot;);
  }
  System.out.println(builder);
 }

}
&lt;/pre&gt;&lt;b&gt;KeyBoard.java&lt;/b&gt;   &lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package com.jagadeesh.utils;

import java.util.Scanner;

public class KeyBoard {
  
    public static int readInt(String message) {
        System.out.print(message);
        Scanner scanner = new Scanner(System.in);
        try {
            int number = Integer.parseInt(scanner.next());
            return number;
        }
        catch(NumberFormatException e) {
            System.out.println(&quot;Invalid Number&quot;);
            return readInt(message);
        }            
    }
    
    public static String read(String message) {
        System.out.print(message);
        Scanner scanner = new Scanner(System.in);
        return scanner.nextLine();
    }    
}
&lt;/pre&gt;&lt;b&gt;EmployeeMain.java&lt;/b&gt;   &lt;br /&gt;
&lt;pre class=&quot;brush:java&quot;&gt;package com.jagadeesh.main;

import com.jagadeesh.domain.Employee;
import com.jagadeesh.service.EmployeeService;
import com.jagadeesh.service.impl.EmployeeServiceImpl;
import com.jagadeesh.utils.EmployeeIO;
import com.jagadeesh.utils.KeyBoard;

public class EmployeeMain {
    public static void main(String[] args) throws Exception {
        int option = 1;
        EmployeeService empService = new EmployeeServiceImpl();
        do {
            Employee employee = EmployeeIO.read();
            empService.addEmployee(employee);
            option = KeyBoard.readInt(
                    &quot;Do you want add another employee(1/0) :&quot;);
            
        } while(option == 1);
        System.out.println(&quot;Reading from List&quot;);
        EmployeeIO.out(empService.getAll());
    }
}
&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;&lt;b&gt;Out put of the program&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:text&quot;&gt;Enter Id :1
Enter First Name :jagadeesh
Enter Last Name :kumar
Enter Email :mannejkumar@gmail.com
Enter Designation :developer
Do you want add another employee(1/0) :1
Enter Id :2
Enter First Name :jagadeesh
Enter Last Name :kumar
Enter Email :mannejkumar@gmail.com
Enter Designation :developer
Do you want add another employee(1/0) :1
Enter Id :1
Enter First Name :jagadeesh
Enter Last Name :kumar
Enter Email :mannejkumar@gmail.com
Enter Designation :developer
Employee already exists
Do you want add another employee(1/0) :testing invalid option
Invalid Number
Do you want add another employee(1/0) :1
Enter Id :3
Enter First Name :jagadeesh
Enter Last Name :kumar
Enter Email :admin@myrmidons.co.in
Enter Designation :developer
Do you want add another employee(1/0) :0
Reading from List
Id First Name Last Name Email  Designation
1 jagadeesh kumar mannejkumar@gmail.com developer
2 jagadeesh kumar mannejkumar@gmail.com developer
3 jagadeesh kumar admin@myrmidons.co.in developer

&lt;/pre&gt;&lt;/div&gt;i am not uploading this example. free file hosting sites removing files. if you want this example please drop your mail id or contact mannejkumar@gmail.com. for more information follow our fan page on facebook&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;/div&gt;</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/4245182393945183512'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1889673847048308806/posts/default/4245182393945183512'/><link rel='alternate' type='text/html' href='http://jagadeeshmanne.blogspot.com/2011/11/core-java-list-and-arraylist-example.html' title='Core Java:  List and ArrayList Example'/><author><name>Anonymous</name><uri>http://www.blogger.com/profile/09122533940640970927</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEheB7WlOm_uDrz6imh9TTA4hH5sbZKCkgdilzM4514jLy3LZbFcrh97KbgSOfbwYo8tSKUI4mepjZgvdAhx6sFUDMlI-igza4wjvyw6OUGP-LkvJgCZDh1FD705IwEHmr0R7YSfvxL0JUY/s72-c/List.png" height="72" width="72"/></entry></feed>