-
In the first part of this article, I began briefing you on optimizations I made to maximize the responsiveness of a JSF application that I developed out in the field. I cited performance problems caused by casually accessing components from a JSF view, then presented a set of best practices to eliminate this unnecessary overhead. Despite the progress made by the end of the first part, you had not yet witnessed the two orders of magnitude in performance improvement that was promised.
-
JavaServer Faces (JSF) has a reputation for having poor performance. Some claim that this "runtime tax" is simply the cost of using a component-based abstraction layer. After focused research, I have determined that by following a handful of best practices, you can get your JSF data tables to perform almost as well as hand-crafted HTML while still being able to retain the benefits of developing with an event-driven programming model. I begin by identifying some performance problems that occur when using JSF UI components, Seam components, and the EL carelessly, and then present, through a series of four lessons, ways to eliminate these problems one-by-one until you have observed a remarkable, two orders of magnitude improvement.
-
How would you implement a Plugin-system for your Java application?
Is it possible to have an easy to use (for the developer) system which achieves the following:
Users put their plugins into a subdirectory of the app
The Plugin can provide a configuration screen
If you use a framework, is the license compatible with commercial developement? -
So we know that all injected properties of a component are dynamically injected prior to business method execution. This means every time a business method is invoked whether or not those properties need to be re-freshed all of the properties marked @In are re-fresh/re-injected. So let's take a hypothetical case. Say we have 20 Seam components that need to be injected into component Foo. Would it not be more efficient to use Component.getInstance(C1.class) instead of the unnecessarily repetitive and time-consuming "swarm" of dynamic injections? For a particular business method, you get the component you need at that exact time. Instead of getting all 20 of them when you may only need one of them for that particular business method. That's overkill. Use @In except when absolutely necessary like injecting SMPC and Log instance via @Logger.
links for 2011-09-21
22 09 2011Comentarios : Leave a Comment »
Categorías : delicious
links for 2011-09-16
17 09 2011-
In this two-part tutorial you will learn how to get started with the development of Seam applications with RichFaces using Eclipse with JBoss Tools. In the 1st part we've set up our environment, created, and run an empty shell Seam application. In this 2nd part we will create a simple web page with a table presenting data on multiple pages using Ajax (a RichFaces component) and its model stored as a POJO Component in the Seam Conversation scope. I assume that you already have some basic knowledge of Seam and JSF, for instance that you know what a Component or the Conversation scope are. I'll present my path to this goal with all the mistakes so that you too can learn from them.
My aim in this tutorial series is to create a Seam portlet displaying data in a paged (and ideally also sortable and filterable, but lets be realistic) table running in the Liferay portal.
Comentarios : Leave a Comment »
Categorías : delicious
links for 2011-09-15
16 09 2011-
If you are building a web application with a user-interface for editing dates that supports time zones, then you are going to need a list of time zones. You need this if you want to edit or display times in 'local time' and store them as UTC (universal time). This article shows the Java code and a handy Seam component that provides the list.
-
The correct solution is to allow the time zone to be set per JSF application, configured in faces-config.xml. In fact, there is already an ideal place to put this configuration: within the <locale-config> element, complementing the default locale. The developer would specify a time zone ID in the <default-time-zone-id> element and JSF would resolve a TimeZone object from this ID. Here's an example showing the default time zone set to New York.
-
The <rich:calendar> component provides the possibility to use internationalization method to redefine and localize the labels. You could use application resource bundle and define RICH_CALENDAR_APPLY_LABEL, RICH_CALENDAR_TODAY_LABEL, RICH_CALENDAR_CLOSE_LABEL, RICH_CALENDAR_OK_LABEL, RICH_CALENDAR_CLEAN_LABEL, RICH_CALENDAR_CANCEL_LABEL there.
You could also pack org.richfaces.renderkit.calendar resource bundle with your JARs defining the same properties.
-
Some features of the Java language simply cannot be ignored. Consider for example interfaces, used extensively by every Java specification; or try/catch blocks, that form the basis for exception handling. Other features are more obscure – useful, but ignored by the masses. Without looking as far as volatile (probably the most obscure Java keyword), think about final. When was the last time you used final in your code?
Me, I'm a final fan. Enamored with final, I'm of the school of thought that inserts final any where, any time. Or almost. But why? In this article I shine the spotlight on the Java keyword final, and invite you to discover its subtle meanings, and the many Java idioms that make use of it. All for better code!
-
Mediator Pattern: Reducing Page Dependencies in JSF
-
Don't access the database in a method that feeds a UIData component! (e.g. <h:dataTable>) I see this mistake being made all the time. It's bad advice and just plain bad practice. Don't do it! The correct way to do this would be to bind the list to a context variable using a Seam factory component so that the list of users is populated exactly once per page, regardless of how many times the variable is resolved. Note that we are scrapping the managed bean definition and using a Seam component instead. The choice of page scope for the users variable ensures that the list is not refetched on a JSF postback either.
-
How and When To Deprecate APIs
Comentarios : Leave a Comment »
Categorías : delicious
links for 2011-09-13
14 09 2011-
$ split -b 1394786 big.log
$ ls -1 x*
xaa
xab
…
xewSplit creates its output files in decreasing alphabetic order. Thus when you list them in the shell they are in the order in which
they were split. As such, you can simply use cat to merge the files. (Thanks to Paul and Davidov for pointing out my for loop was superfluous.)$ cat x* >merged.big.log
$ ls -l *.log
-rw-rw-r– 1 brock brock 175743061 Oct 12 22:08 big.log
-rw-rw-r– 1 brock brock 175743061 Oct 12 01:11 merged.big.log
$ diff merged.big.log big.log
$ md5sum *.log
47de08911534957c1768968743468307 big.log
47de08911534957c1768968743468307 merged.big.log(cat works for files created with hjsplit, too)
Comentarios : Leave a Comment »
Categorías : delicious
links for 2011-09-09
9 09 2011-
Seam Framework – Creating Custom EL Functions
Comentarios : Leave a Comment »
Categorías : delicious
links for 2011-08-26
27 08 2011-
The way to handle this for anything other than kill -9 would be to register a shutdown hook. If you can use (SIGTERM) kill -15 the shutdown hook will work. (SIGINT) kill -2 DOES cause the program to gracefully exit and run the shutdown hooks.
I tried the following test program on OSX 10.6.3 and on kill -9 it did NOT run the shutdown hook, didn't think it would. On a kill -15 it DOES run the shutdown hook every time.public class TestShutdownHook
{
public static void main(final String[] args) throws InterruptedException
{
Runtime.getRuntime().addShutdownHook(new Thread()
{
@Override
public void run()
{
System.out.println("Shutdown hook ran!");
}
});while (true)
{
Thread.sleep(1000);
}
}
}There isn't any way to really gracefully handle a kill -9 in any program.
-
The term network programming refers to writing programs that execute across multiple devices (computers), in which the devices are all connected to each other using a network.
The java.net package of the J2SE APIs contains a collection of classes and interfaces that provide the low-level communication details, allowing you to write programs that focus on solving the problem at hand.
The java.net package provides support for the two common network protocols:
TCP: TCP stands for Transmission Control Protocol, which allows for reliable communication between two applications. TCP is typically used over the Internet Protocol, which is referred to as TCP/IP.
UDP: UDP stands for User Datagram Protocol, a connection-less protocol that allows for packets of data to be transmitted between applications.
-
I finally found a working codes for Java Socket Programming..
from http://www.tutorialspoint.com/java/java_networking.htm
Comentarios : Leave a Comment »
Categorías : delicious
links for 2011-08-17
18 08 2011-
import java.text.SimpleDateFormat;
import java.util.*;public class LocalesList {
static public void main(String[] args) {
Locale list[] = SimpleDateFormat.getAvailableLocales();
Set set = new TreeSet();
for (int i = 0; i < list.length; i++) {
set.add(list[i].getDisplayName()
+"\t\t\t:\t"+ list[i].toString());
}
Iterator it = set.iterator();
while (it.hasNext()) {
System.out.println(it.next() );
}
}
} -
<a href="#section2">Go To Section 2</a><br>
blah<br>
blah<br>
blah<br>
blah<br>
blah<br>
blah<br>
<a name="section2">Welcome To Section 2!</a> -
The aim of this post is the same as for the previous one – to cover some component specific questions in RichFaces which frequently asked at RichFaces User Forum. Some points (or maybe all of them) could be already known for you… But do not forget that everybody sometimes starts something from scratch 🙂 Thus, my intention is to help the guys who just start RichFaces usage with some kickstart samples like this.
-
Regular Expression Basic Syntax Reference
Comentarios : Leave a Comment »
Categorías : delicious
links for 2011-08-16
17 08 2011-
In CSS, pattern matching rules determine which style rules apply to elements in the document tree. These patterns, called selectors, may range from simple element names to rich contextual patterns. If all conditions in the pattern are true for a certain element, the selector matches the element.
The case-sensitivity of document language element names in selectors depends on the document language. For example, in HTML, element names are case-insensitive, but in XML they are case-sensitive.
-
<style>
<!–
a:link { color: #000099; text-decoration: none;}
a:visited { color: #CCC; text-decoration: none;}
a:active { color: #666; text-decoration: none;}
a:hover { color: #000; text-decoration: underline;}
–>
</style> -
Once a Swing component has been realized, all code that might affect or depend on the state of that component should be executed in the event-dispatching thread.
-
There are 3 ways to terminate a thread:
The thread has finished the work it is designed to do, and exits the run() method naturally.
The thread has received an interruption signal, while doing its work. It decides to not continue with work and exits the run() method. It may also decide to ignore the signal and continue to work.
The thread has been marked as daemon thread. When the parent thread who created this thread terminates, this thread will be forcefully terminated by the JVM. -
In a Swing application, most of the processing takes place in a single, special thread called the event dispatch thread.
This thread becomes active after a component becomes realized : either pack, show, or setVisible(true) has been called. When a top level window is realized, all of its components are also realized. Swing is mostly single-threaded : almost all calls to realized components should execute in the event dispatch thread. The thread-safe exceptions are
some methods of JComponent : repaint, revalidate, invalidate
all addXXXListener and removeXXXListener methods
all methods explicitly documented as thread-safe -
System.exit should be used with care. The normal method of terminating a program is to terminate all user threads.
Cases in which System.exit is appropriate :
utility scripts
GUI applications, in which the event dispatch user thread is created in the background. Here, the program may be terminated by calling System.exit, or, for example, by setting :JFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
From Sun's Portability Cookbook :
"The System.exit method forces termination of all threads in the Java virtual machine. This is drastic….System.exit should be reserved for a catastrophic error exit, or for cases when a program is intended for use as a utility in a command script that may depend on the program's exit code."
-
// : c13:Stopping.java
// The safe way to stop a thread.
// From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002
// http://www.BruceEckel.com. See copyright notice in CopyRight.txt.import java.util.Timer;
import java.util.TimerTask;class CanStop extends Thread {
// Must be volatile:
private volatile boolean stop = false;private int counter = 0;
public void run() {
while (!stop && counter < 10000) {
System.out.println(counter++);
}
if (stop)
System.out.println("Detected stop");
}public void requestStop() {
stop = true;
}
}public class Stopping {
public static void main(String[] args) {
final CanStop stoppable = new CanStop();
stoppable.start();
new Timer(true).schedule(new TimerTask() {
public void run() {
System.out.println("Requesting stop");
stoppable.requestStop();
}
}, 500); // run() after 500 milliseconds
}
} ///:~ -
How to stop a Thread is a perannual question for Java programmers. Finally with the release of Java V5.0 (or V1.5), which incorporates java.util.concurrent, a definitive answer can be given. The answer is you stop a thread by using interrupt(). This article covers some of the background to stopping threads and the suggested alternatives and discusses why interrupt() is the answer. It also discusses interrupting blocking I/O and what else the programmer needs to do to ensure their threads and tasks are stoppable.
-
Here is an example of a utility Stopwatch class which can provide timings for any section of code.
For measuring the relative execution times of alternate implementations, consider turning off the HotSpot compiler, using java -Xint. This will ensure a uniform environment for the entire duration of a program.
-
Pattern objects compile the regular expressions which are passed to them. If a regular expression is used many times, then this compilation should be performed only once.
Be wary of the these convenience methods, which compile a regular expression each time they are called:
Pattern.matches
String.matches
String.replaceAll
String.replaceFirst
String.split
Comentarios : Leave a Comment »
Categorías : delicious
links for 2011-08-09
10 08 2011-
import java.io.File;
import java.io.FileReader;
import java.io.IOException;public class Main {
public static String deserializeString(File file)
throws IOException {
int len;
char[] chr = new char[4096];
final StringBuffer buffer = new StringBuffer();
final FileReader reader = new FileReader(file);
try {
while ((len = reader.read(chr)) > 0) {
buffer.append(chr, 0, len);
}
} finally {
reader.close();
}
return buffer.toString();
}
} -
protected void processLine(String aLine){
//use a second Scanner to parse the content of each line
Scanner scanner = new Scanner(aLine);
scanner.useDelimiter("=");
if ( scanner.hasNext() ){
String name = scanner.next();
String value = scanner.next();
log("Name is : " + quote(name.trim()) + ", and Value is : " + quote(value.trim()) );
}
else {
log("Empty or invalid line. Unable to process.");
}
//no need to call scanner.close(), since the source is a String
} -
You look at Commons Exec and think "Wow – calling Runtime.exec() is easy and the Apache folks are wasting their and my time with tons of code". Well, we learned it the hard way that using plain Runtime.exec() can be a painful experience […] you are invited to delve into commons-exec and have a look at the hard lessons the easy way…
CommandLine cmdLine = new CommandLine("AcroRd32.exe");
cmdLine.addArgument("/p");
cmdLine.addArgument("/h");
cmdLine.addArgument("${file}");
HashMap map = new HashMap();
map.put("file",new File("invoice.pdf"));
commandLine.setSubstitutionMap(map);
DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
ExecuteWatchdog watchdog=new ExecuteWatchdog(60*1000);
Executor executor = new DefaultExecutor();
executor.setExitValue(1);
executor.setWatchdog(watchdog);
executor.execute(cmdLine, resultHandler);
//some time later the result handler callback was invoked so we can safely request the exit value
int exitValue=resultHandler.waitFor(); -
Apache Commons-exec samples
-
Commons exec provides a PumpStreamHandler which redirects standard output to the Java process' standard output. How can I capture the output of the command into a String? He're what I found:
import java.io.ByteArrayOutputStream;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.Executor;
import org.apache.commons.exec.PumpStreamHandler;public String execToString(String command) throws Exception {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
CommandLine commandline = CommandLine.parse(command);
DefaultExecutor exec = new DefaultExecutor();
PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
exec.setStreamHandler(streamHandler);
exec.execute(commandline);
return(outputStream.toString());
}
Comentarios : Leave a Comment »
Categorías : delicious
links for 2011-07-08
9 07 2011-
Use the power of regular expressions to ease text parsing and processing
-
Summary of regular-expression constructs
-
Java 4 (JDK 1.4) and later have comprehensive support for regular expressions through the standard java.util.regex package. Because Java lacked a regex package for so long, there are also many 3rd party regex packages available for Java. I will only discuss Sun's regex library that is now part of the JDK. Its quality is excellent, better than most of the 3rd party packages. Unless you need to support older versions of the JDK, the java.util.regex package is the way to go.
Java 5 and 6 use the same regular expression flavor (with a few minor fixes), and provide the same regular expression classes. They add a few advanced functions not discussed on this page.
-
Applications frequently require text processing for features like word searches, email validation, or XML document integrity. This often involves pattern matching. Languages like Perl, sed, or awk improves pattern matching with the use of regular expressions, strings of characters that define patterns used to search for matching text. To pattern match using the Java programming language required the use of the StringTokenizer class with many charAt substring methods to read through the characters or tokens to process the text. This often lead to complex or messy code.
-
[This text is taken directly from the Java API documentation]
Comentarios : Leave a Comment »
Categorías : delicious
links for 2011-06-29
30 06 2011-
If you are dealing about special characters in page parameters and/or URL, you should add the uri-encoding="ISO-8859-1" to Seam Manager properties in your components.xml, see JBSEAM-4330 (https://jira.jboss.org/jira/browse/JBSEAM-4330) :
<core:manager uri-encoding="ISO-8859-1" …>
take into account
<web:character-encoding-filter encoding="UTF-8"
override-client="true"
url-pattern="*.seam"/>if first solution doesn't work
Comentarios : Leave a Comment »
Categorías : delicious
links for 2011-06-10
11 06 2011-
md5sum.exe – 48KB 88170 Downloads since 9/29/00
Comentarios : Leave a Comment »
Categorías : delicious
links for 2011-06-08
9 06 2011-
The International Phonetic Alphabet in Unicode
-
English Pronunciation
Comentarios : Leave a Comment »
Categorías : delicious
links for 2011-05-31
1 06 2011-
package org.kodejava.example.util;
import java.util.Currency;
import java.util.Locale;public class CurrencySymbol {
public static void main(String[] args) {
Currency currency = Currency.getInstance(Locale.JAPAN);
System.out.println("Currency.getSymbol() = " + currency.getSymbol());currency = Currency.getInstance(Locale.UK);
System.out.println("Currency.getSymbol() = " + currency.getSymbol());currency = Currency.getInstance(Locale.US);
System.out.println("Currency.getSymbol() = " + currency.getSymbol());currency = Currency.getInstance(new Locale("in", "ID"));
System.out.println("Currency.getSymbol() = " + currency.getSymbol());
}
} -
The locale is set during execution and is not stored in the JRXML file.
If you run the report through iReport, it is possible to set the report locale in the Options window under the "Report execution options" section in the General tab. This will change how iReport runs your report.
If you run the report embedded in Java, you set the REPORT_LOCALE parameter, like you mention. The following code is what I use:
Locale locale = new Locale("en", "US");
metadata.put(JRParameter.REPORT_LOCALE, locale);Where metadata is the parameter map sent to fillReport(…).
Comentarios : Leave a Comment »
Categorías : delicious
links for 2011-05-30
31 05 2011-
For the purposes of this article a Seam project named example will be used. This is only important in regards to remembering the default generated naming of the persistence unit and other configuration, ect… which will default to the project name, example.
-
I found the solution to my problem, I'll put the solution here if someone has the same problem.
I was defining byte array parameter as an object and when I was adding it to the page it was by default added as a String in text field. The byte array was image which I wanted to display on the report, so first I had to convert byte array to ByteArrayInputStream on the Java side, define parameter as type InputStream, and then display it within the image, also as InputStream type.
Comentarios : Leave a Comment »
Categorías : delicious
links for 2011-05-27
28 05 2011-
public static String capitalize(String s) { if (s.length() == 0) return s; return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase(); }
-
The Recommendations for Chart and Graphic comprise guidelines for the use of charts, graphics, images, colors and text.
-
NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setMaximumCategoryLabelLines(2); -
(BarRenderer(renderer)).setItemMargin(0.0);
-
CategoryPlot plot = (CategoryPlot)chart.getPlot(); CategoryAxis xAxis = (CategoryAxis)plot.getDomainAxis(); xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
Comentarios : Leave a Comment »
Categorías : delicious
links for 2011-05-24
25 05 2011-
AutoMySQLBackup has all the features I needed: it can backup a single database, multiple databases, or all the databases on the server; each database is saved in a separate file that can be compressed (with gzip or bzip2); it will rotate the backups and not keep them filling your hard drive (as normal in the daily backup you will have only the last 7 days of backups, the weekly if enabled will have one for each week, etc.). It has also some other features (check the project homepage for full details), that I am not using myself (like email logs for example), but other peoples might find interesting.
-
MySQL is one of the most popular open source database management system for the development of interactive Websites.
If your site stores its sensitive data in a MySQL database, you will most definitely want to backup that information so that it can be restored in case of any disaster (we all have been there).
There are several ways to backup MySQL data. In this article we’ll look at how to backup your databases using different methods, we will also learn how to achieve an automatic backup solution to make the process easier. Starting with the mysqldump utility that comes with MySQL, we will review several examples using mysqldump, including the backup of your database to a file, another server, and even a compressed gzip file and send it to your email.
-
SSH is a must use tool for system administrators. However, residing access security on a human entered password is not very wise. Script kiddies may break into your system due to a lazy user with a weak password. And it is beyond the system administrator power to make users choose good passwords.
-
This short tutorial describes how to configure JBoss Application Server (Jboss GA 5.1.0) on a debian linux (Debian GNU/Linux 5.x “Lenny” ). Article starts with installation of java JDK and continues with JBoss installation and basic configuration according to standard file system hierarchy. Also init.d. scripts configuration is given here.
-
15 gotchas in seam
-
There seem to be a problem with IE8 and Seam applications. We are running Seam 2.1, JSF 1.2 and Facelets, and I cannot say for sure where the bug is. For all I know its a bug with IE8.
There seem to be problems when creating long-running conversations. In link using IE8 the cid doesnt appear. Somehow it is stripped or doesn't render correctly, and it causes some strange behaviour.
When trying to create a long running conversation by pushing an edit link for instance, we get a "Your session has timeout" exception.We fixed this IE8 problem by telling Internet Explorer to emulate IE7 in pages.xml
<page view-id="*">
<header name="X-UA-Compatible">IE=EmulateIE7</header>
</page>I suggest you do the same until the bug is identified and fixed.
Comentarios : Leave a Comment »
Categorías : delicious
links for 2011-05-20
21 05 2011-
# import java.text.DateFormat;
# import java.text.SimpleDateFormat;
# import java.util.Calendar;
# import java.util.Date;
#
# // Java 1.4+ Compatible
# //
# // The following example code demonstrates how to get
# // a Date object representing the first day of the month
# // relative to a given Date object.
#
# public class GetFirstDayOfMonth {
#
# public static void main(String[] args) {
#
# Date today = new Date();
#
# Calendar calendar = Calendar.getInstance();
# calendar.setTime(today);
#
# calendar.set(Calendar.DAY_OF_MONTH, 1);
#
# Date firstDayOfMonth = calendar.getTime();
#
# DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
# System.out.println("Today : " + sdf.format(today));
# System.out.println("First Day of Month: " + sdf.format(firstDayOfMonth));
# }
# }
Comentarios : Leave a Comment »
Categorías : delicious
links for 2011-05-13
14 05 2011-
Command line: For anonymous sites, the format is cd ftp://ftp.yoursite.com
To connect to a site with a password (non-anonymous),
cd ftp://username:password@ftp.yoursite.com
(This may return an error message if you did not specify a directory, but will connect you anyway.)
Or type in the full path: cd ftp://username:password@ftp.yoursite.com/public_htmlLeft / Right dropdown menu: will connect on that respective side. Arrow down to FTP link, or use hotkey P. A dialog box will request the FTP address in the same format:
Anonymous: ftp.yoursite.com
Non-anonymous: username:password@ftp.yoursite.com/public_html
Comentarios : Leave a Comment »
Categorías : delicious
links for 2011-05-11
12 05 2011-
Uno de los problemas a los que se enfrenta un responsable de mantenimiento que quiere mejorar los resultados del departamento a su cargo es que debe MEDIR la evolución de los aspectos más importantes que definen o determinan la calidad de su trabajo. ¿pero cuales son esos indicadores? ¿Qué parámetros determinan que el trabajo de un departamento se está haciendo bien o mal?
-
The trick to this is that if you want to add a line break within a cell, press Alt + Enter, instead of just Enter.
-
Any application that does not always need administrator privileges should not run with them by default. However, when a user wants to perform a task that requires elevation, you need to show them that this is required by displaying the Vista shield icon. When this is clicked, your application will then need to restart with administrator privileges. Interested? Then read on…
Comentarios : Leave a Comment »
Categorías : delicious
Comentarios recientes