Learn the latest Spring Framework and pass Spring Core Certification 4.x with online udemy training

Learn the latest Spring Framework and pass Spring Core Certification 4.x with online udemy training

https://www.udemy.com/spring-framework-4-course-and-core-spring-certification/?couponCode=edulearnspring25
https://www.udemy.com/spring-framework-4-course-and-core-spring-certification/?couponCode=edulearnspring25

https://www.udemy.com/spring-framework-4-course-and-core-spring-certification/?couponCode=edulearnspring25

Redemption Code: edulearnspring25

Hi,

I am Tuna Tore and the owner of this technical blog;

I created an online course for learning the details and usages of Spring Framework in commercial environments.

If you would like to learn the latest version of Spring Framework with step by step examples/codes and pass Core Spring Framework Certification 4.x then you can attend this udemy course through the following link;

Spring Framework 4.x Course and Core Spring Certification

Spring Framework and Core Spring Certification Udemy course with discount
Spring Framework and Core Spring Certification Udemy course with a discount coupon

If you attend this course through this link, I will provide more than %50 discount coupon.
Actual course price is 59 euros and with this link you will be able to learn and code Spring Framework Applications by only paying
25 euros (instead of 59 euros)

Here you can find the contents of udemy Spring Framework Course;

  • Spring Container, Dependency, and IOC (Inversion of Control)
  • Spring Aspect Oriented Programming
  • Spring JDBC, Transactions, and ORM (Hibernate)
  • Spring MVC
  • Spring Security
  • Spring Messaging (JMS)
  • REST
  • Unit Testing with JUnit for Spring Applications
  • Library Management with Maven using STS (Spring Tool Suite)

After attending the course, if you have any questions, I will be ready to support you.

Regards,

imageio image compression example


  

package nl.kameroom.image;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Iterator;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageOutputStream;

public class ImageService {
	
	public void compressAndWriteImage(BufferedImage img, File destFile) throws Exception {
		
		 Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg");
         ImageWriter writer = (ImageWriter)iter.next();
         // Prepare output file
         ImageOutputStream ios = ImageIO.createImageOutputStream(destFile);
         writer.setOutput(ios);

         // Set the compression quality
         ImageWriteParam iwparam = writer.getDefaultWriteParam();
         iwparam.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT) ;
         iwparam.setCompressionQuality(0.3F); //between 0.0-1.0

         // Write the image
         writer.write(null, new IIOImage(img, null, null), iwparam);

         // Cleanup
         ios.flush();
         writer.dispose();
         ios.close();
         
	}
	
	public String validateFile(String contentType, String fileName, String orgFileName, long size) {
		System.out.println("contentType " + contentType);
		System.out.println("fileName " + fileName);
		System.out.println("orgFileName " + orgFileName);
		System.out.println("size " + size);
		final String MAX_SIZE_IMAGES = "2000000";
		
	    String message = "";
	      
	      String mimeType = contentType;
	      
	      if ( mimeType != null && mimeType.startsWith( "image/" ) )
	      {
	         if ( ! (mimeType.equalsIgnoreCase( "image/png") 
	        		 	||  mimeType.equalsIgnoreCase( "image/jpeg") 
	        		 		||  mimeType.equalsIgnoreCase( "image/bmp")
	        		 			||  mimeType.equalsIgnoreCase( "image/jpg")) )
	         {
	        	message = "Invalid File Type";
	            return message;
	         }
	         if ( size > Long.valueOf(MAX_SIZE_IMAGES))
	         {
	        	 message = "Invalid File Size";
		         return message;
	         }
	      }
	      else
	      {
	    	  message = "Invalid File Type";
	          return message;
	         
	      }
		return message;
	}
}

How to use FilenameFilter by an example code


By running the following code, only the .log file will be listed by implementing FilenameFilter.

The vital method for this code is public boolean accept used to Filter all files inside a directory.


import java.io.File;
import java.io.FilenameFilter;

public class FileNameFilterExample{

/**
 * @param FilenameFilter example
 */
 public static void main(String[] args) {

 File c = new File ("C:\\");
 FileNameFilterExample mainClass = new FileNameFilterExample();
 FileNameFilterExample.FileNameFiltering filter = mainClass.new FileNameFiltering();

 String [] fileNames = c.list(filter);
 for(String fileName : fileNames) {
 System.out.println(fileName);
 }

 }

public class FileNameFiltering implements FilenameFilter {

@Override
 public boolean accept(File dir, String name) {
 // listing only .log files
 return name.endsWith(".log");
 }

 }

}

Sample output of the code;

a – Copy (2).log
a – Copy (3).log
a – Copy (4).log
a – Copy (5).log
a – Copy.log
a.log

java.util.regex.PatternSyntaxException: Unmatched closing ‘)’ solution


If you encountered the following exception during run time;

java.util.regex.PatternSyntaxException: Unmatched closing ‘)’
Change your code such as the following for the parenthesis

String replaced = string.replaceFirst(“)“, “replaced”);  –> run time exception
String replaced = string.replaceFirst(“\\)“, “replaced”); –> correct usage

How to integrate JSF and Spring Framework


If you would like to integrate the JSF MVC framework with the Spring Framework, you can use the following approach;
There are also other configurations  available however this one fits very well while developing web applications using JSF and Spring.

In this example, I am using the basic .jars required by Spring Framework. These jars are;

spring-web.jar
spring-webmvc-2.5.jar
org.springframework.expression-3.1.0.RC1.jar
org.springframework.core-3.1.0.RC1.jar
org.springframework.context-3.1.0.RC1.jar
org.springframework.beans-3.1.0.RC1.jar
org.springframework.asm-3.1.0.RC1.jar

You also the following jars inside your project’s lib folder in order to use JSF framework;

jstl.jar
standard.jar
jsf-impl.jar
jsf-api.jar
commons-beanutils.jar
commons-collections.jar
commons-digester.jar
commons-logging.jar

Here you can see the project’s library structure;

SpringJSFApplication.class this class will be used as  the main application inside the program, it also has a reference for the FooService class  initialized by Spring Framework.

package com.tunatore.spring.application;

import com.tunatore.spring.service.FooService;

/**
*
* @author tunatore
*/
public class SpringJSFApplication {

private FooService fooService;

/**
* @return the fooService
*/
public FooService getFooService() {
return fooService;
}

/**
* @param fooService the fooService to set
*/
public void setFooService(FooService fooService) {
this.fooService = fooService;
}

}

 Foo.class is used a regular bean and it is solely Java POJO

package com.tunatore.spring.bean;

/**
*
* @author tunatore
*/
public class Foo {
private String name = "FooBean Name is here!";

public Foo(String name) {
this.name = name;
}

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

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

}

 FooService.class is used to get a Foo Object (or from Database)

package com.tunatore.spring.service;

import com.tunatore.spring.bean.Foo;

/**
*
* @author tunatore
*/
public class FooService {
public Foo getFooBean() {
return new Foo("This is a new Foo [initiated by Spring Framework]");
}
}

The following file is required to configure Spring beans

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
 Document : applicationContext.xml
 Created on : 28 November 2011, 13:47
 Author : tunatore
 Description:
 applicationContext.xml file is used by
 Spring for bean initializations
-->
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" 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.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">

<bean id="springJSFApplication" class="com.tunatore.spring.application.SpringJSFApplication">
 <property name="fooService" ref="fooService"/>
</bean>

<bean id="fooService" class="com.tunatore.spring.service.FooService"/>

</beans>

web.xml file should include the location of the applicationContext.xml and two Spring specific listeners
org.springframework.web.context.ContextLoaderListener
org.springframework.web.context.request.RequestContextListener

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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">
 <servlet>
 <servlet-name>Faces Servlet</servlet-name>
 <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
 <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
 <servlet-name>Faces Servlet</servlet-name>
 <url-pattern>/faces/*</url-pattern>
 </servlet-mapping>
 <session-config>
 <session-timeout>
 30
 </session-timeout>
 </session-config>
 <welcome-file-list>
 <welcome-file>faces/index.jsp</welcome-file>
 </welcome-file-list>
 <context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>/WEB-INF/applicationContext*.xml</param-value>
 </context-param>
 <listener>
 <listener-class>
 org.springframework.web.context.ContextLoaderListener
 </listener-class>
 </listener>
 <listener>
 <listener-class>
 org.springframework.web.context.request.RequestContextListener
 </listener-class>
 </listener>
</web-app>

With the following faces-config.xml file
fooService Service object will be initialized through Spring Framework. You  also need to define 
org.springframework.web.jsf.DelegatingVariableResolver inside this file.

faces-config.xml

<?xml version='1.0' encoding='UTF-8'?>

<!-- =========== FULL CONFIGURATION FILE ================================== -->

<faces-config version="1.2"
 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-facesconfig_1_2.xsd">

<application>
 <variable-resolver>
 org.springframework.web.jsf.DelegatingVariableResolver
 </variable-resolver>
 </application>
 <managed-bean>
 <managed-bean-name>SpringJSFApplication</managed-bean-name>
 <managed-bean-class>
 com.tunatore.spring.application.SpringJSFApplication
 </managed-bean-class>
 <managed-bean-scope>session</managed-bean-scope>
 <managed-property>
 <property-name>fooService</property-name>
 <value>#{fooService}</value>
 </managed-property>
 </managed-bean>
</faces-config>

This index page will be call fooService methods 

index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

<f:view>
 <html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
 <title>Spring JSF Integration Example</title>
 </head>
 <body>
 <h1><h:outputText value="#{SpringJSFApplication.fooService.fooBean.name}"/></h1>
 </body>
 </html>
</f:view>

When you run the program, you will see the following screen on the browser;

You can download the program’s source by clicking here (This is a war file including sources)

Comments or questions are welcomed

How to calculate method execution time in Java (using System.currentTimeMillis())


Friends the following udemy course created by me;

      Click here to attend Spring Framework 4.x and certification course with a discount

Spring Framework and Core Spring Certification Udemy course with discount
Spring Framework and Core Spring Certification Udemy course with a discount coupon

Here you can find a code example for calculating the execution time of a method;


package methodexecutiontimer;

/**
*
* @author tunatore
*/
public class MethodExecutionTimer {

public static void main(String[] args) {

  long start = System.currentTimeMillis();
  heavyMethod();
  long end = System.currentTimeMillis();
  System.out.println("Method execution total time"
  + " in seconds ==&gt; " + (end - start) / 1000 + " seconds");

}

public static void heavyMethod() {

  for (int i = 1; i &lt; 5; i++) {
  try {
      Thread.sleep(i * 1000); // * 1000 makes it second 1*1000 = 1 second
  } catch (InterruptedException ex) {
  ex.printStackTrace()
  }

 }
}
}

 

Program output;

run:
Method execution total time in seconds ==> 10 seconds
BUILD SUCCESSFUL (total time: 10 seconds)

How to run OS commands (Windows OS) from Java Web Applications (J2EE)


If you want to call OS specific commands inside a Java J2EE web application, you can use the following code.

By using this code, you can also get the output from the command console and use it for displaying or other purposes.

Here you can find the BatchFileExecuter class

package com.tunatore.batchoperations;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 *
 * @author tunatore
 */
public class BatchFileExecuter extends HttpServlet {
    protected void handleRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, InterruptedException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
BufferedReader bufferedReader = null;
Process process = null;
try {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet BatchFileExecuter</title>");
out.println("</head>");
out.println("<body><center><h1>Content</h1><table border=\"1\">");
//this is the directory which will be used as home directory for the command executing
File directory = new File("C:\\Program Files\\Java\\jdk1.6.0_27\\");
process = Runtime.getRuntime().exec("cmd /c dir", null ,directory);
//reading the InputStream using Buffered Reader
bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String currentLine; //reading line by line the output from the command console
while ((currentLine = bufferedReader.readLine()) != null) {
//this piece of code is used for formating the InputStream getting from the command console
  out.println("<tr><td>"
  + currentLine.replace("<", "&lt;").replace(">", "&gt;")
+ "</td></tr>");
}
out.println("</table></center></body>");
out.println("</html>");
} finally {
bufferedReader.close();
//process.destroy();
out.close();
  }
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
try {
handleRequest(request, response);
} catch (InterruptedException ex) {
   Logger.getLogger(BatchFileExecuter.class.getName()).log(Level.SEVERE, null, ex);
}
}
 @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
try {
handleRequest(request, response);
} catch (InterruptedException ex) {
            Logger.getLogger(BatchFileExecuter.class.getName()).log(Level.SEVERE, null, ex);
}
}
}


You can call this class from a JSP file called index.jsp

<%--
    Document   : index
    Created on : 07-11-2011, 15:30:42
    Author     : tunatore
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JavaExecuteBatchWebProject</title>
    </head>
    <body>
        <h1>JavaExecuteBatchWebProject</h1>
        <i>(`cmd /c dir`)</i> command will be executed on the Server Machine </br></br>
        <i>C:\\Program Files\\Java\\jdk1.6.0_27\\</i> will be used for applying the command dir</br></br>
        The output of the command will be published on the browser  </br></br>
<a href="/JavaExecuteBatchWebProject/BatchFileExecuter">Run command on Windows OS</a>
   </body>
</html>

And lastly your web.xml file should like the following;

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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_3_0.xsd">
    <servlet>
        <servlet-name>BatchFileExecuter</servlet-name>
        <servlet-class>com.tunatore.batchoperations.BatchFileExecuter</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>BatchFileExecuter</servlet-name>
        <url-pattern>/BatchFileExecuter</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

Here you can see the outputs;

First index.jsp output

Second screen’s output

Download All Source