Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Wednesday, March 19, 2008

java: An algorithm for converting an array to comma delimited/separated string/value (e.g. csv)

StringBuilder sb = new StringBuilder();

Long[] array = {new Long("1"), new Long("2"), new Long("3")};

for (int i = 0; i < array.length(); i++)
{
   if (i > 0) 
   {
       sb.append(", ");
   }

   sb.append(array[i]);
}

System.out.println(sb.toString());

//output: 1, 2, 3

Tuesday, March 18, 2008

java: How to convert String array to Long array

String[] numbersString = {"1", "2", "3"};

List list = new ArrayList();

for (int i = 0; i <>
{
    Long tmp = Long.valueOf(s[i]);
    list.add(tmp); 
}    
//convert Long ArrayList to Long[] array 
Long[] numbersLong = (Long[])list.toArray(new Long[0]);

Saturday, March 15, 2008

java: How to put checkboxes in DisplayTag using Struts multibox


<display:table name="sessionScope.myFormBean.mySearchResultArrayList" id="myRecord">
<display:column title="Select">
<html:multibox property="selectedItems"
value='<%= (String)((com.abc.def.MyClass)myRecord).getAbc().toString() %>' />
</display:column>
</display:table>


Note:

myFormBean is the name of your Form Bean (i.e. MyFormBean.java)

mySearchResultArrayList is a collection getter in your MyFormBeanName.java. It will hold a collection of your MyClass.java

MyClass will represent each row in your DisplayTag (i.e. MyClass.java). Your mySearchResultArrayList will contain many MyClass.java

myRecord represents the reference to the MyClass object.

selectedItems is a String array property in your MyFormBeanName.java with a getter/setter. It will hold the values of the selected checkboxes. It will also be the name of the checkbox group in html.


MyClass.java


public class MyClass
{
private String abc;

public void setAbc(String abc)
{
this.abc = abc;
}

private String getAbc( )
{
return abc;
}
}



MyFormBean.java

public class MyFormBean
{
private String[ ] selectedItems;
private List mySearchResultArrayList;

public void setMySearchResultArrayList(List list)
{
mySearchResultArrayList = list;
String[] selectedItems = (String[]) mySearchResultArrayList.toArray(new String[0]);
}

public List get
MySearchResultArrayList( )
{
return
mySearchResultArrayList;
}

public String[ } getSelectedItems( )
{
return
selectedItems;
}

public void setSelectedItems(String[ ] selectedItems)
{
this.selectedItems = selectedItems;
}
}

java: How to get DisplayTag sorting URL to work in Struts Tiles

Simply put requestURI with blank value onto the DisplayTag attribute.


<display:table name="sessionScope.myForm.searchResult"
id="record"
requestURI="">

</display:table>

java: How to convert a String ArrayList into String array

String[] stringArray = (String[]) stringArrayList.toArray(new String[0]);

java: The difference between the HTML comment <!-- --> and the JSP comment <%-- --%>

The HTML comment will show up in browser view source.

The JSP comment <%-- --%> will not show up in browser view source.

Monday, March 10, 2008

java: Why Log4J's Logger should be declared static final

Declaring Logger to be static final is recommended, particularly for long lived objects such as the Struts Action class
http://www.owasp.org/index.php/Poor_Logging_Practice:_Logger_Not_Declared_Static_Final

e.g.
private static final Logger LOGGER = Logger.getLogger(Donkey.class)

The Struts framework creates only one instance of an Action class for all client requests. e.g. FooAction and BarAction will only be created once.
Static means the Logger is not specific to a particular client request, but is shared by all requests.
Final means the Logger will only be instantiated once.

Logger is tread safe because it doesn't hold a state.

Sunday, February 24, 2008

Java: Eclipe's notion of classpath 101

In Eclipse, if you don't specify the build path, your classes by default will be placed in the base classpath of your project module. E.g.
C:\workspaces\myproject\myModuleEJB\classes\xxx

Therefore, your base classpath is C:\workspaces\myproject\myModuleEJB\classes\xxx

Consider two spring config source folders :
C:\workspaces\myproject\myModuleEJB\testsrc\spring\testApplicationContext.xml
C:\workspaces\myproject\myModuleEJB\configsrc\spring\businessRules.xml

testApplicationContext.xml is referring to businessRules.xml e.g.

testApplicationContext.xml
===================

<bean id="businessRules" init="false" class="org.springframework.context.support.ClassPathXmlApplicationContext">
<constructor-arg>
<list><value>spring/businessRules.xml</value></list>
</constructor-arg>
</bean>


both testApplicationContext.xml and businessRules.xml are compiled by Eclipse into
C:\workspaces\myproject\myModuleEJB\classes\spring\testApplicationContext.xml
C:\workspaces\myproject\myModuleEJB\classes\spring\businessRules.xml

therefore, if testApplicationContext.xml wants to refer to businessRules.xml, the testApplicationContext.xml has to refer to the base classpath location of businessRules.xml
ie. /spring/businessRules.xml

Sunday, February 03, 2008

java: A simple ANT template


<?xml version="1.0" ?>
<project name="secondbuildJAR" default="compile">

<property file="${user.home}/build.properties"/>

<property name="source.dir" location="src"/>
<property name="build.dir" location="build"/>
<property name="build.classes.dir" location="${build.dir}/classes"/>
<property name="distribution.dir" location="dist"/>
<property name="distribution.doc.dir" location="${distribution.dir}/doc" />


<property name="project.name" value="${ant.project.name}" />
<property name="project.version" value="0.1.alpha" />
<property name="target.name" value="${project.name}-${project.version}.jar" />
<property name="target.jar" location="${distribution.dir}/${target.name}" />


<patternset id="meta.files">
<include name="**/*.xml"/>
<include name="**/*.properties"/>
</patternset>


<path id="compile.classpath">
<fileset dir="lib">
<include name="*.jar"/>
<include name="*.zip"/>
</fileset>
</path>



<path id="run.classpath">
<path refid="compile.classpath"/>
<pathelement location="${target.jar}"/>
</path>



<target name="clean">
<delete dir="${build.dir}" />
<delete dir="${distribution.dir}" /> <!--this will delete both dist and dist/doc -->

<mkdir dir="${build.classes.dir}" />
<mkdir dir="${distribution.doc.dir}" />
</target>



<!-- Copy metadata to build classpath -->
<target name="copymetafiles" depends="clean">
<copy todir="${build.classes.dir}">
<fileset dir="${source.dir}">
<patternset refid="meta.files"/>
</fileset>
</copy>
</target>



<target name="compile" depends="copymetafiles" description="Compiles the project">
<javac srcdir="${source.dir}"
destdir="${build.classes.dir}"
debug="${build.debug}">
<classpath refid="compile.classpath"/>
</javac>
</target>


<target name="archive" depends="compile" description="JARs up the project">
<jar destfile="${target.jar}"
duplicate="preserve"
manifest="${source.dir}/META-INF/MANIFEST.MF">
<fileset dir="${build.classes.dir}"/>
</jar>
</target>



<target name="execute" depends="archive" description="Executes the main class">
<echo>running this program now!!!</echo>
<java classname="org.antbook.welcome.Main" classpathref="run.classpath" failonerror="true">
<arg value="a" />
<arg value="b" />
<arg file="." />
</java>
<echo>end running the program!!!</echo>
</target>


<target name="echo">
<echo message="ant.file = ${ant.file}" /><!--where this ant file is located-->
<echo message="ant.home = ${ant.home}" />
<echo>ant.version = ${ant.version}</echo>
<echo>java.home = ${java.home}</echo>
<echo message="ant.java.version = ${ant.java.version}" />
<echo>ant.project.name = ${ant.project.name}</echo>
<echo>user.name = ${user.name}</echo>
<echo>user.home = ${user.home}</echo>
<echo>basedir = ${basedir}</echo>
<echo>build.debug = ${build.debug}</echo>
</target>



</project>

Sunday, January 06, 2008

java/linux: Setup ClassPath in Unix/Linux (ubuntu) on your .bashrc

If you want to be able to call eclipse / ant / java from any prompt in your linux system, then
edit your .bashrc and add this lines :

# User specific environment and startup programs
export ECLIPSE_HOME=/usr/local/eclipse
export JAVA_HOME=/usr/lib/jvm/java-6-sun
export ANT_HOME=/usr/share/ant

PATH=$PATH:$ECLIPSE_HOME:$JAVA_HOME/bin:$ANT_HOME/bin

export PATH


note: $PATH is how your current path is configured. If you type in echo $PATH in the command line, you should see something like this
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:

The colon ":" is simply just the delimiter.

Once you've edited your .bashrc, reboot your pc (or type ctrl + alt + backspace) for your new settings to take effect. After you've rebooted, type the following from the command line and see the results :

echo $JAVA_HOME


See :

http://java.sun.com/docs/books/tutorial/essential/environment/paths.html

Monday, October 02, 2006

java/linux: Installing JDK/JavaSE

From command prompt, su as root.

create dir /usr/java
place jdk-1_5_0_09-linux-i586.bin in /usr/java

chmod 777 jdk-1_5_0_09-linux-i586.bi

From /usr/java type
./jdk-1_5_0_09-linux-i586.bin

JDK is now installed in /usr/java/jdk1.5.0_09

Sunday, January 22, 2006

java: Generating unique sequence of numbers

Calendar calendar = Calendar.getInstance(TimeZone.getDefault());

//generate a unique sequential number. We derive this from the
//number of
milliseconds since 00:00:00 GMT Jan. 1, 1970 using //calendar object.
String runNumber = new Long(calendar.getTime().getTime()).toString();

System.out.println(runNumber);

java: Sorting Dates in a List (Collection)

final String DATE_FORMAT = "dd/MM/yy";
DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
dateFormat.setTimeZone(TimeZone.getDefault());

//we store date as time in milliseconds.
//getTime() returns the number of milliseconds since
//midnight of January 1, 1970. This method is also very
//useful for generating a unique sequence of numbers.
Long date0 = new Long(dateFormat.parse("29/01/1995").getTime());
Long date1 = new Long(dateFormat.parse("13/12/2007").getTime());
Long date2 = new Long(dateFormat.parse("01/04/2000").getTime());

List dateList = new ArrayList();
dateList.add(date0);
dateList.add(date1);
dateList.add(date2);

Collections.sort(dateList);

//Get wrapper Long from list. convert Long to String. 
//Convert String to primitive long. Convert primitive long to Date.
Date dateLatest = new Date(Long.parseLong(((Long) dateList.get(dateList.size()-1)).toString()));
String dateLatestString = dateFormat.format(dateLatest);

System.out.println(dateLatestString);