Archive

Posts Tagged ‘Java’

Equals Method for Objects in Java

March 24, 2018 Leave a comment

This post is about how to compare object based on their fields and return true if they’re equal. To achieve this, we must override equals AND hashCode method.

Below the example.


public class Book {

private int id;
private String title;
private String author;

public Book(){
}

public Book(int id, String title, String author){
this.id = id;
this.title = title;
this.author = author;
}

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}

@Override
public boolean equals(Object obj) {
if (obj == null)
return false;

if (!(obj instanceof Book))
return false;

if (obj == this)
return true;

if (this.getTitle().equals(((Book) obj).getTitle()) && this.getTitle().equals(((Book) obj).getTitle())) {
return true;
} else {
return false;
}
}

@Override
public int hashCode() {
final int prime = 41;
int result = 1;
result = prime * result + ((this.getAuthor() == null) ? 0 : this.getAuthor().hashCode());
result = prime * result + ((this.getTitle() == null) ? 0 : this.getTitle().hashCode());
return result;
}
}

in piece code above, object is considered equal if field author and title have same value.

public static void main( String[] args )
{

Book firstBook = new Book(1, "Supernova", "Dee Lestari");
Book secondBook = new Book(2, "Supernova", "Dee Lestari");
Book thirdBook = new Book(3, "Aroma Karsa", "Dee Lestari");

List<Book> books = new ArrayList<Book>();
books.add(firstBook);

System.out.println("Is First equals Second book: "+firstBook.equals(secondBook));
System.out.println("Is First equals Third book: "+firstBook.equals(thirdBook));
System.out.println("Is Books List Containts Second book: "+books.contains(secondBook));
System.out.println("Is Books List Containts third book: "+books.contains(thirdBook));}

Result :

Equals Override Result

 

Overriding hashCode method.

The purpose overriding this method is if work with Java Hashed Collection, object that has same field value ( in this case title and author field) considered equal.

Let’s say, we don’t override hashCode method.

 
public static void main( String[] args ) {

Book firstBook = new Book(1, "Supernova", "Dee Lestari");
Book secondBook = new Book(2, "Supernova", "Dee Lestari");
Book thirdBook = new Book(3, "Aroma Karsa", "Dee Lestari");

HashSet <Book> hashBooks = new HashSet <Book> ();
hashBooks.add(firstBook);
hashBooks.add(secondBook);
hashBooks.add(thirdBook);
System.out.println("HashSet size: " + hashBooks.size());
}

Result:

HashCode Method Is Not Overrided

As you see, hashBooks variable containts 3 element, HashSet consider them as different object. We expect 2 element since object firstBook and secondBook has same field value.

Conclusion

  • It is mandatory to override hashcode()¬†each time we override equals()
  • If two objects are equal, they MUST have the same hash code

Thank you. ūüėÄ

Advertisements

Customize 403 Access Denied Spring Security

February 23, 2018 1 comment

In this post, I will show you how to add customize 403 access denied page in spring security. I use project in another post as basis.

1. Add 403 page

<html>
<body>
 <h1>HTTP Status 403 - Access is denied</h1>
 <h2>${msg}</h2>
</body>
</html>

2.Add a mapping for ‚Äú/403‚ÄĚ url in controller

 @RequestMapping(value = "/403", method = RequestMethod.GET)
 public ModelAndView aaccessDenied(Principal user) {
 mv = new ModelAndView("403");
 if (user != null) {
 mv.addObject("msg", "Hi " + user.getName()
 + ", you do not have permission to access this page!");
 } else {
 mv.addObject("msg",
 "You do not have permission to access this page!");
 }
 return mv;
 }

3.Add custom class to handle 403
In this class we can perform some logic before we redirect request to 403 page

</pre>
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

public class CustomAccessDeniedHandler implements AccessDeniedHandler {

private String accessDeniedPage= "403";
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exception)
throws IOException, ServletException {
System.out.println("Logic in here");
response.sendRedirect(accessDeniedPage);
}
}

4. Edit Spring Security config xml

	<http auto-config="true">
	<access-denied-handler ref="customAccessDeniedHandler" />
         ...
	</http>

        <beans:bean id="customAccessDeniedHandler"  class="org.mvc.security.config.CustomAccessDeniedHandler" />

5. Screen shoot

403

Spring Security Form Login With Database

January 28, 2018 1 comment

In this post, we will show you how to perform authentication using Spring Security backed by database.

Technology stack

  • Spring 4.2.5.RELEASE
  • Spring Security 4.2.3.RELEASE
  • Maven
  • Hibernate 5.2.5.Final
  • MySQL Database
  • Eclipse

Project structure

Project Structure

Below details step.

  • User entity
</pre>

package org.mvc.security.entity;

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Transient;

/**
* The Class User.
*/
@Entity
@Table(name = "users")
public class User {

/** The id. */
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;

/** The username. */
@Column(name = "username")
private String username;

/** The password. */
@Column(name = "password")
private String password;

/** The password confirm. */
@Transient
private String passwordConfirm;

/** The roles. */
@ManyToMany(cascade = CascadeType.REMOVE, fetch =FetchType.EAGER)
@JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private List<Role> roles;

/**
* Gets the id.
*
* @return the id
*/
public Long getId() {
return id;
}

/**
* Sets the id.
*
* @param id the new id
*/
public void setId(Long id) {
this.id = id;
}

/**
* Gets the username.
*
* @return the username
*/
public String getUsername() {
return username;
}

/**
* Sets the username.
*
* @param username the new username
*/
public void setUsername(String username) {
this.username = username;
}

/**
* Gets the password.
*
* @return the password
*/
public String getPassword() {
return password;
}

/**
* Sets the password.
*
* @param password the new password
*/
public void setPassword(String password) {
this.password = password;
}

/**
* Gets the roles.
*
* @return the roles
*/
public List<Role> getRoles() {
return roles;
}

/**
* Sets the roles.
*
* @param roles the new roles
*/
public void setRoles(List<Role> roles) {
this.roles = roles;
}

/**
* Gets the password confirm.
*
* @return the password confirm
*/
public String getPasswordConfirm() {
return passwordConfirm;
}

/**
* Sets the password confirm.
*
* @param passwordConfirm the new password confirm
*/
public void setPasswordConfirm(String passwordConfirm) {
this.passwordConfirm = passwordConfirm;
}

}
  • Role entity

package org.mvc.security.entity;

import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

/**
* The Class Role.
*/
@Entity
@Table(name = "roles")
public class Role {

/** The id. */
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

/** The name. */
@Column(name = "name")
private String name;

/** The users. */
@ManyToMany(mappedBy = "roles", fetch = FetchType.EAGER)
private List<User> users;

/**
* Gets the id.
*
* @return the id
*/
public Long getId() {
return id;
}

/**
* Sets the id.
*
* @param id the new id
*/
public void setId(Long id) {
this.id = id;
}

/**
* Gets the name.
*
* @return the name
*/
public String getName() {
return name;
}

/**
* Sets the name.
*
* @param name the new name
*/
public void setName(String name) {
this.name = name;
}

/**
* Gets the users.
*
* @return the users
*/
public List<User> getUsers() {
return users;
}

/**
* Sets the users.
*
* @param users the new users
*/
public void setUsers(List<User> users) {
this.users = users;
}

}

  • Spring context

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">

<context:annotation-config/>
<bean id="springDatasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url" value="${jdbc.url}" />
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="springDatasource" />
<property name="packagesToScan" value="org.mvc.security.entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.connection.autocommit">${hibernate.connection.autocommit}</prop>
</props>
</property>
</bean>

<tx:annotation-driven transaction-manager="transactionManager" />

<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>

* Spring security xml configuration

</pre>

<beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.2.xsd">

<http auto-config="true">
<csrf disabled="true"/>
<intercept-url pattern="/" access="permitAll" />
<intercept-url pattern="/login*" access="isAnonymous()" />
<intercept-url pattern="/user/**" access="hasAuthority('USER')" />
<intercept-url pattern="/admin/**" access="hasAuthority('ADMIN')" />

<form-login login-page="/login" authentication-success-handler-ref="customSuccessHandler" authentication-failure-url="/login?error=true" username-parameter="username" password-parameter="password" />
<logout logout-success-url="/login?logout=true" />
</http>

<beans:bean id="customSuccessHandler" class="org.mvc.security.config.CustomSuccessHandler" />

<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="userDetailsService">
</authentication-provider>
</authentication-manager>

</beans:beans>

* Create database with hibernate name and edit user and password for MySql database at application.properties file respectively. Table user and role will be created automatically

* Run this sql script


insert into roles (name) values ('USER');
insert into roles (name) values ('ADMIN');

insert into users (password, username) values ('12345', 'User');
insert into users (password, username) values ('12345', 'Admin');

insert into users_roles (user_id, role_id) values (1,1);
insert into users_roles (user_id, role_id) values (2,2);

* Add security filter in web.xml file

 <filter>
 <filter-name>springSecurityFilterChain</filter-name>
 <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
 </filter>
 <filter-mapping>
 <filter-name>springSecurityFilterChain</filter-name>
 <url-pattern>/*</url-pattern>
</filter-mapping

* Login form

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<div class="container">
<form class="form-horizontal" method="post" action="login" >
 <h2>Login Form</h2>
 <div class="form-group">
 <label class="control-label col-sm-2" for="username">Username</label>
 <div class="control-label col-sm-8">
 <input type="text" class="form-control" id="username" name="username" placeholder="Type Username"/>
 </div>
 </div>
 
 <div class="form-group">
 <label class="control-label col-sm-2" for="password">Password</label>
 <div class="control-label col-sm-8">
 <input type="password" class="form-control" id="password" name="password" placeholder="Type Password"/>
 </div>
 </div>
 <span>${error}</span>
 <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
 <button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>

* Screen shoot

Login Form

 

You can get complete code in here

Hope it will help.

Thank you.

Struts2 Dynamic Method Invocation

April 14, 2017 Leave a comment

Dynamic invocation in Struts2 is used to avoid configuration separate action mapping for each method in action class by using wildcard method.

Look at Struts configuration below.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
	<constant name="struts.enable.DynamicMethodInvocation" value="true" />
	<constant name="struts.devMode" value="false" />
	<constant name="struts.custom.i18n.resources" value="app-resources" />
	<constant name="struts.action.extension" value="html" />
        <constant name="struts.mapper.action.prefix.enabled" value="true"/>
 
	<package name="default" namespace="/" strict-method-invocation="false" extends="struts-default">

		<action name="*Book" method="{1}" class="strutshelloworld.net.ren.struts2.actions.BookAction">
		      <result name="success">/WEB-INF/jsp/Book.jsp</result>
		</action>
	</package>
</struts>

Action code.

import com.opensymphony.xwork2.ActionSupport;

/**
 * The Class BookAction.
 */
public class BookAction extends ActionSupport {

    /** The message. */
    private String message;

    /* (non-Javadoc)
     * @see com.opensymphony.xwork2.ActionSupport#execute()
     */
    public String execute() {
        message = "Inside execute method";
        return SUCCESS;
    }

    /**
     * Adds the.
     *
     * @return the string
     */
    public String add() {
        message = "Inside add method";
        return SUCCESS;
    }

    /**
     * Update.
     *
     * @return the string
     */
    public String update() {
        message = "Inside update method";
        return SUCCESS;
    }

    /**
     * Delete.
     *
     * @return the string
     */
    public String delete() {
        message = "Inside delete method";
        return SUCCESS;
    }

    /**
     * Gets the message.
     *
     * @return the message
     */
    public String getMessage() {
        return message;
    }

    /**
     * Sets the message.
     *
     * @param message the new message
     */
    public void setMessage(String message) {
        this.message = message;
    }
}

Please consider this as view code

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>In here</title>
</head>
<body>


<h1>Hello Here</h1>


<s:form action="Book">
<s:submit action="addBook" key="label.submit" align="center" />
<s:submit action="updateBook" key="label.update" align="center" />
<s:submit action="deleteBook" key="label.delete" align="center" />
</s:form>
</body>
</html>

As you can see, instead writing different name for each action name, action is provided with name=”*Book” method=”{1}” means if the input is ‚ÄúaddBook‚ÄĚ or “updateBook”¬Ě then the add() / update() method will be executed in Action class accordingly.

Please note it, strict-method-invocation (SMI) property in package tag has default value true. For futher reading about Strict Method Invocation (SMI)  you can see in here and here.

Thank you. ūüôā

java.lang.ClassNotFoundException: org.Springframework.Web.Context.ContextLoaderListener

March 16, 2017 Leave a comment

How to solve java.lang.ClassNotFoundException: org.Springframework.Web.Context.ContextLoaderListener.

Firstly we must know root cause :
This error because using Spring MVC framework in Java Web application and configured org.springframework.web.context.ContextLoaderListener as a listener in your deployment descriptor also known as web.xml, but the JAR which contains this class is not available in web application’s classpath. This jar appears in spring-web.jar, if you use maven as build tool so make sure that spring-web dependency exist in pom file.


<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>

Second, right click web project -> Select “Deployment Assembly” -> Click the “Add..” button on the right -> Select “Java Build Path Entries” from the menu of Directive Type and click “Next” -> Select “Maven Dependencies” from the Java Build Path Entries menu -> Click finish.

Please see picture below.

Build path

Thank you.

Categories: Java, Java and Web Tags: , ,

How To Remove Duplicate Value In Array Without Collection Help

October 27, 2016 Leave a comment

Below how to remove duplicate value in array without collection help


public class RemoveDuplicateManual {

public int[] removeDuplicateNumber(int[] inputArray) {
Arrays.sort(inputArray);
int[] outputArray = new int[inputArray.length];
int previous = inputArray[0];
int observed = 0;
for (int i = 1; i < inputArray.length; i++) {
observed = inputArray[i];
if (previous != observed) {
outputArray[i] = observed;
}
previous = observed;
}

return outputArray;
}
}

ūüôā

Iterator Pattern

March 22, 2016 Leave a comment

Iterator pattern is used to provide a way to access the elements of an aggregate object sequentially without exposing its internal structure.

Iterator Pattern

Iterator Pattern

Here is example.

SubjectType.java

public enum SubjectType {
     MANDATORY, OPTIONAL, ALL
}

Subject.java

 public class Subject {

    private String name;
    private String lecturer;
    private SubjectType type;
    
    public Subject(){
        
    }
    public Subject(String name, String lecturer, SubjectType type) {
        super();
        this.name = name;
        this.lecturer = lecturer;
        this.type = type;
    }
    public String getName() {
        return name;
    }
    public String getLecturer() {
        return lecturer;
    }
    public SubjectType getType() {
        return type;
    }
    @Override
    public String toString() {
        return "Subject [name=" + name + ", lecturer=" + lecturer + ", type=" + type + "]";
    }

}
 

SubjectCollection.java

public interface SubjectCollection {
    public void addSubject(Subject subject);
    public void removeSubject(Subject subjet);
    public SubjectIterator iterator(SubjectType type);
}

SubjectIterator.java

 public interface SubjectIterator {
   public Boolean hasNext();
   public Subject next();
   public void remove();
} 

SubjectCollectionImpl.java

public class SubjectCollectionImpl implements SubjectCollection {

    private List<Subject> subjects;

    public SubjectCollectionImpl() {
        subjects = new ArrayList<Subject>();
    }

    public void addSubject(Subject subject) {
        subjects.add(subject);
    }

    public void removeSubject(Subject subject) {
        subjects.remove(subject);
    }

    public SubjectIterator iterator(SubjectType type) {
        return new Iterator(type, subjects);
    }

    private class Iterator implements SubjectIterator {

        private SubjectType type;
        private int index;
        private List<Subject> subjects;

        private Iterator(SubjectType type, List<Subject> subjects) {
            this.type = type;
            this.subjects = subjects;
        }

        public Boolean hasNext() {
            while (index < subjects.size()) {
                Subject s = subjects.get(index);
                if (s.getType().equals(type)) {
                    return true;
                } else {
                    index++;
                }
            }
            return false;
        }

        public Subject next() {
            Subject s = subjects.get(index);
            index++;
            return s;
        }

        public void remove() {
            subjects.remove(index);
            index++;
        }

    }
}

App.java

public class App 
{
    public static void main( String[] args )
    {
    	SubjectCollection subjectCollection = populateSubject();
    	SubjectIterator iterator = subjectCollection.iterator(SubjectType.ALL);
    	while(iterator.hasNext()){
    		Subject s = iterator.next();
    		System.out.println(s.toString());
    	}
    	System.out.println("-----------------------");
    	iterator = subjectCollection.iterator(SubjectType.MANDATORY);
    	while(iterator.hasNext()){
    		Subject s = iterator.next();
    		System.out.println(s.toString());
    	}
    	System.out.println("-----------------------");
    	iterator = subjectCollection.iterator(SubjectType.OPTIONAL);
    	while(iterator.hasNext()){
    		Subject s = iterator.next();
    		iterator.remove();
    		System.out.println(s.toString());
    	}
    }
    
    public static SubjectCollection populateSubject(){
    	SubjectCollection subjectCollection = new SubjectCollectionImpl();
    	
    	subjectCollection.addSubject((new Subject("Accounting", "John", SubjectType.OPTIONAL)));
    	subjectCollection.addSubject((new Subject("Art", "Smith", SubjectType.OPTIONAL)));
    	subjectCollection.addSubject((new Subject("Chemistry", "Lennon", SubjectType.ALL)));
    	subjectCollection.addSubject((new Subject("Civil", "Alan", SubjectType.ALL)));
    	subjectCollection.addSubject((new Subject("Economics", "Mike", SubjectType.MANDATORY)));
    	subjectCollection.addSubject((new Subject("Education", "Joe", SubjectType.MANDATORY)));
    	
    	return subjectCollection;
    }
}

Result.

Iterator Result

Iterator Result

Categories: Java Tags: , ,