How to read file in Java? (BufferedReader Example)

Java provides many API to read files , here is once simple example to read a file using Buffered Reader

package com.pretech;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
	public static void main(String[] args) throws IOException {
		BufferedReader bf = new BufferedReader(new FileReader("c://buffertext.txt"));
		String value;
		while ((value = bf.readLine()) != null) {
			System.out.println(value);
		}
	}
}

How to convert String to Date in Java

In Java we can use SimpleDateFormat API to format String to Date object. Here is one simple example to convert a String to Date object

Example

package com.pretech;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringtoDateConversion {
	public static void main(String[] args) {
		DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
		String dateInString = "12-Dec-2010";
		try {
			Date date = formatter.parse(dateInString);
			System.out.println("Date object is " + date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
}

Output



Date object is Sun Dec 12 00:00:00 IST 2010


How to get Current working Directory in java ?

To get current directory location we can use user.dir property

System.getProperty("user.dir")

Example

package com.pretech;
public class CurrentDirectory {
	public static void main(String[] args) {
		System.out.println("Current Directory :"
				+ System.getProperty("user.dir"));
	}
}

What is Tomcat default password

In Apache tomcat user roles are configured in /conf/tomcat-users.xml file. By default we can see all user roles are commented in this xml file. To get the admin access add new user roles in tomcat-users.xml file

Example

<tomcat-users>
    <!--
  NOTE:  By default, no user is included in the "manager-gui" role required
  to operate the "/manager/html" web application.  If you wish to use this app,
  you must define such a user - the username and password are arbitrary.
-->
    <!--
  NOTE:  The sample user and role entries below are wrapped in a comment
  and thus are ignored when reading this file. Do not forget to remove
  <!.. ..> that surrounds them.
-->
    <!--
  <role rolename="tomcat"/>
  <role rolename="role1"/>
  <user username="tomcat" password="tomcat" roles="tomcat"/>
  <user username="both" password="tomcat" roles="tomcat,role1"/>
  <user username="role1" password="tomcat" roles="role1"/>
-->
    <user password="pretech" roles="manager-script,admin,manager-gui" username="pretech"/>
</tomcat-users>

How to skip tests in Maven

There are two ways we can skip the tests in maven

1. Using skipTests option pom.xml

<build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.15</version>
        <configuration>
          <skipTests>true</skipTests>
        </configuration>
      </plugin>
    </plugins>
  </build>

2. Skip tests as argument (During command line maven install)

$ mvn install -Dmaven.test.skip=true

Struts 2 Login Form Example

In this example we will see how to create a simple login page ,validation  and navigation using Struts 2

Environment Used

Java 1.7

Eclipse Juno

Apache Tomcat 7

Struts 2 Jars

1. Create a dynamic web project in Eclipse

Create a Dynamic web project in Eclipse and configure apache tomcat as Server. Once it is created download Struts 2 jars and place in to WEB-INF/lib folder. Here is the final structure of the project. (Click here to download this example with jars)

image

2. Update Web.xml file

Add Struts FilterDispatcher details in to web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
    <display-name>Struts2HelloWorldExample</display-name>
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
</web-app>

3. Create an Action class (LoginAction.java)

package com.pretech;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {
    private String name;
    private String password;
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String execute() {
        if (name.equals("pretech") & password.equals("pretech")) {
            return SUCCESS;
        } else {
            return ERROR;
        }
    }
}

4. Create a loginform (index.jsp)

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<body>
<s:form action="loginaction">
<s:textfield name="name" label="Enter Username" /><br>
<s:password name="password" label="Enter Password" /><br>
<s:submit value="Submit" align="center" />
</s:form>
</body>
</html>

5. Create a success page (success.jsp)

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head></head>
<body>
 <h4> You
 <s:property value="name" /> Successfully logged
 </h4>
</body>
</html>

6. Create an error page (error.jsp)

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head></head>
<body>
 <h4> Login Failed
 </h4>
</body>
</html>

7. Create Struts.xml file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <include file="struts-default.xml"/>
    <package name="com" extends="struts-default">
        <action name="loginaction" class="com.pretech.LoginAction">
            <result name="success">/success.jsp</result>  
                     <result name="error">/error.jsp</result>      
        </action>
    </package>
</struts>

8. Deploy and Run application in Tomcat

Run the application and give your input


image

image

Mockito Simple Mocking Example

In the previous example EasyMock we created Mock object using EasyMock, in this example we will see how to create mock objects in Mockito.

1. Create a Maven project and add below dependency

  <dependency>
	<groupId>org.mockito</groupId>
	<artifactId>mockito-all</artifactId>
	<version>1.8.4</version>
</dependency>

2. Create a POJO class (Employee.java)

package com.pretech;
public class Employee {
	private String name;
	private String address;
	private String age;
//Getters and Setters

3. Create a Java class which needs to be tested

package com.pretech;
public class EmployeeDetails {
	public String createNewEmployee(Employee emp) {
		String result = null;
		if (emp.getAddress().equals("Bangalore")) {
			result = "Employee from bangalore";
		}
		return result;
	}
}

4. Create a Test class using Mockito

package com.pretech;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
public class EmployeeDetailsTest {
	@Mock
	Employee emp;
	@Before
	public void setUp() throws Exception {
		MockitoAnnotations.initMocks(this);
	}
	@Test
	public void test1() {
		String expected = "Employee from bangalore";
		System.out.println("Test1");
		Mockito.when(emp.getAddress()).thenReturn("Bangalore");
		EmployeeDetails stdetails = new EmployeeDetails();
		assertEquals(expected, stdetails.createNewEmployee(emp));
	}
}

5. Run it as JUnit Test cases



image


Model Context Protocol (MCP) — Complete Guide for Backend Engineers

  Model Context Protocol (MCP) — Complete Guide for Backend Engineers Build Tools, Resources, and AI-Driven Services Using LangChain Moder...

Featured Posts