Wednesday 12 June 2013

How To Make A File Read Only In Java

A Java program to demonstrate the use of java.io.File setReadOnly() method to make a file read only. Since JDK 1.6, a new setWritable() method is provided to make a file to be writable again.

Example

package com.mitul;
 
import java.io.File;
import java.io.IOException;
 
public class FileReadAttribute
{
 
    public static void main(String[] args) throws IOException
    { 
     File file = new File("c:/file.txt");
 
     //mark this file as read only, since jdk 1.2
     file.setReadOnly();
 
     if(file.canWrite()){
          System.out.println("This file is writable");
     }else{
          System.out.println("This file is read only");
     }
 
     //revert the operation, mark this file as writable, since jdk 1.6
     file.setWritable(true);
 
     if(file.canWrite()){
          System.out.println("This file is writable");
     }else{
          System.out.println("This file is read only");
     }    
    }
}

How To Set The File Permission In Java


In Java, file permissions are very OS specific: *nix , NTFS (windows) and FAT/FAT32, all have different kind of file permissions. Java comes with some generic file permission to deal with it.

Check if the file permission allow :
  1. file.canExecute(); – return true, file is executable; false is not.
  2. file.canWrite(); – return true, file is writable; false is not.
  3. file.canRead(); – return true, file is readable; false is not.
Set the file permission :
  1. file.setExecutable(boolean); – true, allow execute operations; false to disallow it.
  2. file.setReadable(boolean); – true, allow read operations; false to disallow it.
  3. file.setWritable(boolean); – true, allow write operations; false to disallow it.
In *nix system, you may need to configure more specifies about file permission, e.g set a 777 permission for a file or directory, however, Java IO classes do not have ready method for it, but you can use the following dirty workaround :
Runtime.getRuntime().exec("chmod 777 file");

File permission example

package com.mitul.file;
 
import java.io.File;
import java.io.IOException;
 
public class FilePermissionExample 
{
    public static void main( String[] args )
    { 
     try {
 
       File file = new File("/mitul/shellscript.sh");
 
       if(file.exists()){
        System.out.println("Is Execute allow : " + file.canExecute());
    System.out.println("Is Write allow : " + file.canWrite());
    System.out.println("Is Read allow : " + file.canRead());
       }
 
       file.setExecutable(false);
       file.setReadable(false);
       file.setWritable(false);
 
       System.out.println("Is Execute allow : " + file.canExecute());
       System.out.println("Is Write allow : " + file.canWrite());
       System.out.println("Is Read allow : " + file.canRead());
 
       if (file.createNewFile()){
         System.out.println("File is created!");
       }else{
         System.out.println("File already exists.");
       }
 
     } catch (IOException e) {
       e.printStackTrace();
     }
    }
}

Spring And Java Thread Example


Java thread images

Here are 3 examples to show you how to do “threading” in Spring. See the code for self-explanatory.

1. Spring + Java Threads example

Create a simple Java thread by extending Thread, and managed by Spring’s container via @Component. The bean scope must be “prototype“, so that each request will return a new instance, to run each individual thread.
PrintThread.java
package com.mitul.thread;
 
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
 
@Component
@Scope("prototype")
public class PrintThread extends Thread{
 
 @Override
 public void run() {
 
  System.out.println(getName() + " is running");
  try {
   Thread.sleep(5000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  System.out.println(getName() + " is running");
 }
 
}
AppConfig.java
package com.mitul.config;
 
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
 
@Configuration
@ComponentScan(basePackages="com.mitul.thread")
public class AppConfig{
}
App.java
package com.mitul;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 
import com.mitul.config.AppConfig;
import com.mitul.thread.PrintThread;
 
public class App 
{
    public static void main( String[] args )
    {
 
     ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
 
     PrintThread printThread1 = (PrintThread) ctx.getBean("printThread");
     printThread1.setName("Thread 1");
 
     PrintThread printThread2 = (PrintThread) ctx.getBean("printThread");
     printThread2.setName("Thread 2");
 
     PrintThread printThread3 = (PrintThread) ctx.getBean("printThread");
     printThread3.setName("Thread 3");
 
     PrintThread printThread4 = (PrintThread) ctx.getBean("printThread");
     printThread4.setName("Thread 4");
 
     PrintThread printThread5 = (PrintThread) ctx.getBean("printThread");
     printThread5.setName("Thread 5");
 
     printThread1.start();
     printThread2.start();
     printThread3.start();
     printThread4.start();
     printThread5.start();
 
    }
}
Output – The order will be vary each time, this is thread :)
Thread 3 is running
Thread 2 is running
Thread 1 is running
Thread 5 is running
Thread 4 is running
Thread 2 is running
Thread 4 is running
Thread 5 is running
Thread 3 is running
Thread 1 is running

2. Spring Thread Pool + Spring non-managed bean example

Uses Spring’s ThreadPoolTaskExecutor to create a thread pool. The executing thread is not necessary managed by Spring container.
PrintThread.java – This thread is not managed by Spring, NO @Component
package com.mitul.thread;
 
public class PrintTask implements Runnable{
 
 String name;
 
 public PrintTask(String name){
  this.name = name;
 }
 
 @Override
 public void run() {
 
  System.out.println(name + " is running");
 
  try {
   Thread.sleep(5000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 
  System.out.println(name + " is running");
 }
 
}
Spring-Config.xml – ThreadPoolTaskExecutor in XML file
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-3.1.xsd">
 
 <bean id="taskExecutor"
  class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
  <property name="corePoolSize" value="5" />
  <property name="maxPoolSize" value="10" />
  <property name="WaitForTasksToCompleteOnShutdown" value="true" />
 </bean>
 
</beans>
App.java
package com.mitul;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
 
import com.mitul.thread.PrintTask;
 
public class App {
  public static void main(String[] args) {
 
    ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Config.xml");
    ThreadPoolTaskExecutor taskExecutor = (ThreadPoolTaskExecutor) context.getBean("taskExecutor");
    taskExecutor.execute(new PrintTask("Thread 1"));
    taskExecutor.execute(new PrintTask("Thread 2"));
    taskExecutor.execute(new PrintTask("Thread 3"));
    taskExecutor.execute(new PrintTask("Thread 4"));
    taskExecutor.execute(new PrintTask("Thread 5"));
 
 //check active thread, if zero then shut down the thread pool
 for (;;) {
  int count = taskExecutor.getActiveCount();
  System.out.println("Active Threads : " + count);
  try {
   Thread.sleep(1000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  if (count == 0) {
   taskExecutor.shutdown();
   break;
  }
 }
 
    }
}
Output – The order will be vary each time.
Thread 1 is running
Thread 2 is running
Thread 3 is running
Thread 4 is running
Active Threads : 4
Thread 5 is running
Active Threads : 5
Active Threads : 5
Active Threads : 5
Active Threads : 5
Thread 2 is running
Thread 1 is running
Thread 3 is running
Thread 4 is running
Thread 5 is running
Active Threads : 0

3. Spring Thread Pool + Spring managed bean example

This example is using ThreadPoolTaskExecutor again, and declares the thread as Spring managed bean via @Component.
The below PrintTask2 is Spring managed bean, you can @Autowired any required beans easily.
PrintTask2.java
package com.mitul.thread;
 
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
 
@Component
@Scope("prototype")
public class PrintTask2 implements Runnable{
 
 String name;
 
 public void setName(String name){
  this.name = name;
 }
 
 @Override
 public void run() {
 
  System.out.println(name + " is running");
 
  try {
   Thread.sleep(5000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 
  System.out.println(name + " is running");
 
 }
 
}
AppConfig.java – ThreadPoolTaskExecutor in Spring configuration file
package com.mitul.config;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
 
@Configuration
@ComponentScan(basePackages = "com.mitul.thread")
public class AppConfig {
 
 @Bean
 public ThreadPoolTaskExecutor taskExecutor() {
  ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
  pool.setCorePoolSize(5);
  pool.setMaxPoolSize(10);
  pool.setWaitForTasksToCompleteOnShutdown(true);
  return pool;
 }
 
}
App.java
package com.mitul;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
 
import com.mitul.config.AppConfig;
import com.mitul.thread.PrintTask2;
 
public class App {
  public static void main(String[] args) {
 
    ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
    ThreadPoolTaskExecutor taskExecutor = (ThreadPoolTaskExecutor) context.getBean("taskExecutor");
 
    PrintTask2 printTask1 = (PrintTask2) context.getBean("printTask2");
    printTask1.setName("Thread 1");
    taskExecutor.execute(printTask1);
 
    PrintTask2 printTask2 = (PrintTask2) context.getBean("printTask2");
    printTask2.setName("Thread 2");
    taskExecutor.execute(printTask2);
 
    PrintTask2 printTask3 = (PrintTask2) context.getBean("printTask2");
    printTask3.setName("Thread 3");
    taskExecutor.execute(printTask3);
 
 for (;;) {
  int count = taskExecutor.getActiveCount();
  System.out.println("Active Threads : " + count);
  try {
   Thread.sleep(1000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  if (count == 0) {
   taskExecutor.shutdown();
   break;
  }
 }
 
   }
}
Output – The order will be vary each time.
Thread 1 is running
Thread 2 is running
Thread 3 is running
Active Threads : 2
Active Threads : 3
Active Threads : 3
Active Threads : 3
Active Threads : 3
Thread 1 is running
Thread 3 is running
Thread 2 is running
Active Threads : 0
Love your comment to improve above program.

How To Create A Web Application Project With Maven


In this tutorial, we will show you how to use Maven to create a Java web application (with Spring MVC) project, and make it support Eclipse IDE.

Tools used :
  1. Maven 3.0.5
  2. Eclipse 4.2
  3. JDK 6
  4. Spring 3.2.0.RELEASED
  5. Tomcat 7

1. Web Application Project from Maven Template

In a terminal (*uix or Mac) or command prompt (Windows), navigate to the folder you want to store the project. Issue following command :
mvn archetype:generate -DgroupId={project-packaging} -DartifactId={project-name} -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false
This tell Maven to create a Java web application project from “maven-archetype-webapp” template.
For example,
$ pwd
/Users/mitul/Documents/workspace
 
$ mvn archetype:generate -DgroupId=com.mitul -DartifactId=CounterWebApp -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false
[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] Generating project in Batch mode
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-webapp:1.0
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: groupId, Value: com.mitul
[INFO] Parameter: packageName, Value: com.mitul
[INFO] Parameter: package, Value: com.mitul
[INFO] Parameter: artifactId, Value: CounterWebApp
[INFO] Parameter: basedir, Value: /Users/mkyong/Documents/workspace
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] project created from Old (1.x) Archetype in dir: /Users/mkyong/Documents/workspace/CounterWebApp
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.147s
[INFO] Finished at: Thu Dec 20 20:35:19 MYT 2012
[INFO] Final Memory: 12M/128M
[INFO] ------------------------------------------------------------------------
In above case, a new web application project named “CounterWebApp“, and the entire project directory structure is created automatically.

2. Maven Directory Layout

Maven created following web application directory layout. A standard deployment descriptor web.xml and Maven pom.xmlare created.
CounterWebApp
   |-src
   |---main
   |-----resources
   |-----webapp
   |-------index.jsp
   |-------WEB-INF
   |---------web.xml
   |-pom.xml
Note
Please check this official guide to understand more.
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mkyong</groupId>
  <artifactId>CounterWebApp</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>CounterWebApp Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>CounterWebApp</finalName>
  </build>
</project>
web.xml – Servlet 2.3 is too old, consider upgrade to 2.5
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >
 
<web-app>
  <display-name>Archetype Created Web Application</display-name>
</web-app>
index.jsp – A simple hello world html file
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>

3. Eclipse IDE Support

To convert the Maven web project to support Eclipse IDE, in terminal, navigate to “CounterWebAPp” folder, issue this command :
mvn eclipse:eclipse -Dwtpversion=2.0
You must add the -Dwtpversion=2.0 argument to make it as a Eclipse web project. Imports it into Eclipse IDE, a globe icon on top of project, means this is a web project in Eclipse.
You want Eclipse web project NOT Eclipse Java project.
Many users are confused, again, if you just issue mvn eclipse:eclipse, it will only convert the project as Eclipse Java project, add extra -Dwtpversion=2.0 argument to make it as Eclipse web project.
Done. This web project is ready to deploy. Attached to Eclipse’s Tomcat server plugin, and start it.
You can access the hello world jsp via – http://localhost:8080/CounterWebApp/

4. Update POM

To make above Maven web project to support Spring MVC framework, we need to touch up on the existing pom.xml :
  1. Add compiler plugin to specify JDK6 to compile this project (default is using JDK1.4).
  2. Add Spring frameworks dependencies.
  3. Update jUnit to latest 4.11.
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
 http://maven.apache.org/maven-v4_0_0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.mkyong</groupId>
 <artifactId>CounterWebApp</artifactId>
 <packaging>war</packaging>
 <version>1.0-SNAPSHOT</version>
 <name>CounterWebApp Maven Webapp</name>
 <url>http://maven.apache.org</url>
 
 <properties>
  <spring.version>3.0.5.RELEASE</spring.version>
  <junit.version>4.11</junit.version>
  <jdk.version>1.6</jdk.version>
 </properties>
 
 <dependencies>
 
  <!-- Spring 3 dependencies -->
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
   <version>${spring.version}</version>
  </dependency>
 
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-web</artifactId>
   <version>${spring.version}</version>
  </dependency>
 
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${spring.version}</version>
  </dependency>
 
  <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>${junit.version}</version>
   <scope>test</scope>
  </dependency>
 </dependencies>
 <build>
  <finalName>CounterWebApp</finalName>
  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.0</version>
    <configuration>
     <source>${jdk.version}</source>
     <target>${jdk.version}</target>
    </configuration>
   </plugin>
  </plugins>
 </build>
</project>

5. Spring MVC REST

Create a Spring MVC controller class, with two simple methods to print a message.
/src/main/java/com/mkyong/controller/BaseController.java
package com.mitul.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
 
@Controller
@RequestMapping("/")
public class BaseController {
 
 @RequestMapping(value="/welcome", method = RequestMethod.GET)
 public String welcome(ModelMap model) {
 
  model.addAttribute("message", "Maven Web Project + Spring 3 MVC - welcome()");
 
  //Spring uses InternalResourceViewResolver and return back index.jsp
  return "index";
 
 }
 
 @RequestMapping(value="/welcome/{name}", method = RequestMethod.GET)
 public String welcomeName(@PathVariable String name, ModelMap model) {
 
  model.addAttribute("message", "Maven Web Project + Spring 3 MVC - " + name);
  return "index";
 
 }
 
}
Create a Spring configuration file, defines the Spring view resolver.
/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml
<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"
 xsi:schemaLocation="
        http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
 
 <context:component-scan base-package="com.mkyong.controller" />
 
 <bean
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix">
   <value>/WEB-INF/pages/</value>
  </property>
  <property name="suffix">
   <value>.jsp</value>
  </property>
 </bean>
 
</beans>
Update existing web.xml to support Servlet 2.5 (the default Servlet 2.3 is too old), and also integrates Spring framework into this web application project via Spring’s listener ContextLoaderListener.
/src/main/webapp/WEB-INF/web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
       http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
       version="2.5"> 
 
 <display-name>Counter Web Application</display-name>
 
 <servlet>
  <servlet-name>mvc-dispatcher</servlet-name>
  <servlet-class>
   org.springframework.web.servlet.DispatcherServlet
  </servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>
 
 <servlet-mapping>
  <servlet-name>mvc-dispatcher</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>
 
 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
 </context-param>
 
 <listener>
  <listener-class>
   org.springframework.web.context.ContextLoaderListener
  </listener-class>
 </listener>
</web-app>
Move existing index.jsp inside folder WEB-INF, to protect user access it directly. In additional, edit the file to print out the${message} variable that pass by the controller.
/src/main/webapp/WEB-INF/pages/index.jsp
<html>
<body>
<h2>Hello World!</h2>
 
<h4>Message : ${message}</h1> 
</body>
</html>
Review the final directory structure

6. Eclipse + Tomcat

In order to start or debug this project via Eclipse server plugin (Tomcat or other container). You need to issue following command again, in order to make all dependencies attached to the project web deployment assembly.
mvn eclipse:eclipse -Dwtpversion=2.0
Before this command, project dependencies are empty.
After this command, now project dependdencies are here!
Important!
Many developers are trapped here, and failed to perform the starting or debugging in Eclipse server plugin, all failed by showing dependencies not found error message. Right click on your project properties, make sure all dependencies are inside the web deployment assembly, otherwise issue mvn eclipse:eclipse -Dwtpversion=2.0again!

7. Maven Packaging

Review the pom.xml again, the packaging tag defining what is the packaging format or output.
pom.xml
<project ...>
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.mitul</groupId>
 <artifactId>CounterWebApp</artifactId>
 
 <packaging>war</packaging>
 <version>1.0-SNAPSHOT</version>
Package the project to deploy is easy, just issue mvn package, it compiles and package the web project into a “war” file and store in project/target folder.
For example :
$pwd
/Users/mkyong/Documents/workspace/CounterWebApp
 
Yongs-MacBook-Air:CounterWebApp mkyong$ mvn package
[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building CounterWebApp Maven Webapp 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] -- omitted for readability
[INFO] 
[INFO] --- maven-war-plugin:2.1.1:war (default-war) @ CounterWebApp ---
[INFO] Packaging webapp
[INFO] Assembling webapp [CounterWebApp] in [/Users/mkyong/Documents/workspace/CounterWebApp/target/CounterWebApp]
[INFO] Processing war project
[INFO] Copying webapp resources [/Users/mkyong/Documents/workspace/CounterWebApp/src/main/webapp]
[INFO] Webapp assembled in [87 msecs]
[INFO] Building war: /Users/mkyong/Documents/workspace/CounterWebApp/target/CounterWebApp.war
[INFO] WEB-INF/web.xml already added, skipping
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.936s
[INFO] Finished at: Thu Dec 20 22:28:53 MYT 2012
[INFO] Final Memory: 14M/206M
[INFO] ------------------------------------------------------------------------
Done, just copy the project/target/CounterWebApp.war file and deploy to your container.

8. Demo

Start the web application.
http://localhost:8080/CounterWebApp/welcome
http://localhost:8080/CounterWebApp/welcome/mitul