- Copy and Paste
- extract package
- copy the contents of the "features" into the "features" folder of eclipse and copy the contents of the "plugins" into the "plugins" folder of eclipse
- Using Update Manager (existing Eclipse software site)
- click Help->Install New Software...
- select the update site of you eclipse' version from the dropdown folder
- find the feature you want from the list and install
- Using Update Manager (new software site)
- click Help->Install New Software... and click on Available Software tab
- add the download site
- select the update/download site from the dropdown
- find the feature you want from the list and install
Drools - http://download.jboss.org/drools/release/5.5.0.Final/org.drools.updatesite/
Some update sites are dependent on the version of eclipse.
Ex. http://www.jboss.org/tools/download.html
- Using Extension - to separate your plugins from other users
- create an extension folder with eclipse folder, e.g. C:\extension\eclipse
- copy the features and plugins folder of the plugin inside the eclipse folder (for additional plugins, do the Copy and Paste method above)
- open Update Manager and Add Site
- in Add Site window, click Local and specify the location of the extension folder, e.g. C:\extension
- browse and check the plugin you want to install in the Available Software list and click Install
- Using Link
Monday, December 6, 2010
Installing Eclipse Plugins
Sunday, December 5, 2010
Tuesday, November 30, 2010
Using FileZilla
- Open FileZilla
- Click File->Site Manager
- Enter host, leave the port blank
Server type: SFTP
Username: SID
Password: orangewins - Click Connect
Wednesday, November 3, 2010
Adding new SVN repository / Check out
SVN must already be installed in your Eclipse before this.
- Open 'SVN Repository Exploring' Perspective. On the 'SVN Repositories' View, click on 'New Repository Location' button.
- Enter URL, username and password, and finish.
- Select the project and right click. Click on 'Find/Check Out As...'
- Choose 'Check out as a project configured using the New Project Wizard' to ensure that the project is check out as an eclipse project (allow setting of build paths)
- Proceed and complete the check out.
Getting started with Eclipse Subversive
Getting started:
http://www.eclipse.org/subversive/documentation/gettingStarted.php
Installation:
http://www.eclipse.org/subversive/documentation/gettingStarted/aboutSubversive/install.php
Sample Installation: (Eclipse Helios)
Install Subversive Plugin using Eclipse update site
1) Help -> Install New Software...
2) In the "Work with" dropdown, select the update site of your eclipse version, e.g Kepler. The available software sites will be listed/displayed.
3) In the list, select Collaboration -> Subversive features then install. At the least, you only need the Subversive SVN Team Provider.
Install Subversive Plugin using SVN update site
1) Help -> Install New Software...
2) In the "Work with" dropdown, select the update site of SVN. If it is not available click "Available Software Sites". On the window that opens, select subversion update locaion. If location is not found, add it. SVN will now appear on the "Work with" dropdown. Select it.
Sample
Name: Subversive
Location: http://download.eclipse.org/technology/subversive/0.7/update-site/
3) In the list, select Subversive features then install.
Install Subversive SVN Connectors
1) Restart Eclipse
2) After restart you'll see connectors discovery dialog.
3) Install Subversive Connectors without registering connectors update site manually.
http://community.polarion.com/projects/subversive/download/eclipse/2.0/helios-site/ -
Update:
If the SVN Connectors are not downloaded,
1. make sure you are using a fresh workspace to launch Subversive Connector Discovery upon restart
2. get the latest release from:
http://www.polarion.com/products/svn/subversive/download.php?utm_source=eclipse.org&utm_medium=link&utm_campaign=subversive
Latest Release – Recommended
Help (free book):
http://svnbook.red-bean.com/
Sources:
http://www.eclipse.org/subversive
http://www.eclipse.org/subversive/documentation/gettingStarted.php
Installation:
http://www.eclipse.org/subversive/documentation/gettingStarted/aboutSubversive/install.php
Sample Installation: (Eclipse Helios)
Install Subversive Plugin using Eclipse update site
1) Help -> Install New Software...
2) In the "Work with" dropdown, select the update site of your eclipse version, e.g Kepler. The available software sites will be listed/displayed.
3) In the list, select Collaboration -> Subversive features then install. At the least, you only need the Subversive SVN Team Provider.
Install Subversive Plugin using SVN update site
1) Help -> Install New Software...
2) In the "Work with" dropdown, select the update site of SVN. If it is not available click "Available Software Sites". On the window that opens, select subversion update locaion. If location is not found, add it. SVN will now appear on the "Work with" dropdown. Select it.
Sample
Name: Subversive
Location: http://download.eclipse.org/technology/subversive/0.7/update-site/
3) In the list, select Subversive features then install.
Install Subversive SVN Connectors
1) Restart Eclipse
2) After restart you'll see connectors discovery dialog.
3) Install Subversive Connectors without registering connectors update site manually.
http://community.polarion.com/projects/subversive/download/eclipse/2.0/helios-site/ -
Update:
If the SVN Connectors are not downloaded,
1. make sure you are using a fresh workspace to launch Subversive Connector Discovery upon restart
2. get the latest release from:
http://www.polarion.com/products/svn/subversive/download.php?utm_source=eclipse.org&utm_medium=link&utm_campaign=subversive
Latest Release – Recommended
- http://download.eclipse.org/technology/subversive/0.7/update-site/ - [required] Subversive plug-in
- http://community.polarion.com/projects/subversive/download/eclipse/2.0/update-site/ - [required] Subversive SVN Connectors
- http://community.polarion.com/projects/subversive/download/integrations/update-site/ - [optional] Subversive Integrations
http://svnbook.red-bean.com/
Sources:
http://www.eclipse.org/subversive
What is Subversion
Subversion® is an open-source version control system. Subversion® allows developers to share there projects on the repositories, where they are stored afterwards. Repository is much similar to a file server, except the fact, that it not only stores the copy of the file system, but its previous states and changing history. Subversion® access its repositories using network, so it provides a probability for a person to work over some shared files and watch for every possible changes made by other developers.
Subversion® home:
http://subversion.apache.org/
http://subversion.tigris.org/ - old home
Trunk, Branches and Tags
Trunk is a main (head) line of development. That's where you share your project and do initial commit. Branches are the additional lines of development. Used when branching for different versions from one initial is needed or when each developer has his own development line and plan. Tags are a kind of specific labels for a set of files each with its own revision number. Used to track the important events if project's life cycle.
Apache Subversion - provides an API for Subversion developers and package maintainers to build Subversion from source code
Binary packages - packages from volunteers built on top of Apache Subversion
- some of the available packages are here: http://subversion.apache.org/packages.html
- Example: Slik SVN
SVNKit
SVNKit is a pure Java toolkit - it implements all Subversion features and provides APIs to work with Subversion working copies, access and manipulate Subversion repositories - everything within your Java application.
Sources:
http://subversion.apache.org/
http://subversion.tigris.org/
http://www.eclipse.org/subversive
http://svnkit.com/index.html
Subversion® home:
http://subversion.apache.org/
http://subversion.tigris.org/ - old home
Trunk, Branches and Tags
Trunk is a main (head) line of development. That's where you share your project and do initial commit. Branches are the additional lines of development. Used when branching for different versions from one initial is needed or when each developer has his own development line and plan. Tags are a kind of specific labels for a set of files each with its own revision number. Used to track the important events if project's life cycle.
Apache Subversion - provides an API for Subversion developers and package maintainers to build Subversion from source code
Binary packages - packages from volunteers built on top of Apache Subversion
- some of the available packages are here: http://subversion.apache.org/packages.html
- Example: Slik SVN
SVNKit
SVNKit is a pure Java toolkit - it implements all Subversion features and provides APIs to work with Subversion working copies, access and manipulate Subversion repositories - everything within your Java application.
Sources:
http://subversion.apache.org/
http://subversion.tigris.org/
http://www.eclipse.org/subversive
http://svnkit.com/index.html
Wednesday, October 20, 2010
Web Server, Web Container & Application Server
A Web Server is a server capable of receiving HTTP requests, interpreting them, processing the corresponding HTTP Responses and sending them to the appropriate clients (Web Browsers).
Example: Apache Web Server
A Web Container, also called Servlet container or Servlet engine, is a J2EE compliant implementation which provides an environment for the Servlets and JSPs to run. Putting it differently we can say that a Web Container is combination of a Servlet Engine and a JSP Engine. If an HTTP Request refers to a Web Component (typically a Servlet or a JSP) then the request is forwarded to the Web Container and the result of the request is sent back to Web Server, which uses that result to prepare the HTTP Response for the particular HTTP Request.
Example: Tomcat is a typical Web Container. A typical setup would be to have Apache HTTP Server as the Web Server and Tomcat as the Web Container.
Illustration: Servlet Container = Web Server + Servlets/JSPs (dynamic response generation)
An Application Server is a complete server, which provides an environment for running the business components (EJBs, ADF BCs, etc.) in addition to providing the capabilities of a Web Container as well as of a Web Server.
Example: Bea WebLogic, IBM WebSphere, Oracle Application Server, etc.
Illustration: Application Server = Web Server + Servlets/JSPs + Business component (EJB)
Source:
- copied from http://geekexplains.blogspot.com/2008/06/web-server-web-container-application.html
- http://www.ecomputercoach.com/index.php/component/content/article/68-servers/72-web-server-vs-servlet-container-vs-application-server.html
Example: Apache Web Server
A Web Container, also called Servlet container or Servlet engine, is a J2EE compliant implementation which provides an environment for the Servlets and JSPs to run. Putting it differently we can say that a Web Container is combination of a Servlet Engine and a JSP Engine. If an HTTP Request refers to a Web Component (typically a Servlet or a JSP) then the request is forwarded to the Web Container and the result of the request is sent back to Web Server, which uses that result to prepare the HTTP Response for the particular HTTP Request.
Example: Tomcat is a typical Web Container. A typical setup would be to have Apache HTTP Server as the Web Server and Tomcat as the Web Container.
Illustration: Servlet Container = Web Server + Servlets/JSPs (dynamic response generation)
An Application Server is a complete server, which provides an environment for running the business components (EJBs, ADF BCs, etc.) in addition to providing the capabilities of a Web Container as well as of a Web Server.
Example: Bea WebLogic, IBM WebSphere, Oracle Application Server, etc.
Illustration: Application Server = Web Server + Servlets/JSPs + Business component (EJB)
Source:
- copied from http://geekexplains.blogspot.com/2008/06/web-server-web-container-application.html
- http://www.ecomputercoach.com/index.php/component/content/article/68-servers/72-web-server-vs-servlet-container-vs-application-server.html
Sunday, September 12, 2010
JSP / JSTL / EL
JSP
JavaServer Pages (JSP) - is the standard presentation-layer technology for the J2EE platform.
JSP scripting elements:
JSTL
JSP Standard Tag Library (JSTL) - is a collection of standard custom tag libraries that implement basic functionality common to a wide range of server-side Java applications.
EL
Expression Language (EL) - is a simplified form for JSP expression
- syntax: ${elExpression}
Source:
http://www.ibm.com/developerworks/java/library/j-jstl0211.html
http://download.oracle.com/docs/cd/E17802_01/j2ee/j2ee/1.4/docs/tutorial-update2/doc/index.html
JavaServer Pages (JSP) - is the standard presentation-layer technology for the J2EE platform.
JSP scripting elements:
- expressions
- form: <%= javaExpression %>
- ex: date = <%= new java.util.Date() %>
- xml syntax: <jsp:expression>javaExpression</jsp:expression> - scriptlets
- form: <% code %>
- xml syntax: <jsp:scriplet>code</jsp:scriplet> - declarations
- form: <!% code %>
- xml syntax: <jsp:declaration>code</jsp:declaration>
- JSP Comment - <%-- JSP Comment --%>
- HTML Comment - <!-- HTML Comment -->
JSTL
JSP Standard Tag Library (JSTL) - is a collection of standard custom tag libraries that implement basic functionality common to a wide range of server-side Java applications.
EL
Expression Language (EL) - is a simplified form for JSP expression
- syntax: ${elExpression}
Source:
http://www.ibm.com/developerworks/java/library/j-jstl0211.html
http://download.oracle.com/docs/cd/E17802_01/j2ee/j2ee/1.4/docs/tutorial-update2/doc/index.html
Thursday, September 9, 2010
Line Wrap for excel cells
DO:
In report manager,
exporter.setParameter(JExcelApiExporterParameter.IS_COLLAPSE_ROW_SPAN, Boolean.TRUE);
In xml,
textField isStretchWithOverflow="true" // on long data input cells
reportElement stretchType="RelativeToTallestObject"
API: http://jasperreports.sourceforge.net/api/net/sf/jasperreports/engine/export/JRXlsAbstractExporterParameter.html
In report manager,
exporter.setParameter(JExcelApiExporterParameter.IS_COLLAPSE_ROW_SPAN, Boolean.TRUE);
In xml,
textField isStretchWithOverflow="true" // on long data input cells
reportElement stretchType="RelativeToTallestObject"
API: http://jasperreports.sourceforge.net/api/net/sf/jasperreports/engine/export/JRXlsAbstractExporterParameter.html
Wednesday, June 9, 2010
Initialization of list/map in one line
List
ArrayList places = new ArrayList(Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
ArrayList list = new ArrayList() {{
add("A");
add("B");
add("C");
}}
link
Map
Map m = new HashMap() {
{
put(".jpg", "image/jpeg");
put(".jpeg", "image/jpeg");
}
};
ArrayList
ArrayList
add("A");
add("B");
add("C");
}}
link
Map
Map
{
put(".jpg", "image/jpeg");
put(".jpeg", "image/jpeg");
}
};
Sunday, April 11, 2010
Java Concurrency/Threads
Process vs Thread
Process - is a running program that runs independently from other processes. It has its own address space and cannot directly access resources of other processes. Each process can have one or more threads.
Thread - is sometimes called lightweight process. Both processes and threads provide an execution environment, but creating a new thread requires fewer resources than creating a new process. Threads share the process's resources, including memory and open files.
2 ways to define a Thread:
Thread methods:
Source: http://java.sun.com/docs/books/tutorial/essential/index.html
http://www.vogella.de/articles/JavaConcurrency/article.html
Process - is a running program that runs independently from other processes. It has its own address space and cannot directly access resources of other processes. Each process can have one or more threads.
Thread - is sometimes called lightweight process. Both processes and threads provide an execution environment, but creating a new thread requires fewer resources than creating a new process. Threads share the process's resources, including memory and open files.
2 ways to define a Thread:
- implement Runnable interface
- more general, can have many superclass
- starting: (new Thread(new HelloRunnable())).start(); - extend Thread class (Thread class itself implements Runnable)
- simpler but limited
- starting: (new HelloThread()).start();
Thread methods:
- public void run() - the only method coming from Runnable
- public void start() - calls the run() method, can only be called once
- public static void sleep(long millis)/(long millis, int nanos) throws InterruptedException - suspend execution for a specified period
- time is not guaranteed
- can be interrupted - public void interrupt() - indicates that thread should stop
- public static boolean interrupted() - interrupted status is cleared
- public boolean isInterrupted() - has no effect on interrupted status
- public final void stop()/suspend()/resume() - deprecated
Object | Thread |
---|---|
notify notifyAll wait | sleep yield |
Source: http://java.sun.com/docs/books/tutorial/essential/index.html
http://www.vogella.de/articles/JavaConcurrency/article.html
Thursday, April 1, 2010
Using Resource Bundle
ResourceBundle is a class used for containing locale-specific data. A Locale defines the user's environment particularly its language and region. A certain number in one locale may be written differently in another. Likewise, a label of a "Cancel" button may differ in different locales. Using ResourceBundle will allow you to handle these different locales without having to hard-code the locale-specific data.
Sample of retrieving locale-specific data
list of resource bundles:
ButtonLabel
ButtonLabel_de
ButtonLabel_en_GB
ButtonLabel_fr_CA_UNIX
selecting the locale-specific ButtonLabel resource bundle:
Locale currentLocale = new Locale("fr", "CA", "UNIX");
ResourceBundle introLabels =
ResourceBundle.getBundle("ButtonLabel", currentLocale);
2 Types of ResourceBundle
Notes:
- things to check/consider when internationalizing: http://java.sun.com/docs/books/tutorial/i18n/intro/checklist.html
- numbers, dates, times, or currencies need not be isolated in a ResourceBundle because only the display format of these objects varies with Locale, the objects themselves do not
- it is better to have multiple ResourceBundle by determining related objects and grouping them together
- ResourceBundle.Control class provides a way to control the instantiation and location of resource bundles. You can override its methods to behave differently.
- list of language codes (ISO-639): http://ftp.ics.uci.edu/pub/ietf/http/related/iso639.txt
- list of country codes (ISO-3166): http://userpage.chemie.fu-berlin.de/diverse/doc/ISO_3166.html
Source: http://java.sun.com/docs/books/tutorial/i18n/resbundle/index.html
Sample of retrieving locale-specific data
list of resource bundles:
ButtonLabel
ButtonLabel_de
ButtonLabel_en_GB
ButtonLabel_fr_CA_UNIX
selecting the locale-specific ButtonLabel resource bundle:
Locale currentLocale = new Locale("fr", "CA", "UNIX");
ResourceBundle introLabels =
ResourceBundle.getBundle("ButtonLabel", currentLocale);
2 Types of ResourceBundle
- PropertyResourceBundle - uses a properties file to contain the key-value pairs. The value can only be a String.
properties files for 3 resource bundles:
LabelsBundle.properties
LabelsBundle_de.properties
LabelsBundle_fr.properties
resource bundle sample content:
# This is the LabelsBundle_de.properties file
s1 = Computer
s2 = Platte
s3 = Monitor
s4 = Tastatur
use of resource bundle sample:
Locale[] supportedLocales = {
Locale.FRENCH,
Locale.GERMAN,
Locale.ENGLISH
};
for (int i = 0; i < supportedLocales.length; i ++) {
ResourceBundle labels =
ResourceBundle.getBundle("LabelsBundle",currentLocale);
String value = labels.getString(key);
Enumeration bundleKeys = labels.getKeys();
while (bundleKeys.hasMoreElements()) {
String key = (String)bundleKeys.nextElement();
String value = labels.getString(key);
}
} - ListResourceBundle - uses a list to contain the key-value pairs. The value can be any object.
3 resource bundles:
StatsBundle_en_CA.class
StatsBundle_fr_FR.class
StatsBundle_ja_JP.class
resource bundle sample:
import java.util.*;
public class StatsBundle_ja_JP extends ListResourceBundle {
public Object[][] getContents() {
return contents;
}
private Object[][] contents = {
{ "GDP", new Integer(21300) },
{ "Population", new Integer(125449703) },
{ "Literacy", new Double(0.99) },
};
}
use of resource bundle sample:
Locale[] supportedLocales = {
new Locale("en","CA"),
new Locale("ja","JP"),
new Locale("fr","FR")
};
for (int i = 0; i < supportedLocales.length; i ++) {
ResourceBundle stats =
ResourceBundle.getBundle("StatsBundle",currentLocale);
Integer gdp = (Integer)stats.getObject("GDP");
}
Notes:
- things to check/consider when internationalizing: http://java.sun.com/docs/books/tutorial/i18n/intro/checklist.html
- numbers, dates, times, or currencies need not be isolated in a ResourceBundle because only the display format of these objects varies with Locale, the objects themselves do not
- it is better to have multiple ResourceBundle by determining related objects and grouping them together
- ResourceBundle.Control class provides a way to control the instantiation and location of resource bundles. You can override its methods to behave differently.
- list of language codes (ISO-639): http://ftp.ics.uci.edu/pub/ietf/http/related/iso639.txt
- list of country codes (ISO-3166): http://userpage.chemie.fu-berlin.de/diverse/doc/ISO_3166.html
Source: http://java.sun.com/docs/books/tutorial/i18n/resbundle/index.html
Tuesday, March 23, 2010
Java Exceptions
Exception Objects
Kinds of Exceptions
Notes
- finally is always executed even if there is a change of control flow like when there is a return statement in try
- can you catch runtime exception? yes, you can catch any Throwable type but since the cost of checking for runtime exceptions exceeds the benefit of catching or specifying them, the compiler does not require that you catch them
- for readable code, it's good practice to append the string Exception to the names of all classes that inherit (directly or indirectly) from the Exception class
- what to use when creating your own exception: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.
Ref: http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html
Throwable
'-> Error
'-> AnnotationFormatError
'-> AssertionError
'-> IOError
'-> ThreadDeath
'-> ...
'-> Exception
'-> RuntimeException
'-> ArithmeticException
'-> ArrayStoreException
'-> ClassCastException
'-> ConcurrentModificationException
'-> IndexOutOfBoundsException
'-> NullPointerException
'-> ...
'-> ClassNotFoundException
'-> CloneNotSupportedException
'-> InterruptedException
'-> IOException
'-> NoSuchMethodException
'-> ...
Kinds of Exceptions
- checked - all exceptions that are not RuntimeException
- unchecked
- Error
- RuntimeException
Notes
- finally is always executed even if there is a change of control flow like when there is a return statement in try
- can you catch runtime exception? yes, you can catch any Throwable type but since the cost of checking for runtime exceptions exceeds the benefit of catching or specifying them, the compiler does not require that you catch them
- for readable code, it's good practice to append the string Exception to the names of all classes that inherit (directly or indirectly) from the Exception class
- what to use when creating your own exception: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.
Ref: http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html
Synchronized & Unsynchronized Objects
Synchronized | Unsynchronized |
---|---|
StringBuffer | StringBuilder |
Vector | ArrayList |
Hashtable | HashMap |
Monday, March 22, 2010
Setting the CLASSPATH Sys Var
To display the current
From: http://java.sun.com/docs/books/tutorial/java/package/managingfiles.html
CLASSPATH
variable, use these commands in Windows and Unix (Bourne shell): To delete the current contents of theIn Windows: C:\> set CLASSPATH
In Unix: % echo $CLASSPATH
CLASSPATH
variable, use these commands: To set theIn Windows: C:\> set CLASSPATH=
In Unix: % unset CLASSPATH; export CLASSPATH
CLASSPATH
variable, use these commands (for example): In Windows: C:\> set CLASSPATH=C:\users\george\java\classes
In Unix: % CLASSPATH=/home/george/java/classes; export CLASSPATH
From: http://java.sun.com/docs/books/tutorial/java/package/managingfiles.html
Tuesday, March 16, 2010
Declaring Constants
I was contemplating for the best way to declare constants in Java and found that there are several ways to do it. The best article I saw regading this topic is here. It helped me decide clearly as to what I should use plus, one of the comments discussed a very interesting information about inlining constants w/c I will also explain later on this blog.
First, I would like to eradicate suggestions/questions that might come up:
Why not use enums? I am referring here to constants that are not related and may even be of different types so enum is not a good choice.
If these constants are not related, why bother grouping them? This is sometimes necessary because there are constants that belong to the same functionality but are not related to each other. You may also want to group constants shared by different classes, more like global constants. These constants do not belong naturally to a certain class so it needs to be grouped somewhere else.
Why not put constants in the class that they are most related to? Aside from the explanation above, this would also lead to dependencies between classes and the constants will clutter. It's always easier to update just one class or few classes.
So what are the options now?
Interface for Constants
ADV:
- cleaner/shorter code because you can define constants without the public static final keywords since they are implicitly public static final
- a class implementing this can refer to the constants without a qualifying class name
DISADV:
- this is not what interface is designed for. Interface is supposed to specify a contract for its services, not to handle data.
- using constant without a qualifying class name can make code more difficult to understand and maintain
- interfaces promotes constants to the API of the class which means that if MyClass implements MyConstantInterface, you can use MyClass.SAMPLE_CONSTANT instead of MyConstantInterface.SAMPLE_CONSTANT. This breaks inheritance and your Javadoc will be full of repeating constants.
Class for Constants with private constructor
ADV:
- cannot be instantiated and cannot be subclassed like interfaces
- the use of qualifying name can add to the readability of the code
DISADV:
- long name, constants are referred using static references like MyConstantClass.SAMPLE_CONSTANT
static import
ADV:
- allow referring to constants without a qualifying class name
DISADV:
- can make code more difficult to understand and maintain
MY CONCLUSION:
You may choose one over another depending on what you need or what is more convenient for you, but for me the best approach is to use class with private constructor. This will avoid all the disadvantages of using an interface. If you still want to use interfaces because of the shorter name reference for constants, you must use static import of a constant class instead. However, this must be taken with precaution. Use it only if you need frequent access of constants from one or very few classes only. Otherwise, readers of your code may get confused as to where a constant comes from.
Now, is there anything else that can do better? Apparently, according to Kevin Riff, there is. When a field is (1)of type primitive or String, (2)declared final, and (3)was initialized upon declaration, it is called "compile-time constant" and it is in-lined in the consumer classes. This means that all reference of this constant is replaced with its actual value at compile time. So if you change the value of a constant, you must recompile not only the containing class but all its consumer classes in order to update the value of the constant.
What is the solution for this? Using a properties file could be considered but if you really need to hard-code your constants in a Java file, you must prevent your constants to be in-line like this,
The code would seem odd so don't forget to add comments explaining what's going on.
Personally, I might not apply this design because it makes the code look odd and somehow ugly. I would rather recompile all affected classes. It happens to almost any class anyway that when you make a change on it, there will be some affected classes that must be recompiled too.
First, I would like to eradicate suggestions/questions that might come up:
Why not use enums? I am referring here to constants that are not related and may even be of different types so enum is not a good choice.
If these constants are not related, why bother grouping them? This is sometimes necessary because there are constants that belong to the same functionality but are not related to each other. You may also want to group constants shared by different classes, more like global constants. These constants do not belong naturally to a certain class so it needs to be grouped somewhere else.
Why not put constants in the class that they are most related to? Aside from the explanation above, this would also lead to dependencies between classes and the constants will clutter. It's always easier to update just one class or few classes.
So what are the options now?
Interface for Constants
ADV:
- cleaner/shorter code because you can define constants without the public static final keywords since they are implicitly public static final
- a class implementing this can refer to the constants without a qualifying class name
DISADV:
- this is not what interface is designed for. Interface is supposed to specify a contract for its services, not to handle data.
- using constant without a qualifying class name can make code more difficult to understand and maintain
- interfaces promotes constants to the API of the class which means that if MyClass implements MyConstantInterface, you can use MyClass.SAMPLE_CONSTANT instead of MyConstantInterface.SAMPLE_CONSTANT. This breaks inheritance and your Javadoc will be full of repeating constants.
Class for Constants with private constructor
ADV:
- cannot be instantiated and cannot be subclassed like interfaces
- the use of qualifying name can add to the readability of the code
DISADV:
- long name, constants are referred using static references like MyConstantClass.SAMPLE_CONSTANT
static import
ADV:
- allow referring to constants without a qualifying class name
DISADV:
- can make code more difficult to understand and maintain
MY CONCLUSION:
You may choose one over another depending on what you need or what is more convenient for you, but for me the best approach is to use class with private constructor. This will avoid all the disadvantages of using an interface. If you still want to use interfaces because of the shorter name reference for constants, you must use static import of a constant class instead. However, this must be taken with precaution. Use it only if you need frequent access of constants from one or very few classes only. Otherwise, readers of your code may get confused as to where a constant comes from.
Now, is there anything else that can do better? Apparently, according to Kevin Riff, there is. When a field is (1)of type primitive or String, (2)declared final, and (3)was initialized upon declaration, it is called "compile-time constant" and it is in-lined in the consumer classes. This means that all reference of this constant is replaced with its actual value at compile time. So if you change the value of a constant, you must recompile not only the containing class but all its consumer classes in order to update the value of the constant.
What is the solution for this? Using a properties file could be considered but if you really need to hard-code your constants in a Java file, you must prevent your constants to be in-line like this,
public class MyLibrary {
public static final String VERSION; // blank final
static {
VERSION = "1.0"; // initialized separately
}
}
The code would seem odd so don't forget to add comments explaining what's going on.
Personally, I might not apply this design because it makes the code look odd and somehow ugly. I would rather recompile all affected classes. It happens to almost any class anyway that when you make a change on it, there will be some affected classes that must be recompiled too.
Monday, March 15, 2010
Java Generics
- introduced in J2SE 5.0
- adds robustness/stability on code by making more bugs detectable at compile time
- normal way can cause runtime ClassCastException
public class Box { private Object object; public void add(Object object) { this.object = object; } public Object get() { return object; } } Box integerBox = new Box(); integerBox.add("10"); // note how the type is now String Integer someInteger = (Integer)integerBox.get();
- sample generic version with type variable T
public class Box
{ private T t; // T stands for "Type" public void add(T t) { this.t = t; } public T get() { return t; } } Box integerBox = new Box (); integerBox.add(new Integer(10)); Integer someInteger = integerBox.get(); // no cast! - generic method/constructor
public static <U> void fillBoxes(U u, List<Box<U>> boxes) { for (Box<U> box : boxes) { box.add(u); } } Crayon red = ...; List<Box<Crayon>> crayonBoxes = ...; // normal way Box.<Crayon>fillBoxes(red, crayonBoxes); // with type inference Box.fillBoxes(red, crayonBoxes); // compiler infers that U is Crayon
- Bounded Parameter types -> when variables are restricted to certain types, upper bound only
<U extends Number & MyInterface> // uses extend for both classes & interfaces
- Unknown type/wilcard bounds -> represented by wildcard character "?"
3 different flavors of wildcards:- " ? " - the unbounded wildcard. It stands for the family of all types.
- " ? extends Type " - a wildcard with an upper bound. It stands for the family of all types that are subtypes of Type , type Type being included.
- " ? super Type " - a wildcard with a lower bound. It stands for the family of all types that are supertypes of Type , type Type being included.
// Box<Integer> and Box<Double> are not subtypes of Box<Number> Box<Number> box = new Box<Integer>(); // compile-time error // Box<Integer> and Box<Double> are subtypes of Box<? extends Number> Box<? extends Number> box = new Box<Integer>(); // ok Integer i = new Integer(1); Number n = i; // compile-time error // Integer is not '? extends Number' // we are not sure that the instance type of Box is Integer, so we cannot add i box.add(i); // compile-time error // Number is not '? extends Number' // we are sure that the type of Box extends a Number but we are not sure of the // instance type of n, so we cannot add n // what if runtime type of Box is Box<Double> but n is Integer box.add(n) // compile-time error // we are not sure that the type of Box is an Integer Integer i2 = box.get(); // we are sure that the type of Box is always extends a Number Number n2 = box.get(); // ok // sample using upperbound & lowerbound wildcards public class Collections { public static <T> void copy ( List<? super T> dest, List<? extends T> src) { // bounded wildcard parameterized types for (int i=0; i<src.size(); i++) dest.set(i,src.get(i)); } }
- Type Erasure -> when generic types are instantiated, all generic information are removed leaving only the raw type. Box
becomes Box only. public class MyClass
{ public static void myMethod(Object item) { if (item instanceof E) { //Compiler error ... } E item2 = new E(); //Compiler error E[] iArray = new E[10]; //Compiler error E obj = (E)new Object(); //Unchecked cast warning } }
Sources:
http://java.sun.com/docs/books/tutorial/java/generics/index.html
http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html
To Study:
-SSL, certificates, keystore, keytool
-html
-jsp
-jsp el(expression lang)
-extjs
-dwr
-tld (tags)
-j2ee
-java
-servlets
-struts
-spring
-drools
-jdbc
-ibatis
-db2
-sql
-ibml
-properties file (adv. of constants in java file)
-logging, log4j
-servers, tomcat
-deployment (war, jar, ear)
-eclipse
-cvs/clearcase/svn
-maven
TODO:
-check ResourceBundle if there's a properties file
-html
-jsp
-jsp el(expression lang)
-extjs
-dwr
-tld (tags)
-j2ee
-java
-servlets
-struts
-spring
-drools
-jdbc
-ibatis
-db2
-sql
-ibml
-properties file (adv. of constants in java file)
-logging, log4j
-servers, tomcat
-deployment (war, jar, ear)
-eclipse
-cvs/clearcase/svn
-maven
TODO:
-check ResourceBundle if there's a properties file
Saturday, March 6, 2010
Java Inheritance
- Variables
Kinds of variables base on scope: local, instance, class
Hiding/Shadowing Variables
- redeclaring a variable that’s already been declared somewhere else. The closest scope is used when you refer it through simple name.
1) local var hides instance var
- use this to access the instance var
2) instance var hides inherited var
- use super.name or cast the object to its super class, with the syntax ((Superclass)object).name
- when the variable is accessed thru the object containing it, the variable used depends on the type the object it was declared with or casted to, not the runtime type of the object. - Methods
Overloading
- same name, diff arguments, return type doesn't matter
Overriding
- same signature (method name + arguments), same return type diff classes
- instance to instance method only
Hiding
- static to static only
- when the method is called thru the object containing it, the method used depends on the type the object it was declared with or casted to, not the runtime type of the object.
Not allowed in methods but allowed in variables/fields:
- static to non-static or vice versa
- narrowing visibility
- different return type (but same signature/name) -> compile error in methods - Object
- implicit superclass of all classes
- must be overridden in objects -> equals(), hashCode(), toString()
clone() method
-protected|public Object clone() throws CloneNotSupportedException
aCloneableObject.clone();
- aCloneableObject must implemenet Cloneable interface
- default behavior of Object's clone() -> creates an object of the same class as the original object and initializes the new object's member variables. But if a member variable is an external object, say ObjExternal, ObjExternal is not cloned but shared. A change in ObjExternal made by one object will be visible in its clone also.
equals() method
- uses ==
- if overridden, u must override hashCode() too. If two objects are equal, their hash code must also be equal.public boolean equals(Object obj) { if (obj instanceof Book) return ISBN.equals((Book)obj.getISBN()); else return false; }
- Abstract vs Interface
- http://mindprod.com/jgloss/interfacevsabstract.html
- when to use one over the other:
General rule is if you are creating something that provides common functionality to unrelated classes, use an interface. If you are creating something for objects that are closely related in a hierarchy, use an abstract class.
Friday, March 5, 2010
Sample CVS config spec
-main
-branch
element * CHECKEDOUT element * /main/LATEST load \Acctsvcs
-branch
element * CHECKEDOUT element * /main/nae_phase1c/LATEST element * /main/NAE_ROOT_PHASE1C -mkbranch nae_phase1c element * /main/LATEST -mkbranch nae_phase1c load \Acctsvcs
Eclipse Pointers / Links
- {object} cannot be resolved in Eclipse
http://blog.sherifmansour.com/?p=207
- installing plugins in Eclipse
http://www.venukb.com/2006/08/20/install-eclipse-plugins-the-easy-way
- SVN Working Copy xxx locked and cleanup failed - Right click on the project then Team -> Cleanup
- setting for debug
SET JAVA_OPTS= -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8000
or
set MEM_ARGS=-Xms32m -Xmx200m
set JAVA_OPTIONS=-Xverify:none -Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=7919
- display tool/icon for showing method only or all source
Window > Customize Perspective.... > Tool Bar Visibility > Editor Presentation > Show Source of Selected Element Only
http://blog.sherifmansour.com/?p=207
- installing plugins in Eclipse
http://www.venukb.com/2006/08/20/install-eclipse-plugins-the-easy-way
- SVN Working Copy xxx locked and cleanup failed - Right click on the project then Team -> Cleanup
- setting for debug
SET JAVA_OPTS= -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8000
or
set MEM_ARGS=-Xms32m -Xmx200m
set JAVA_OPTIONS=-Xverify:none -Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=7919
- display tool/icon for showing method only or all source
Window > Customize Perspective.... > Tool Bar Visibility > Editor Presentation > Show Source of Selected Element Only
Monday, March 1, 2010
Monday, February 22, 2010
Weblogic 9 setup
- Create domain directory
- Go to {weblogic.dir}\weblogic92\common\bin and run config.cmd
- Select Create a new Weblogic domain
- Select the source (automatic or with template)
- Input admin username and password
- Choose startup mode and JDK. Use JRocket for JDK.
- Enter domain name & location and click Create Check Start Admin Server and click Done
- Change port number
- Go to http://{hostname/localhost}:7001/console and login
- Navigate to {domain name}->Environment-Servers. Select AdminServer(admin)
- Change the Listen Port and save changes.,/li>
- Activate changes
- Add the db2jcc jars for the DB2 driver classes
- Go to your DB2 installation or <sqllib_home>\java directory
- Copy the following jars to your <weblogic_domain>\lib directory:
- db2jcc.jar
- db2jcc_license_cu.jar
- db2jcc_license_cisuz.jar
- Restart server
- Add JDBC Data Source
- Navigate to {domain name}->Services->JDBC->Data Sources. Add new data source.
- Set Data Source properties and click Next
Name: db2Pool JNDI Name: db2Pool Database Type: DB2 Database Driver: IBM's DB2 Driver(Type 2)
- Select transaction options (use defaults)
- Set connection properties and click Next
Database Name: db2test Host Name: Port: Database User Name: coreusrt Password:
- Test Database Connection. Update the following:
Driver Class Name: com.ibm.db2.jcc.DB2Driver URL: jdbc:db2://db2t.vigslbp.bear.com:5510/DB2TEST
click Test Configuration and Next - Select the server and click Finish
- Activate changes
- Deploy Web App
Note: Make sure that the WEB-INF/lib of the webapp contains all needed lib (ex. by copy.runtime.lib)- Navigate to {domain name}->Deployments. Click Install
- Select the path of your application root directory (webapp directory). Click Next
- Select Install this deployment as an application and click Next
- Set settings (use default) and click Next
- Review choices and click Finish
- Activate changes
- Navigate back to {domain name}->Deployments. Select webapp and click Start servicing all requests. Start deployment
- Finish! You may now go to your webapp.
Sample: http://pbctx60.bsna.bsroot.bear.com:7831/acctsvcs-nae/nae/acctvwup?action=showPage
Tuesday, February 16, 2010
Java Annotations
- provides data about a program but do not directly affect the program semantics
- defined similar to interface
@interface Author {
String author();
String date();
String[] reviewers(); // Note use of array
} - sample use:
@Author(
name = "Benjamin Franklin",
date = "3/27/2003",
reviewers = {"Alice", "Bob", "Cindy"} // Note array notation
)
class MyClass() { }
3 Predefined Annotation Types:
1) @Deprecated - should also be documented using the Javadoc @deprecated tag
/**
* @deprecated
* explanation of why it was deprecated
*/
@Deprecated
2) @Override
3) @SuppressWarnings
@SuppressWarnings("deprecation") //deprecation warning - suppressed
@SuppressWarnings({"unchecked", "deprecation"}) // legacy code & deprecation warning - suppressed
Detailed explanation here: http://java.sun.com/j2se/1.5.0/docs/guide/language/annotations.html
Subscribe to:
Posts (Atom)