Archive

Archive for the ‘Java’ Category

How To Find Longest Palindrome In String

July 29, 2017 Leave a comment

Below is code to find longest palindrome in string.


public class Palindrome {

public String getLongestPalindrome(String words) {
String longest = words.substring(0, 1);
for (int i = 0; i < words.length(); i++) {
String temp = helper(words, i, i);
if (longest.length() < temp.length()) {
longest = temp;
}

temp = helper(words, i, i + 1);
if (longest.length() < temp.length()) {
longest = temp;
}
}
return longest;
}

private String helper(String words,int left, int right) {
while (left >= 0 && right < words.length()&& words.charAt(left) == words.charAt(right)) {
left--;
right++;
}
return words.substring(left + 1, right);
}
}

ūüôā

Advertisements

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: , ,

Struts2 Interceptor Example

February 12, 2017 Leave a comment

In Struts2 interceptor are called one after other one in a configured order for each invocation of an action class. So with interceptor we can do some perform task like logging, validation before action is called.
In this tutorial it shows how to create an own interceptor in Struts2 (Login and Loggin Interceptor). Sumary steps below.

  • Create a class that implements com.opensymphony.xwork2.interceptor.Interceptor interface and override the intercept(ActionInvocation invocation), init, destroy method.

Interceptor class (AuthInterceptor.java)

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

/**
* The Class AuthInterceptor.
*/
public class AuthInterceptor implements Interceptor {

/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;

/* (non-Javadoc)
* @see com.opensymphony.xwork2.interceptor.Interceptor#destroy()
*/
public void destroy() {
System.out.println("destroy Auth");
}

/* (non-Javadoc)
* @see com.opensymphony.xwork2.interceptor.Interceptor#init()
*/
public void init() {
System.out.println("init Auth");
}

/* (non-Javadoc)
* @see com.opensymphony.xwork2.interceptor.Interceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
*/
public String intercept(ActionInvocation invoke) throws Exception {
SessionMap sessionMap = (SessionMap) ActionContext.getContext().getSession();
if(sessionMap.get("user") == null){
return Action.LOGIN;
} else {
return invoke.invoke();
}
}
}

Interceptor class (LogInterceptor.java)

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
/**
* The Class LogInterceptor.
*/
public class LogInterceptor implements Interceptor {

/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;

/* (non-Javadoc)
* @see com.opensymphony.xwork2.interceptor.Interceptor#destroy()
*/
public void destroy() {
System.out.println("destroy Log");
}

/* (non-Javadoc)
* @see com.opensymphony.xwork2.interceptor.Interceptor#init()
*/
public void init() {
System.out.println("init Log");
}

/* (non-Javadoc)
* @see com.opensymphony.xwork2.interceptor.Interceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
*/
public String intercept(ActionInvocation invoke) throws Exception {
String className = invoke.getAction().getClass().getName();
long startTime = System.currentTimeMillis();
System.out.println("Before calling action: " + className);

String result = invoke.invoke();

long endTime = System.currentTimeMillis();
System.out.println("After calling action: " + className + " Time taken: " + (endTime - startTime) + " ms");
return result;
}
}

If any intercept method in interceptor class decides action should not executed,
it can return a string value and response will be created from global result that same name in struts config file.

  • Configure the interceptor in the struts.xml.
<interceptors>
<interceptor name="authentication" class="strutshelloworld.net.ren.struts2.interceptors.AuthInterceptor">
</interceptor>

<interceptor name="logging" class="strutshelloworld.net.ren.struts2.interceptors.LogInterceptor">
</interceptor>

<interceptor-stack name="authStack">
<interceptor-ref name="authentication" />
<interceptor-ref name="logging" />
<interceptor-ref name="defaultStack" />
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="defaultStack"></default-interceptor-ref>
  • Add global result
<action name="index">
<interceptor-ref name="authStack"></interceptor-ref>
<result type="redirect">/home.html</result>
</action>
  • Add interceptor in action
<action name="home" class="strutshelloworld.net.ren.struts2.actions.UserAction">
<interceptor-ref name="authStack"></interceptor-ref>
<result name="success">/WEB-INF/jsp/Welcome.jsp</result>
</action>

For complete code, you can get it in here.
Fyi, I used project in this post as basis.

Thank you. ūüôā

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;
}
}

ūüôā

How To Reverse Number

August 6, 2016 Leave a comment

Below is code to reverse number.


public class ReverseNumber {

int reverse = 0;

public void reverse(int number) {
while (number != 0) {
reverse = reverse * 10 + number % 10;
number = number / 10;
}
System.out.println(reverse);
}
}

ūüôā

Categories: Java Tags: ,

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: , ,