Because I am constantly busy working on something, I have never had time to actually put everything in words and pictures. But, since you got here, then you must have already seen some part of my work - and this is the way I’m talking. I'm 24, born in Romania, studied at UPG Romania in software development field. I started from 0, mostly with basic stuff, and I’m evolving every day to an expert. I'm focused on freelancing projects, from small websites, to really heavy stuff.

Thursday, March 31, 2011

How to control time with JSR 310


Are you enough with java.util.Date and Calendar? Is relatively hard to use and does not satisfy your “hunger” for time control? If the answer is “yes”, then it is time to take a closer look to JSR 310 which is a set of classes for Java 7 which are a revamp of Java's built-in Date and Calendar classes. In the series of beta releases of Java 7, this API is not bundled yet, therefore if you want to play with it you need to have in your classpath the JAR from here: http://sourceforge.net/projects/threeten/files/threeten/.

Some other resources of JSR 310 are:

http://jcp.org/en/jsr/summary?id=310
http://sourceforge.net/apps/mediawiki/threeten/index.php?title=ThreeTen
http://groovycookbook.org/basic_types/dates_times_jsr310/

One of my favorite things is the Clock class that acts as a facade for accessing the current time. You can access current time like this:

Clock clock = Clock.system(TimeZone.UTC);

And now, you can “play” with many methods of the Clock class, as you can see below (get time, day, yesterday, tomorrow, year and so on):

Year year = clock.year();
YearMonth yearMonth = clock.yearMonth();
LocalDate today = clock.today();
LocalDate yesterday = clock.yesterday();
LocalDate tomorrow = clock.tomorrow();
LocalTime time = clock.time();
LocalTime timeToMinute = clock.timeToMinute();
LocalTime timeToSecond = clock.timeToSecond();

If we send this to System.out,

System.out.println("Year: " + year);
System.out.println("Year Month: " + yearMonth);
System.out.println("Today: " + today);
System.out.println("Yesterday: " + yesterday);
System.out.println("Tomorrow: " + tomorrow);
System.out.println("Time: " + time);
System.out.println("Time to minute: " + timeToMinute);
System.out.println("Time to second: " + timeToSecond);

We get:

Year: Year=2011
Year Month: 2011-03
Today: 2011-03-31
Yesterday: 2011-03-30
Tomorrow: 2011-04-01
Time: 08:08:04.812
Time to minute: 08:08
Time to second: 08:08:04

From NetBeans, here it is the set of Clock methods (they are pretty intuitive):


Class name Description

Clock - A facade class for accessing the current time (overview above).
LocalDate - Local date with no time or time zone.
LocalTime - Time with no date or time zone.
ZonedDateTime - Calendar information, often viewed as
year-month-day-hour-minute-second-zone.
LocalDateTime - Local date and time with no time zone.
Instant - Instantaneous point in time with nanosecond precision.
Period - Period consisting of the standard year, month, day, hour, minute,
second and nanosecond units.

Well, here are same methods of LocalDate class (so many and so gooooood):

And, some of LocalTime:

These great methods can be use to accomplished many delicate tasks, like:

• Define time periods – one year period:

Period one_year = Period.ofYears(1);
System.out.println(one_year.getYears());

Output: 1

• Instant time:

Instant instant = clock.instant();
System.out.println(instant);

Output: 2011-03-31T16:25:34.752Z

• Format time:

LocalDate today = clock.today();
DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder().appendValue(CopticChronology.dayOfMonthRule(), 2).appendLiteral('-').appendText(CopticChronology.monthOfYearRule(), DateTimeFormatterBuilder.TextStyle.SHORT).appendLiteral('-').appendText(CopticChronology.yearRule());
System.out.println(builder.toFormatter().print(today));

Output: 22-7-1727

And, there are so many to explore!

Wednesday, March 30, 2011

How to generate DAO classes for Hibernate with JDBC transaction factory


If you need to generate DAO classes (Home classes) for Hibernate based on JDBC transaction factory, then in a start folder you need:

• A folder named hbm2java_gen that contains all the POJOs classes.
• The below ant script (named hbm2daoJNDI_JDBCTransactionFactory.xml):

<project name="Hibernate Tools for Ant - hbm2daoJDBC" default="run">
<target name="clean">
<delete dir="JDBC_java/classes"/>
<delete dir="JDBC_java/jar"/>
</target>
<target name="compile" depends="clean">
<mkdir dir="JDBC_java/classes"/>
<javac srcdir="JDBC_java/src" destdir="JDBC_java/classes"/>
</target>
<target name="jar" depends="compile">
<mkdir dir="JDBC_java/jar"/>
<jar destfile="JDBC_java/jar/GenerateDAOForJDBC.jar"
basedir="JDBC_java/classes">
<manifest>
<attribute name="Main-Class"
value="com.hibernate.jdbc.GenerateDAOForJDBC"/>
</manifest>
</jar>
</target>
<target name="run" depends="jar">
<java jar="JDBC_java/jar/GenerateDAOForJDBC.jar" fork="true"/>
</target>
</project>

• The JDBC_java folder that can be downloaded from http://www.filefactory.com/file/ca0a5c0/n/HibernateTools.rar.
• A folder named hbm2daojdbc_gen folder that will contain the generated DAOs.

Now, you can generate the DAOs, like this:

1. Edit /JDBC_java/src/package.properties file, to specify your application package (by default, it is set to com.hibernate.demo).
2. Run the above Ant script with:

ant –f hbm2daoJNDI_JDBCTransactionFactory.xml

A generated transaction will be of form (supposing a User POJO class):

public void persist(Users transientInstance) {
log.debug("Persisting Users instance");
try {
sessionFactory.getCurrentSession().beginTransaction();
sessionFactory.getCurrentSession().persist(transientInstance);
sessionFactory.getCurrentSession().getTransaction().commit();
log.debug("Persist successful");
} catch (RuntimeException re) {
factory.getCurrentSession().getTransaction().rollback();
log.error("Persist failed", re);
throw re;
}
}

For Tomcat users, in the JDBC_java/src/ you can find a simple example of web.xml and META-INF/context.xml for configuring datasource connection through JNDI.

A possible hibernate.cfg.xml for this case will look like below:
code>
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.datasource">java:/comp/env/jdbc/usersdb
</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.transaction.factory_class">
org.hibernate.transaction.JDBCTransactionFactory</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="com/hibernate/demo/Users.hbm.xml" />
</session-factory>
</hibernate-configuration>

This post is just one of a set of Ant scripts that explores Hibernate Tools for Ant. The complete set can be downloaded from here ( http://www.filefactory.com/file/ca0a5c0/n/HibernateTools.rar ).

How to capture System.out and System.err


Sometimes you need to capture the text being written to a PrintStream by a 3rd party component. Here it is a simple solution for out and err PrintStreams:

//System.out
PipedOutputStream pipeOut = new PipedOutputStream();
PipedInputStream pipeIn = new PipedInputStream(pipeOut);
System.setOut(new PrintStream(pipeOut));
// now read from pipeIn

//System.err
PipedOutputStream pipeOut = new PipedOutputStream();
PipedInputStream pipeIn = new PipedInputStream(pipeOut);
System.setErr(new PrintStream(pipeOut));
// now read from pipeIn

Monday, March 28, 2011

How to traverse a file tree in NIO.2 and Java 7 (JDK 7)


JDK 7 and NIO.2 brings new and great I/O features – many of them are related with file system and files. Based on these features I tried to develop a simple Search File application. The idea is to provide a file name and the application will detect all system roots and search for that file – it is also a good idea to specify a starting folder with a few intuitive modifications.
Well, to accomplish this task we need two things:

java.nio.file.FileVisitor interface - has hooks for before, during, and
after a file is "visited", as well as for when failure occurs.
walkFileTree method (new in NIO.2) which can be use to traverse a tree
of directories and files. When you invoke this method, you specify the root and how
many levels deep you want to go. You can also set an attribute to indicate that it
should follow links.

Here is the Search File solution:

import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitOption;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.EnumSet;

class Search implements FileVisitor {

private final Path searchedFile;
public boolean found = false;

public Search(Path searchedFile) {
this.searchedFile = searchedFile;
}

boolean search(Path file) throws IOException{
if (file.getFileName().equals(searchedFile)) {
System.out.println("Searched file was found: " + searchedFile
+ " in " + file.toRealPath(true).toString());
found = true;
return true;
}

return false;
}

@Override
public FileVisitResult postVisitDirectory(Object dir, IOException exc)
throws IOException {
System.out.println("Visited: " + (Path) dir);
return FileVisitResult.CONTINUE;
}

@Override
public FileVisitResult preVisitDirectory(Object dir, BasicFileAttributes attrs)
throws IOException {
return FileVisitResult.CONTINUE;
}

@Override
public FileVisitResult visitFile(Object file, BasicFileAttributes attrs)
throws IOException {
boolean success = search((Path) file);
if (!success) {
return FileVisitResult.CONTINUE;
} else {
return FileVisitResult.TERMINATE;
}
}

@Override
public FileVisitResult visitFileFailed(Object file, IOException exc)
throws IOException {
return FileVisitResult.CONTINUE;
}
}

class Main {

public static void main(String[] args) throws IOException {

Path searchDir = null;
File[] roots = File.listRoots();
Path searchFile = Paths.get("rafa.png"); //this is the searched file
Search go = new Search(searchFile);
EnumSet opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);

for (File root : roots) {
if (!go.found) {
searchDir = Paths.get(root.getPath());
Files.walkFileTree(searchDir, opts, Integer.MAX_VALUE, go);
}
}

if (!go.found) {
System.out.println("The file " + searchFile + " was not found!");
}
}
}

How to list the system roots (very useful for Windows)


Have you ever need to get all root of your system (C:/, D:/, E:/ etc) ? It is very simple with the below code:

...
File[] roots = File.listRoots();
for (File root : roots) {
System.out.println(root);
}
...

Possible output:

C:\
D:\
E:\

Thursday, March 24, 2011

How to upload with PrimeFaces under Tomcat 6


Download a complete example tested under Tomcat 6 from here.


In last few months I’ve notice a big interest for the Prime Faces upload solution. I can’t say that I’m surprise, since it is a very good looking upload, easy to configure and use. Therefore, I’ve decide to provide a small guide to implement Prime Faces upload under a Tomcat 6 web application.
For start, you will need the following JARs, under your /lib folder (you can take them separately from web, or if you take this complete example from http://www.filefactory.com/file/ca41567/n/prime_faces_upload.rar, then they are already included):

• primeface-2.2.RC2.jar (this is what I’ve used, but you can take the latest
Prime Faces library from PrimeFaces site – http://www.primefaces.org).
• jsf-api-2.0.2-FCS.jar (again, take the latest, if you consider that you need it)
• jsf-impl-2.0.2-FCS.jar
• el-api-2.2.jar
• el-impl-2.2.jar
• commons-io-1.4.jar
• commons-fileupload-1.2.jar

Next, I’ve configure the application descriptor, web.xml (depending on Prime Faces version, these configurations may be slightly different). In this descriptor I’ve configured Prime Faces upload filter:

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
<context-param>
<description>Context param for JSTL 1.2 to work in Tomcat 6 sun RI
</description>
<param-name>com.sun.faces.expressionFactory</param-name>
<param-value>com.sun.el.ExpressionFactoryImpl</param-value>
</context-param>
<context-param>
<description>Parameter required by Mojarra 2.0</description>
<param-name>com.sun.faces.allowTextChildren</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>javax.faces.VALIDATE_EMPTY_FIELDS</param-name>
<param-value>true</param-value>
</context-param>
<filter>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
<init-param>
<param-name>thresholdSize</param-name>
<param-value>2097152</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
<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.xhtml</welcome-file>
</welcome-file-list>
</web-app>

Next, I wrote a simple JSF page to test the Prime Faces upload component:

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.prime.com.tr/ui">
<h:head>
</h:head>
<h:body>
<h:outputText value="Select the files to upload (maxim 2MB):"/>
<p:growl id="uploadMessages" showSummary="true" showDetail="true"/>
<h:form enctype="multipart/form-data" prependId="false">
<p:fileUpload update="uploadMessages"
fileUploadListener="#{fileUploadController.handleFileUpload}"
sizeLimit="2097152"
multiple="true"
label="choose"
allowTypes="*.jpg;*.png;*.gif;"
description="Images"/>
</h:form>
</h:body>
</html>

As you can see, p:fileUpload is very flexible and customizable, allowing us to specify upload characteristics with a few simple attributes. Going further, we need a managed bean capable of dealing with upload itself. A possible implementation (probably not the best, but for sure not the worst) is listed below:

package com.extensions;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.faces.FacesException;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import org.primefaces.event.FileUploadEvent;

@ManagedBean(name = "fileUploadController")
@RequestScoped
public class uploadFilesBean {

//Primitives
private static final int BUFFER_SIZE = 6124;
private String folderToUpload;

/** Creates a new instance of UploadBean */
public uploadFilesBean() {
}

public void handleFileUpload(FileUploadEvent event) {

ExternalContext extContext=FacesContext.getCurrentInstance().getExternalContext();

File result = new File(extContext.getRealPath("//WEB-INF//files//" +
event.getFile().getFileName()));
//System.out.println(extContext.getRealPath("//WEB-INF//files//" +
// event.getFile().getFileName()));

try {
FileOutputStream fileOutputStream = new FileOutputStream(result);

byte[] buffer = new byte[BUFFER_SIZE];

int bulk;
InputStream inputStream = event.getFile().getInputstream();
while (true) {
bulk = inputStream.read(buffer);
if (bulk < 0) {
break;
}
fileOutputStream.write(buffer, 0, bulk);
fileOutputStream.flush();
}

fileOutputStream.close();
inputStream.close();

FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName()
+ " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);

} catch (IOException e) {
e.printStackTrace();

FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR,
"The files were not uploaded!", "");
FacesContext.getCurrentInstance().addMessage(null, error);
}
}
}

The uploaded files goes to /WEB-INF/files folder.

Here it is a nice screenshot of Prime Faces upload:

That was a simple example of Prime Faces upload. Do not hesitate to follow Prime Faces - ShowCase site (http://www.primefaces.org/showcase/ui/fileUploadHome.jsf) where you can see more types of uploads supported by Prime Faces.

Download a complete example tested under Tomcat 6 from here.

How to upload with Postlet Applet in Java


Download a complete example tested under Tomcat 6 from here.


Postlet is a Java applet used for uploading files to web servers. It supports multiple file uploading using a nice and easy to use design. Postlet provide 4 main features:

• File progress bar
• Error checking
• Easy selection and upload of multiple files
• Resizing of images over a set size

For start, you must download Postlet, the Java applet upload, from http://postlet.com/. Extract the postlet.jar under your web application.

The applet is customizable through a set of parameters:

• destination - which is the URL to your servlet that will accept file upload
• language - which is the language to use for Postlet's user interface
• backgroundcolour - which is the color to use for Postlet background
• tableheadercolour - which is the colour to use for the text of the Table Headers
• tableheaderbackgroundcolour - which is the colour to use for the background of
the Table Headers
• fileextensions - which is a list of the file extensions
• warnmessage - which is the ability to show a warning message once the upload
button is pressed. It’s value can be “true” or “false”
• autoupload - which is the ability to automatically upload files once they are
selected. It’s value can be “true” or “false”
• helpbutton - which is the ability to show a help button. It works on versions
newer than 0.10.0 and it’s value can be “true” or “false”
• maxpixels - which is the maximum number of pixels allowed for GIF, JPEG and PNG
images when there are uploaded. If files exceed this limit, they are resized to
the set limit. If are resized GIF images, there are uploaded as PNG images. It
works on version newer than 0.13.
• helppage - which is the URL to show if the user clicks the help button. The
default URL is to http://www.postlet.com/help/
• maxthreads - which is the maximum number of connections to use. It can takes
values from 1 to 5.
• Endpage - which is the URL to take the user to once upload has completed.
• Failedfilesmessage - which is the ability to show the popup message listing the
files that failed to upload

A possible configuration is listed below:

<applet name="postlet" code="Main.class"
archive="./applets/postlet.jar" width="850" height="150" mayscript>
<param name = "maxthreads" value = "5" />
<param name = "language" value = "" />
<param name = "type" value = "application/x-java-applet;version=1.3.1" />
<param name = "destination"
value = "http://localhost:8085/PostletUpload/applet_upload" />
<param name = "backgroundcolour" value = "56328145" />
<param name = "tableheaderbackgroundcolour" value = "24279327" />
<param name = "tableheadercolour" value = "0" />
<param name = "warnmessage" value = "false" />
<param name = "autoupload" value = "false" />
<param name = "helpbutton" value = "false" />
<param name = "fileextensions" value = "Image Files,jpg,gif,jpeg" />
<param name = "endpage" value = "[*** ENDPAGE URL***]" />
<param name = "helppage"
value = "http://www.postlet.com/help/?thisIsTheDefaultAnyway" />
</applet>

When the uploads ends, a JavaScript function can fire up a message:

<script type="text/javascript">
function postletFinished(){
alert("Postlet Applet Succesfully Accomplished its Job!"); }
</script>

For this application (on the server side) you can use the COS described in this post How to upload in Java (Upload using the COS library). Notice the messages returned by the server should by specific to Postlet Upload – http://postlet.com/ you can see the entire list of possible responses. The COS implementation for Postlet Upload is:

public class AppletUploadServlet extends HttpServlet {

protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

final int permitedSize = 314572800; //~ 300 MB bytes
final String[] extensions = {".zip",".xls"};

StringBuffer answer = new StringBuffer();
answer.append("POSTLET REPLY\nPOSTLET:YES\nEND POSTLET REPLY\n");

PrintWriter out = response.getWriter();
response.setContentType("text/html;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "No-cache");
response.setDateHeader("Expires",0);

try{
String strDirectory = "files";
String uploadPath = request.getRealPath("//WEB-INF//"+strDirectory+"//");

//or, like this, from web.xml
String uploadPath_rezerva = request.getRealPath(getServletConfig().
getInitParameter("uploadPath"));

MultipartRequest multipartRequest = new MultipartRequest(request,
uploadPath, permitedSize, "ISO-8859-1", new DefaultFileRenamePolicy());

Enumeration files = multipartRequest.getFileNames();

String extension1 = "";
String extension2 = "";
String filename = "";

while (files.hasMoreElements())
{
String name = (String)files.nextElement();
filename = multipartRequest.getFilesystemName(name);
String originalFilename = multipartRequest.getOriginalFileName(name);

extension1 = filename.substring(filename.length() - 4, filename.length());
extension2 = originalFilename.substring(originalFilename.length() - 4,
originalFilename.length());

//use O'Reilly COS
File currentFile = multipartRequest.getFile(name);
}

out.println(answer);

}catch (Exception exception)
{
answer.delete(0, answer.length());
answer.append("POSTLET REPLY\nPOSTLET:NO\nPOSTLET:SERVER ERROR\n
POSTLET:ABORT ALL\nEND POSTLET REPLY\n");

out.println(answer);
} finally { if(out != null) {out.close();} }
}
}

The result of this application is shown below in figure below:



Download a complete example tested under Tomcat 6 from here.

Introducing AppDynamics - Application Management for the Cloud Generation


Official site: http://litedocs.appdynamics.com/

This post wants to be just a discover point of a great tool named AppDynamics, therefore major content is taken from the official site. AppDynamics does not reinvent the wheel, but it brings some cool stuff in the application performance management solutions. First, I was impress of how easy is to install, configure and start working with it. Try it yourself!

What's unique about AppDynamics ?

AppDynamics has developed a next-generation Application Performance Management solution that's distinct in four ways:

• We are the first product built from the ground up for highly distributed
service-oriented environments.
• We enable fast root cause diagnostics at the method/class level, but create no
more than 2% overhead-even in high-volume production deployments.
• We are able to not only manage applications, but dynamically scale them in
cloud and virtual environments.
• We cost a fraction of legacy old-school Application Performance Management
solutions!

Watch these short 2 minute videos to learn more about some of AppDynamics' capabilities:

1. Application Mapping - Auto-discover and map entire distributed applications

2. Transaction Flow Monitoring - Follow transaction requests from tier to tier, and enable instand troubleshooting of performance problems

3. Deep Diagnostics - Drill-down at the code level - find code hot spots, slow SQL calls, deadlocks, etc.

4. Policy Engine - Intelligent real-time analysis and proactive alerting

5. Cloud orchestration - Automate remediation and leverage the cloud for dynamic capacity

The unzipped AppDynamics archive contains two main tools, the Lite Viewer and Application Server Agent.

• The Lite Viewer is started by double-click on adlite-viewer.jar, and after it starts it is accessible by default on http://localhost:8990 (authenticate with admin/admin).
• The Application Server Agent can be installed on different application servers (Weblogic, Tomcat, JBoss, Websphere, Glassfish, Jetty, OSGi Containers, Tanuki service wrapper). You can find details about how to configure the agent on each of these servers on http://litedocs.appdynamics.com/, under Install the Application Server Agent section.

I have installed the Agent on Tomcat 6 in a few minutes. After I extracted the AppServerAgentLite.zip, I just edit the Tomcat Catalina.bat, by adding these lines:

rem ----- Configure AppDynamics Lite Application Server Agent
if "%1"=="stop" goto skip_agent
set JAVA_OPTS=%JAVA_OPTS% -javaagent:
"D:\AppDynamicsLite\AppServerAgentLite\javaagent.jar"
:skip_agent


That’s all! When I start Tomcat the Agent was successfully configured!

Next, I have been started the Viewer, and fire requests from some of my web applications under Tomcat. Here are some screenshots of the viewer:

• AppDynamics Dashboard
• AppDynamics Business Transactions (1)
• AppDynamics Business Transactions (2)

If you decide to download and play with AppDyanamics, it is a good idea to check http://litedocs.appdynamics.com/, Use Lite for the first time section – there you will more detailed screenshots.

Notice that in this post I have introduce AppDynamics Free, but it is also available as Pro version (30 days trial version). The Pro version brings new:

• Service level management for response times and infrastructure.
• Proactive monitoring with real-time alerting based on performance policies.
• Single-pane distributed visibility into transactions with the ability to go deep
into all tiers for user requests.
• Historical data retention (spanning years).
• Self-learning performance baselines for all performance-related data.
• Automatic triggering of deep-dive diagnostics based on recent performance.
• Centralized configuration management for agents spread across the application
topology.
• Automatic remediation of common performance problems, dynamic scaling and cloud
bursting.
• Manage the performance of mission-critical production Java applications in cloud
or physical-cloud hybrid environments.
• Automatic remediation for common performance problems like JVM/machine restarts.
• Capacity allocation using cloud/virtualization technologies based on application
semantics like Business Transaction load/service levels.
• Cloud bursting combining physical and cloud/virtualization infrastructures.

Official site: http://litedocs.appdynamics.com/

How to play with a JFileChooser open dialog (part 3)


Everybody knows what is a file chooser, therefore without any introduction here are some copy-paste examples (check the below list to see if is anything for you):

• Capture JFileChooser.SELECTED_FILE_CHANGED_PROPERTY
• Set a JLable accessory
• Change the approve button text and add a toolptip
• Set a picture preview accessory

• Capture JFileChooser.SELECTED_FILE_CHANGED_PROPERTY

JFileChooser fileChooser = new JFileChooser();

fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
fileChooser.setDialogTitle("Select a file ...");

fileChooser.addPropertyChangeListener(new PropertyChangeListener() {

public void propertyChange(PropertyChangeEvent evt) {
if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(evt.getPropertyName())) {
File file = (File) evt.getNewValue();
if (file != null) {
System.out.println(file.getName());
}
}
}
});

int result = fileChooser.showOpenDialog(null);

if (result == JFileChooser.APPROVE_OPTION) {
System.out.println("Selected path:" + fileChooser.getCurrentDirectory().toString()
+ File.separatorChar + fileChooser.getSelectedFile().getName());
}
if (result == JFileChooser.CANCEL_OPTION) {
System.out.println("Task canceled!");
}

• Set a JLable accessory

...
fileChooser.setAccessory(new LabelAccessory(fileChooser));
...

class LabelAccessory extends JLabel implements PropertyChangeListener {

public LabelAccessory(JFileChooser chooser) {
chooser.addPropertyChangeListener(this);
setPreferredSize(new Dimension(250, 50));
setHorizontalAlignment(JLabel.CENTER);
}

public void propertyChange(PropertyChangeEvent changeEvent) {
String changeName = changeEvent.getPropertyName();
if (changeName.equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) {
File file = (File) changeEvent.getNewValue();
if (file != null) {
setText(file.getName());
}
}
}
}



• Change the approve button text and add a toolptip

...
fileChooser.setApproveButtonText("Pick me! Pick me!");
fileChooser.setApproveButtonToolTipText("Open your favorite file ...");
...



• Set a picture preview accessory

...
PreviewImg previewImg = new PreviewImg();
fileChooser.setAccessory(previewImg);
fileChooser.addPropertyChangeListener(previewImg);
...
static class PreviewImg extends JPanel implements PropertyChangeListener {

private JLabel label;
private int miw;

public PreviewImg() {
setLayout(new BorderLayout(2, 2));
setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
add(new JLabel("Preview:"), BorderLayout.NORTH);
label = new JLabel();
label.setBackground(Color.BLACK);
label.setOpaque(true);
label.setPreferredSize(new Dimension(250, 250));
miw = 245;
label.setBorder(BorderFactory.createEtchedBorder());
add(label, BorderLayout.CENTER);
}

public void propertyChange(PropertyChangeEvent evt) {
Icon icon = null;
if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(evt.getPropertyName())) {
File newFile = (File) evt.getNewValue();
if (newFile != null) {
String path = newFile.getAbsolutePath();
if (path.endsWith(".jpg") || path.endsWith(".gif") || path.endsWith(".png")
|| path.endsWith(".bmp") || path.endsWith(".jpeg")) {
try {
BufferedImage img = ImageIO.read(newFile);
float width = img.getWidth();
float height = img.getHeight();
float scale = height / width;
width = miw;
height = (width * scale);
icon = new ImageIcon(img.getScaledInstance(Math.max(1, (int) width),
Math.max(1, (int) height), Image.SCALE_SMOOTH));
} catch (IOException e) {
//Some error reported!
}
}
}

label.setIcon(icon);
this.repaint();

}
}
}

How to pass JSF parameters with HTTP GET within the URL


You can find this recipe in JSF 2.0 Cookbook from Packt




In this recipe, you can see a quick method of retrieving parameters from JSF code.

Getting ready
We have developed this recipe with NetBeans 6.8, JSF 2.0, and GlassFish v3. The JSF 2.0 classes were obtained from the NetBeans JSF 2.0 bundled library.

How to do it...
You can retrieve parameters using the #{param.parameter_name} expression, such as the following (notice that the parameter is named id, and we are using #{param.id} to retrieve its value):

<h:form id="formId">
<h:commandButton id="btn1Id" value="Pass parameter 100 ..."
onclick="window.open('pagetwo.xhtml?id=100', 'MyWindow', 'height=350,
width=250, menubar=no,toolbar=no'); return false;" />
</h:form>
...
<h:outputText value="The parameter passed is: #{param.id}" />
...

Another solution is to retrieve the value through a managed bean, as shown next:

<h:form id="formId">
<h:commandButton id="btn2Id" value="Pass parameter 200 ..."
onclick="window.open('pagethree.xhtml?id=200', 'MyWindow', 'height=350,
width=250,menubar=no,toolbar=no'); return false;" />
</h:form>
...
<h:outputText value="The parameter passed is: #{bean.passedParameter}"/>
...

The managed bean that actually retrieves the parameter value is:

package bean;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

@ManagedBean
@RequestScoped
public class Bean {

private String passedParameter;

public String getPassedParameter() {
FacesContext facesContext = FacesContext.getCurrentInstance();
this.passedParameter = (String) facesContext.getExternalContext().
getRequestParameterMap().get("id");
return this.passedParameter;
}

public void setPassedParameter(String passedParameter) {
this.passedParameter = passedParameter;
}
}

How it works...
In the first example, the task is performed by the EL, #{param.parameter_name}, while, in the second example, the managed bean uses the getRequestParameterMap function, which has access to the GET request parameters.



You can find this recipe in JSF 2.0 Cookbook from Packt

How to work with JSF hidden fields from JavaScript


You can find this recipe in JSF 2.0 Cookbook from Packt




The idea of putting together JSF hidden fields and JavaScript comes from a simple question—how to use JavaScript and JSF to submit a form from a control event? In other words you will see how to submit a form immediately after a checkbox is checked or unchecked (it is simple to imagine how to apply this solution for other components such as radio buttons).

Getting ready
We have developed this recipe with NetBeans 6.8, JSF 2.0, and GlassFish v3. The JSF 2.0 classes were obtained from the NetBeans JSF 2.0 bundled library.

How to do it...
The solution is pretty simple, but the idea it self is ingenious and involves JavaScript and JSF command links. First we write a simple JSF form (this form will be submitted when the checkbox is checked / unchecked):

<h:form id="myForm">
<h:selectBooleanCheckbox id="checkbox" value="#{participateBean.participate}"
title="Click it to select or deselect"
onclick="submitForm('myForm:hiddenCommandLink');"/>
<h:outputText value="Want to participate?"/>
</h:form>

As you can see, when the onclick event is fired (the checkbox is checked or unchecked) the submitForm JavaScript function is called. This function receives one argument, representing the id of a simple JSF h:commandLink component. This component contains the form's action (a redirection to another page) and a simple CSS style for being invisible. Putting this command link in the form will look like the following:

<h:form id="myForm">
<h:selectBooleanCheckbox id="checkbox" value="#{participateBean.participate}"
title="Click it to select or deselect"
onclick="submitForm('myForm:hiddenCommandLink');"/>
<h:outputText value="Want to participate?"/>
<h:commandLink id="hiddenCommandLink" style="display:none;visibility:hidden;"
action="response?facesredirect=true"/>
</h:form>

Now, the submitForm function simulates a click event on our command link through pure
JavaScript code:

function submitForm(commandLinkId) {
var fire = document.getElementById(commandLinkId);
if (document.createEvent) {
var eventObject = document.createEvent("MouseEvents");
eventObject.initEvent( "click", true, false );
fire.dispatchEvent(eventObject);
} else if (document.createEventObject); { fire.
fireEvent("onclick");
}
}

We didn't say anything about the ParticipateBean, since is not relevant here, it is just for
proving that the submission really works.

How it works...
When users check/uncheck the form's checkbox, the onclick event is fired and the JS submitForm is called. The secret is that this function received the id of a command link—which is in the JSF form—and it is able to submit this form through its action attribute.
This action is forced by JavaScript code by dispatching an artificial click event for the command link.

There's more...
You can use this recipe for any other JSF component. For example, you may want to submit a form after a radio button is selected, or after a character is typed in a text field, or a combo-box item is selected and so on. The principle remains the same, except that you need to fi re up the correct event (such as onclick or onchange), depending on the JSF component.



You can find this recipe in JSF 2.0 Cookbook from Packt

Tuesday, March 22, 2011

How to render a CSS alert


Alerts! Always jump at the heigher Z-order in the center of the screen. Sometimes very useful, othertimes boring, but for sure when they aren't read, they were "carying" an important message. Who did not skip an important alert, and the read all the followings ?

Well, CSS can help you to render a frendly alert, not a box as JavaScript, but a nice message. The CSS is:

.alert {
background: #fff6bf url(../images/rafa.jpg) center no-repeat;
background-position: 20px 50%;
text-align: right;
padding: 15px 15px 15px 15px;
border-top: 3px solid #cc0000;
border-bottom: 3px solid #cc0000;
font: bold 11px Verdana, sans-serif;
width: 50%;
}

Now you can alert something, by writing a paragraph that uses the CSS above class:

<p class="alert">Today I will play the final at Indian Wells with Novak Djockovic!</p>

Here it is a nice CSS alert:

How to render a CSS Lightbox style


CSS hover can do a hocus-pocus to deliver a simple Lightbox to your page. Anyway, do not get to excited, is not that cool as a JavaScript Lightbox, but you know … it works when your aim is to avoid JavaScript. Therefore, here it is:

The CSS is straightforward:

body
{
margin: 0 auto;
padding: 10px;
position: relative;
width: 500px;
}

.gallery a .seeit
{
display: none;
}

.gallery a:hover .seeit
{
display: block;
position: absolute;
top: -43px;
left: -65px;
z-index: 100;
}

.gallery img
{
background: #ccccff;
border-color: #cccccc;
border-style: solid;
border-width: 1px;
padding: 5px;
vertical-align: top;
width: 60px;
height: 43px;
}

.gallery li
{
background: #eeefff;
display: inline;
float: left;
margin: 3px;
padding: 3px;
position: relative;
}

.gallery .seeit
{
border-color: #ccccdd;
width: 200px;
height: 150px;
}

A quick HTML test to render the number 1 ATP:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Rafael Nadal Image Gallery</title>
<link rel="stylesheet" href='css/gallery.css'
type="text/css" media="screen, projection" />
</head>

<body>
<h3>Rafael Nadal Image Gallery</h3>
<ul class="gallery">
<li>
<a href="http://www.rafaelnadal.com/">
<img src="rafael/rafa_1.jpg"/>
<img class="seeit" src="rafael/rafa_1.jpg"/></a>
</li>
<li>
<a href="http://www.rafaelnadal.com/">
<img src="rafael/rafa_2.jpg"/>
<img class="seeit" src="rafael/rafa_2.jpg"/></a>
</li>
<li>
<a href="http://www.rafaelnadal.com/">
<img src="rafael/rafa_3.jpg"/>
<img class="seeit" src="rafael/rafa_3.jpg"/></a>
</li>
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
<li>
<a href="http://www.rafaelnadal.com/">
<img src="rafael/rafa_14.jpg"/>
<img class="seeit" src="rafael/rafa_14.jpg"/></a>
</li>
<li>
<a href="http://www.rafaelnadal.com/">
<img src="rafael/rafa_15.jpg"/>
<img class="seeit" src="rafael/rafa_15.jpg"/></a>
</li>
</ul>
</body>
</html>

And a screenshot:

How to use hbm2cfgxml to generate Hibernate JPA configuration file


Hibernate Tools it is used as the basis for both the Ant tasks and the Eclipse plugins - both available from tools.hibernate.org.

Hibernate Configuration file exporter (<hbm2cfgxml>)
In this post, you can see a complete Ant script that uses the <hbm2cfgxml> exporter to generate a hibernate.cfg.xml in JPA style. As prerequisites, we have a META-INF/persistence.xml file in a folder named properties:

<?xml version="1.0" encoding="UTF-8"?>
<persistence
xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="unitTest">
<properties>
<property name="hibernate.connection.driver_class"
value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.url"
value="jdbc:mysql://localhost:3306/usersdb"/>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.password" value="root"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
</properties>
</persistence-unit>
</persistence>

Based on this file, we have created the below Ant script that generates the hibernate.cfg.xml configuration file (the file is generated into a folder, named hbm2cfgjpa_gen):

<project name="Hibernate Tools for Ant - hbm2cfg_jpa" default="generate">

<!-- Hibernate Tools libraries -->
<property name="librariesdir" value="./libs"/>

<!-- Hibernate Tools libraries paths -->
<path id="libraries">
<fileset dir="${librariesdir}">
<include name="*.jar"/>
</fileset>
</path>

<!-- Directory where the generated .cfg.xml file is saved -->
<property name="build.dir.hbm2cfg_jpa" value="./hbm2cfgjpa_gen"/>

<!-- Define the "hibernatetool" task -->
<taskdef name="hibernatetool" classname="org.hibernate.tool.ant.HibernateToolTask"
classpathref="libraries" />

<!-- Clean the exiting CFG files -->
<target name="clean">
<delete includeemptydirs="true">
<fileset dir="${build.dir.hbm2cfg_jpa}" includes="**/*"/>
</delete>
</target>

<!-- Generating hibernate configuration file via hbm2cfgxml from a basic
persistence.xml -->
<target name="generate" depends="clean">
<hibernatetool destdir="${build.dir.hbm2cfg_jpa}">
<classpath>
<path location="./persistence"/>
</classpath>
<jpaconfiguration persistenceunit="unitTest"/>
<hbm2cfgxml ejb3="${ejb3}" />
</hibernatetool>
</target>
</project>

The Ant script is named hbm2cfg_jpa.xml. It runs from command line prompt by:

${your_location}>ant –f hbm2cfg_jpa.xml

A possible output is listed below:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.connection.autocommit">true</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver
</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.release_mode">auto
</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/usersdb
</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.ejb.discard_pc_on_close">false</property>
<property name="hibernate.query.jpaql_strict_compliance">true</property>
<property name="hibernate.transaction.factory_class">
org.hibernate.transaction.JDBCTransactionFactory</property>
<property name="hibernate.transaction.flush_before_completion">false
</property>
<property name="hibernate.use_identifier_rollback">false</property>
</session-factory>
</hibernate-configuration>

This post is just one of a set of Ant scripts that explores Hibernate Tools for Ant. The complete set can be downloaded from here ( http://www.filefactory.com/file/ca0a5c0/n/HibernateTools.rar ).

Saturday, March 19, 2011

How to copy a static HashMap into a JTable


It was a sunny day with easy code and birds singing. But, suddenly a static HashMap (it could be non-static, also) wants to be copied into a two columns JTable, keys on first column, and values on the second one. Well, the clouds start to press and before I notice it start to rain … “with questions”:

- how to delete all rows of a JTable (I need this because sometimes I have to
refresh the JTable for 0) ?
- how to obtain the keys from the JTable by index, or similar?
- How to add or insert the HashMap elements into JTable ?

Oh, sorry, I forgot to introduce you my static HashMap, nothing special, just a trivial one – the elements are irrelevant, therefore I’ll skip it:

public class MyMapHostClass {
...
public static Map myMap = new HashMap();
...
}

Afterwards, it proves to be a summer rain, warm and refreshing, because the answers jump up in a few minutes: delete all rows using a backward loop (or a nice trick) – both here, get all keys with the keySet method, and insert/add them into JTable with insertRow/addRow method. Well, I glue all these answers into lines code, and get this:

...
DefaultTableModel model = (DefaultTableModel) jTable.getModel();
...
//remove all rows
model.getDataVector().removeAllElements();
...
//get all keys – notice the static effect, you can use it for non-static HashMap either
Set keys = MyMapHostClass.myMap.keySet();

//get an Iterator over keys
Iterator iteratorKeys = keys.iterator();

//put them into jTable
while (iteratorKeys.hasNext()) {
String key = (String) iteratorKeys.next();
//insert on first position by pushing down the existing rows
model.insertRow(0, new Object[]{key, MyMapHostClass.myMap.get(key)});
//append at the end
model.addRow(new Object[]{key, MyMapHostClass.myMap.get(key)});
}

Done! Now, is still raining, but … I’m singing in the rain!

How to remove all rows of a JTable


Well, if this task appears into your application then you will be probably tempted to jump over the below magic lines of code (I was!):

DefaultTableModel model = (DefaultTableModel) ${jTable}.getModel();

for (int i = 0; i< model.getRowCount(); i++) {
model.removeRow(i);
}

Mmmmm … that not so magic because when you will test the application some rows will still be there. Following a simple logic will reveal the explanation - imagine that your model contains (in this order) : A, B and C

Your getRowCount equals 3

loop 1 : remove index 0 , A (B comes to index 0 , C comes to index 1)
loop 2 : remove index 1 , C
loop 3 : remove index 2 , but there is nothing at index 2 anymore !

Being aware of this “issue”, you can solve the problem like this:

for (int i = model.getRowCount() - 1; i >= 0; i--) {
model.removeRow(i);
}

Or, a real magic:

model.getDataVector().removeAllElements();

Well, that was a nice trick!

How to create your own clock


This tip is an example of how you can display a simple clock on you’re website using the JavaScript Date Object.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Create you're own clock</title>
<script type="text/javascript">
function startTime()
{
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();

// add a zero in front of numbers<10
m = checkTime(m);
s = checkTime(s);
document.getElementById('clock').innerHTML = h +" : "+ m +" : "+ s;
t = setTimeout('startTime()',500);
getDay();
}

function checkTime(i)
{
if (i < 10)
{
i = "0" + i;
}
return i;
}
function getDay()
{
var date = new Date();

var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";

var months = new Array(12);
months[0] = "January";
months[1] = "February";
months[2] = "March";
months[3] = "April";
months[4] = "May";
months[5] = "June";
months[6] = "July";
months[7] = "August";
months[8] = "September";
months[9] = "October";
months[10] = "November";
months[11] = "December";

var week = weekday[date.getDay()];
var day = date.getDate();
var month = months[date.getMonth()];
var year = date.getFullYear();
document.getElementById('day').innerHTML = week + ", " + day;
document.getElementById('year').innerHTML = month + " " + year;
}
</script>
<style type="text/css">
.date
{
font-family: "Comic Sans MS", cursive, sans-serif;
font-weight: bold;
}
</style>
</head>

<body onload = "startTime();">
<div class="date" id = "clock"></div>
<div class="date" id ="day"></div>
<div class="date" id = "year"></div>
</body>
</html>

And the result is :

How to get a JSF inputText value from JavaScript


You can find this recipe in JSF 2.0 Cookbook from Packt




In the next example we will type text in a JSF h:inputText component, and after each character is typed, a JavaScript alert box will reveal the text inserted so far.

Getting ready
We have developed this recipe with NetBeans 6.8, JSF 2.0, and GlassFish v3. The JSF 2.0 classes were obtained from the NetBeans JSF 2.0 bundled library.

How to do it...
The secret of our recipe consists in using the onkeyup event for calling a JavaScript function. Here it is the code:

<h:head>
<script type="text/javascript" language="javascript">
function getInputText(text)
{
alert(text.value);
}
</script>
</h:head>
<h:body>
<h:inputText id="inputId" value="" onkeyup ="getInputText(this);"/>
</h:body>

How it works...
When a character is typed in the h:inputText , the onkeyup event is fired and the JavaScript getInputText function is called. This JS function extracts the text from the JSF h:inputText through the received argument. Notice that the this keyword is used.



You can find this recipe in JSF 2.0 Cookbook from Packt


How to integrate JavaScript and JSF


You can find this recipe in JSF 2.0 Cookbook from Packt




JSF and JavaScript can combine their forces to develop powerful applications. For example, let's see how we can use JavaScript code with h:commandLink and h:commandButton to obtain a confirmation before getting into action.

Getting ready
We have developed this recipe with NetBeans 6.8, JSF 2.0, and GlassFish v3. The JSF 2.0 classes were obtained from the NetBeans JSF 2.0 bundled library.

How to do it...
As you know the h:commandLink takes an action after a link is clicked (on the mouse click event), while h:commandButton does the same thing, but renders a button, instead of a text link. In this case, we place a JavaScript confirmation box before the action starts its effect. This is useful in user tasks that can't be reversed, such as deleting accounts, database records, and so on.

Therefore, the onclick event was implemented as shown next:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>JSF and JavaScript example</title>
</h:head>
<h:body>
<!-- using h:commandLink and JavaScript -->
<h:form id="myCLForm">
<h:commandLink id="cmdlinkID" value="Delete record"
onclick="if (!confirm('Are you sure you want to delete the current record?'))
return false" action="#{bean.deleteRecord}"/>
</h:form>
<!-- using h:commandButton and JavaScript -->
<h:form id="myCBForm">
<h:commandButton id="cmdbtnID" value="Delete record"
onclick="if (!confirm('Are you sure you want to delete the current record?'))
return false" action="#{bean.deleteRecord}"/>
</h:form>
</h:body>
</html>

How it works...
Notice that we embed the JavaScript code inside the onclick event (you also may put it separately in a JS function, per example). When the user clicks the link or the button, a JS confirmation box appear with two buttons. If you confirm the choice, the JSF action takes place, while if you deny it then nothing happens.

There's more...
You can use this recipe to display another JS box, such as prompt box or alert box.



You can find this recipe in JSF 2.0 Cookbook from Packt

How to play with a JFileChooser open dialog (part 2)


Everybody knows what is a file chooser, therefore without any introduction here are some copy-paste examples (check the below list to see if is anything for you):

• Copying the filename path from a JFileChooser to the Clipboard
• Set and get the current directory of a JFileChooser
• Getting the File-Type Name of a File
• Capture JFileChooser.DIRECTORY_CHANGED_PROPERTY
• Put JFileChooser.showOpenDialog result in a nice switch-case

Copying the filename path from a JFileChooser to the Clipboard - typing CTRL-C in a file chooser dialog copies the names of the selected files to the clipboard.

Per example, I’ve done that for a few folders and here it is the clipboard content:

D:\articlesAlin\figures\Maven article
D:\articlesAlin\figures\UML article
D:\articlesAlin\figures\Upload article

Set and get the current directory of a JFileChooser

JFileChooser fileChooser = new JFileChooser();

fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
fileChooser.setDialogTitle("Select a file ...");

try {
// Create a File object containing the canonical path of the desired directory
File file = new File(new File(".").getCanonicalPath());
// Set the current directory to the home directory
//fileChooser.setCurrentDirectory(null);

// Set the current directory
fileChooser.setCurrentDirectory(file);
} catch (IOException e) {
//...
}

int result = fileChooser.showOpenDialog(null);

if (result == JFileChooser.APPROVE_OPTION) {
System.out.println("Selected folder:"
+ fileChooser.getCurrentDirectory().toString());
System.out.println("Selected path:" + fileChooser.getCurrentDirectory().toString()
+ File.separatorChar + fileChooser.getSelectedFile().getName());
}
if (result == JFileChooser.CANCEL_OPTION) {
System.out.println("Task canceled!");
}

Getting the File-Type Name of a File

JFileChooser fileChooser = new JFileChooser();

fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
fileChooser.setDialogTitle("Select a file ...");

int result = fileChooser.showOpenDialog(null);

if (result == JFileChooser.APPROVE_OPTION) {
System.out.println("File type: "
+ fileChooser.getTypeDescription(fileChooser.getSelectedFile()));
}
if (result == JFileChooser.CANCEL_OPTION) {
System.out.println("Task canceled!");
}

Some outputs:

File type: Text Document
File type: Remote Desktop Connection
File type: PNG image

Capture JFileChooser.DIRECTORY_CHANGED_PROPERTY

JFileChooser fileChooser = new JFileChooser();

fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
fileChooser.setDialogTitle("Select a file ...");

fileChooser.addPropertyChangeListener(new PropertyChangeListener() {

public void propertyChange(PropertyChangeEvent evt) {
if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(evt.getPropertyName())) {
JFileChooser chooser = (JFileChooser) evt.getSource();
File oldDirectory = (File) evt.getOldValue();
File newDirectory = (File) evt.getNewValue();
File curDirectory = chooser.getCurrentDirectory();

System.out.println("Old directory: " + oldDirectory.getName());
System.out.println("New directory: " + newDirectory.getName());
System.out.println("Current directory: " + curDirectory);
}
}
});

int result = fileChooser.showOpenDialog(null);

if (result == JFileChooser.APPROVE_OPTION) {
System.out.println("Selected path: "
+ fileChooser.getCurrentDirectory().toString()
+ File.separatorChar + fileChooser.getSelectedFile().getName());
}
if (result == JFileChooser.CANCEL_OPTION) {
System.out.println("Task canceled!");
}

Put JFileChooser.showOpenDialog result in a nice switch-case

JFileChooser fileChooser = new JFileChooser();

fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
fileChooser.setDialogTitle("Select a file ...");

int result = fileChooser.showOpenDialog(null);

switch (result) {
case JFileChooser.APPROVE_OPTION:
System.out.println("Approve was clicked");
break;
case JFileChooser.CANCEL_OPTION:
System.out.println("Cancel was clicked");
break;
case JFileChooser.ERROR_OPTION:
System.out.println("Error ... error ... error ...");
break;
}

Friday, March 18, 2011

How to upload in Java ( YUI Uploader and Java)


Download a complete example tested under Tomcat 6 from here.


The YUI Uploader is a great upload component from Yahoo. This is a customizable component, with a great design that can accomplish from simple uploads to complex ones. Specifically, the YUI Uploader allows for (this features are taken from YUI Uploader site):

• Multiple file selection in a single "Open File" dialog.
• File extension filters to facilitate the user's selection.
• Progress tracking for file uploads.
• A range of available file metadata: filename, size, date created, date modified, and author.
• A set of events dispatched on various aspects of the file upload process: file selection, upload progress, upload completion, etc.
• Inclusion of additional data in the file upload POST request.
• Faster file upload on broadband connections due to the modified SEND buffer size.
• Same-page server response upon completion of the file upload.

In this post, you will see how to implement the YUI Uploader into a web application build in a Java context. For start, you must download YUI Uploader from here. Depending on the web application context, to use the Uploader Control, include the following source files in your web page (in this example you stored the YUI Uploader into a folder named /yui under application root):

<script type="text/javascript" src="yui/build/yahoo-dom-event/yahoo-dom-event.js">
</script>
<script type="text/javascript" src="yui/build/element/element-min.js"></script>
<script type="text/javascript" src="yui/build/uploader/uploader-min.js"></script>

Next, you can place the code necessary for configure the YUI Uploader. First, you can see a few details about each representative chunk of code, and after that you will see the code :

First of all, you need to specify the path (relative to the page or absolute) of the uploader.swf file to the location of the HTML page in which a Uploader Control instance will appear and then render the uploader as a button.

// Instantiate the uploader and write it to its placeholder div.
YAHOO.widget.Uploader.SWFURL = "yui/resources/uploader.swf";
var uploader = new YAHOO.widget.Uploader( "uploaderUI",
"yui/resources/selectFileButton.png");

The Uploader has a number of methods that allows you to manage the upload process and dispatches various events for different aspects of the upload process. To add event listeners to various events called by the uploader you may do like this :

// Add event listeners to various events on the uploader.
// Methods on the uploader should only be called once the contentReady event has
// fired.
uploader.addListener('contentReady', handleContentReady);
uploader.addListener('fileSelect',onFileSelect)
uploader.addListener('uploadStart',onUploadStart);
uploader.addListener('uploadProgress',onUploadProgress);
uploader.addListener('uploadCancel',onUploadCancel);
uploader.addListener('uploadComplete',onUploadComplete);
uploader.addListener('uploadCompleteData',onUploadResponse);
uploader.addListener('uploadError', onUploadError);

Now, you need to define the event handlers. The first event that you need to create should be the contentReady witch will enable the logging output in the uploader (the log messages will be output both to the YUI Logger, and the Flash trace output), disallow multiple file selection and set file filters to filter user selection.

function handleContentReady () {
// Allows the uploader to send log messages to trace, as well as to YAHOO.log
uploader.setAllowLogging(true);

// Restrict selection to a single file (that's what it is by default,
// just demonstrating how).
uploader.setAllowMultipleFiles(false);

// New set of file filters.
var ff = new Array({description:"Images", extensions:"*.txt;*.jpg;*.png;*.gif"});

// Apply new set of file filters to the uploader.
uploader.setFileFilters(ff);
}

When the “Upload File” button is clicked, the upload function is called.

// Initiate the file upload. Since there's only one file,
// we can use either upload() or uploadAll() call. fileList
// needs to have been populated by the user.
function upload() {
if (fileID != null) {
uploader.upload(fileID, "http://localhost:8085/YUI_upload/oreilly_upload");
fileID = null;
}
}

When a file is selected, record the id of the selected file, disable the uploader UI, display the name of the file and reset the progress bar.

// Fired when the user selects files in the "Browse" dialog
// and clicks "Ok".
function onFileSelect(event) {
for (var item in event.fileList) {
if(YAHOO.lang.hasOwnProperty(event.fileList, item)) {
YAHOO.log(event.fileList[item].id);
fileID = event.fileList[item].id;
}
}
uploader.disable();
var filename = document.getElementById("fileName");
filename.innerHTML = event.fileList[fileID].name;
var progressbar = document.getElementById("progressBar");
progressbar.innerHTML = "";
}

The next function handles uploadProgress events, and draws a progress bar of correct size.

// Do something on each file's upload progress event.
function onUploadProgress(event) {
prog = Math.round(300*(event["bytesLoaded"]/event["bytesTotal"]));
progbar = "<div style=\"background-color: #f00; height: 5px; width: " +
prog + "px\"/>";
var progressbar = document.getElementById("progressBar");
progressbar.innerHTML = progbar;
}

Next, you need to handle the uploadComplete event, draws a full progress bar, and re-enables the uploader UI.

// Do something when each file's upload is complete.
function onUploadComplete(event) {
uploader.clearFileList();
uploader.enable();
progbar = "<div style=\"background-color: #CCCCCC; height: 5px; width: 300px\"/>";
var progressbar = document.getElementById("progressBar");
progressbar.innerHTML = progbar;
var filename = document.getElementById("fileName");
filename.innerHTML = "";
}

The code without comments is shown below:

...
<style type="text/css">
.uploadButton a, .clearButton a {
display:block;
width:100px;
height:40px;
text-decoration: none;
margin-left:5px;
}

.uploadButton a {
background: url("yui/resources/uploadFileButton.png") 0 0 no-repeat;
}

.clearButton a {
background: url("yui/resources/clearListButton.png") 0 0 no-repeat;
}

.uploadButton a:visited, .clearButton a:visited {
background-position: 0 0;
}

.uploadButton a:hover, .clearButton a:hover {
background-position: 0 -40px;
}

.uploadButton a:active, .clearButton a:active {
background-position: 0 -80px;
}
</style>

<div>
<div id="fileProgress" style="border: black 1px solid; width:300px; height:40px;
float:left">
<div id="fileName" style="text-align:center; margin:5px;
font-size:15px; width:290px; height:25px; overflow:hidden">
</div>
<div id="progressBar" style="width:300px;height:5px;background-color:#CCCCCC"></div>
</div>
<div id="uploaderUI" style="width:100px;height:40px; margin-left:5px;float:left">
</div>
<div class="uploadButton" style="float:left">
<a class="rolloverButton" href="#" onClick="upload(); return false;"></a>
</div>
<div class="clearButton" style="float:left"><a class="rolloverButton" href="#"
onClick="handleClearFiles(); return false;"></a></div>
</div>

<script type="text/javascript">

YAHOO.widget.Uploader.SWFURL = "yui/resources/uploader.swf";
var uploader = new YAHOO.widget.Uploader( "uploaderUI",
"yui/resources/selectFileButton.png" );
uploader.addListener('contentReady', handleContentReady);
uploader.addListener('fileSelect',onFileSelect)
uploader.addListener('uploadStart',onUploadStart);
uploader.addListener('uploadProgress',onUploadProgress);
uploader.addListener('uploadCancel',onUploadCancel);
uploader.addListener('uploadComplete',onUploadComplete);
uploader.addListener('uploadCompleteData',onUploadResponse);
uploader.addListener('uploadError', onUploadError);

// Variable for holding the selected file ID.
var fileID;

function handleClearFiles() {
uploader.clearFileList();
uploader.enable();
fileID = null;

var filename = document.getElementById("fileName");
filename.innerHTML = "";

var progressbar = document.getElementById("progressBar");
progressbar.innerHTML = "";
}

function handleContentReady () {
uploader.setAllowLogging(true);
uploader.setAllowMultipleFiles(false);
var ff = new Array({description:"Images", extensions:"*.txt;*.jpg;*.png;*.gif"});
uploader.setFileFilters(ff);
}

function upload() {
if (fileID != null) {
uploader.upload(fileID, "http://localhost:8080/YUI_upload/oreilly_upload");
fileID = null;
}
}

function onFileSelect(event) {
for (var item in event.fileList) {
if(YAHOO.lang.hasOwnProperty(event.fileList, item)) {
YAHOO.log(event.fileList[item].id);
fileID = event.fileList[item].id;
}
}
uploader.disable();

var filename = document.getElementById("fileName");
filename.innerHTML = event.fileList[fileID].name;

var progressbar = document.getElementById("progressBar");
progressbar.innerHTML = "";
}

// Do something on each file's upload start.
function onUploadStart(event) {
}

function onUploadProgress(event) {
prog = Math.round(300*(event["bytesLoaded"]/event["bytesTotal"]));
progbar = "<div style=\"background-color: #f00; height: 5px; width: " +
prog + "px\"/>";
var progressbar = document.getElementById("progressBar");
progressbar.innerHTML = progbar;
}

function onUploadComplete(event) {
uploader.clearFileList();
uploader.enable();

progbar = "<div style=\"background-color: #CCCCCC; height: 5px; width: 300px\"/>";
var progressbar = document.getElementById("progressBar");
progressbar.innerHTML = progbar;

var filename = document.getElementById("fileName");
filename.innerHTML = "";
}

// Do something if a file upload throws an error.
// (When uploadAll() is used, the Uploader will
// attempt to continue uploading.
function onUploadError(event) {
}

// Do something if an upload is cancelled.
function onUploadCancel(event) {
}

// Do something when data is received back from the server.
function onUploadResponse(event) {
alert("Server response successfully received!");
}

</script>
...

For this application you can use the COS described in this post How to upload in Java (Upload using the COS library) . The result of this application is shown below in figure below:



Download a complete example tested under Tomcat 6 from here.