Conventions: s - string, i - int, b - boolean, l - long, f - float MyClass - subclass of Class oMyClass - instance of MyClass - 1 public class / src f required - any nu nonpublic classes - f name must = public clas name + .java.
I. java.lang
a. Wrapper Classes
TYPE CONVERSION Long.parseLong(s); Long.toString(l); Integer.toString(i); // int -> string Integer.parseInt(s); // string -> int List oList = oStringArray.asList(oStringArray); // string array -> list String str = Integer.toString(i); or String str = "" + i String str = Double.toString(d); String str = Long.toString(l); String str = Float.toString(f); String to integer : str = "25"; int i = Integer.valueOf(str).intValue(); or int i = Integer.parseInt(str); double d = Double.valueOf(str).doubleValue(); long l = Long.valueOf(str).longValue(); or long l = Long.parseLong(str); float f = Float.valueOf(str).floatValue(); decimal to binary : int i = 42; String binstr = Integer.toBinaryString(i); decimal to hexadecimal : int i = 42; String hexstr = Integer.toString(i, 16); or String hexstr = Integer.toHexString(i); hexadecimal (String) to integer : int i = Integer.valueOf("B8DA3", 16).intValue(); or int i = Integer.parseInt("B8DA3", 16); ASCII code to String int i = 64; String aChar = new Character((char)i).toString(); integer to ASCII code (byte) char c = 'A'; int i = (int) c; // i will have the value 65 decimal To extract Ascii codes from a String String test = "ABCD"; for ( int i = 0; i < test.length(); ++i ) { char c = test.charAt( i ); int j = (int) c; System.out.println(j); } integer to boolean b = (i != 0); boolean to integer i = (b)?1:0; note :To catch illegal number conversion, try using the try/catch mechanism. try{ i = Integer.parseInt(aString); } catch(NumberFormatException e) { }
II. Tools
a. Eclipse Java IDE Market share is: eclipse 45%, Borland JBuilder 16%, IDEA IntelliJ 10%, Others 29% (QA Systems 2003). Alternatives; Struts Studio, RoamingStudio (www.roamingmedia.com ) etc.
Adding New Project: File > New > Project > Java: Java Project > Proj.Name: atb40 & Proj contents: c:\atb40\atbiws60 > Java Settings: Src: i/p: WEB-INF/src + o/p: WEB-INF/classes & Order and Export: "Select All"
[shift] --> | ← (select text) ^C (copy) ^V (paste) ^L (line no) ^F (find) - auto gen comments + javadoc: Window > Preferences > Java > Code Generation > Code and Comments - auto gen getter/setter for formbean/dto: def all vars; r(anywhere in prog) > Source > Gen. Getter + Setter > Select All - makg new divisn: drag prog by title bar --> on boundary, arrow becoms + - org imports: r(Prog) > Source > Organize Imports - make as tab: drag till cascaded notebook icon appears -> usu. Outline, Hierarchy, Pkg Explorer as tabs in one window - cvs comments: eclipse:Window>Preferences>Java>Code Generation>Code and Comments /* * $$Header$$ * $$Author$$ * $$Date$$ * $$Revision$$ * $$Id$$ * $$Log$$ * * ============================================================== * * Copyright (c) ${year},All rights reserved. */ - line width / margin: Project Code Style > Edit Global Settings > General > Right margin = 80
- "server Error" & window: "Compilation Problems" -> stop Sun One, rebuild all in eclipse. - eclipse copies src/*.properties to src/*.classes
b. ant
<project name="MyStrutsProject" default="dist" basedir="."> <description> struts ant buildfile </description> <property name="xsrc" location="WEB-INF/src"/> <!-- set global properties for this build --> <property name="xbuild" location="WEB-INF/classes"/> <property name="xdist" location="WEB-INF/dist"/> <target name="init"> <tstamp/> <!-- create time stamp --> <mkdir dir="${xbuild}"/> </target> <target name="compile" depends="init" description="compile srcs"> <!-- Compile the java code from ${src} into ${build} --> <javac srcdir="${xsrc}" destdir="${xbuild}" classpath="WEB-INF/lib"/> </target> <target name="dist" depends="compile" description="make war"> <war warfile="f-${DSTAMP}.war" webxml="web.xml"> <fileset dir="."> <!-- include all JSPs in root level --> <include name="*.jsp"/> <include name="*.xml"/> </fileset> <lib dir="./WEB-INF/lib"> <include name="*.jar"/> </lib> <!-- include all tag libraries in WEB-INF, but not web.xml (that's handled separately) --> <webinf dir="WEB-INF/"> <include name="*.tld"/> </webinf> <classes dir="./WEB-INF/classes"/> <!-- include all compiled classes --> </war> </target> <target name="deploy"> <!-- Copy the war file to the JBoss deploy directory --> <copy file="f.war" todir="."/> </target> <target name="all" depends="dist,deploy"/> </project>
<project name="ATB3.2" default="compile" basedir="."> <description> ATB 3.2 ant buildfile <property name="psrc" location="WEB-INF/src"/> <property name="pbuild" location="WEB-INF/classes"/> <property name="pdist" location="WEB-INF/dist"/> <property name="plib" location="WEB-INF/lib"/> <target name="init"> <tstamp/> <mkdir dir="${pbuild}"/> </target> <target name="compile" depends="init" description="compile srcs"> <!-- Compile the java code from ${src} into ${build} --> <javac srcdir="${psrc}" destdir="${pbuild}"> <classpath path="${plib}"> <fileset dir="${plib}"> <include name="*.jar"/> </fileset> </classpath> </javac> </target> <target name="build" depends="compile" description="make war"> <war warfile="f-${DSTAMP}.war" webxml="WEB-INF/web.xml"> <fileset dir="."> <!-- include all JSPs in root level --> <include name="*.jsp"/> <include name="*.xml"/> </fileset> <lib dir="WEB-INF/lib"> <include name="*.jar"/> </lib> <!-- include all tag libraries in WEB-INF, but not web.xml (that's handled separately) --> <webinf dir="WEB-INF/"> <include name="*.tld"/> </webinf> <classes dir="./WEB-INF/classes"/> </war> </target> </project>
II. JDBC
String query = "SELECT T_NAME, PRICE FROM TOFFEES"; ResultSet rs = stmt.executeQuery(query); while (rs.next()) { String s = rs.getString("T_NAME"); float n = rs.getFloat("PRICE"); System.out.println(s + " " + n); String s = rs.getString | getInt (1); // usg col index, 1 = 1st col float n = rs.getFloat(2); } while (oResultSet.next()) { oVector.addElement( oResultSet.getLong("task_type_id")); v.add(r.getString("name")); ... } List list = new ArrayList (); while (rs.next ()) { list.add (report); } ... ArrayList arrayList = new ArrayList(); while (resultSet.next()) { String isbn = resultSet.getString(1); arrayList.add(isbn); } preparedStatement.close(); return arrayList; ... int colType = rs.getColumnType(1); correspond to sql data types: -7 BIT -6 TINYINT -5 BIGINT -4 LONGVARBINARY -3 VARBINARY -2 BINARY -1 LONGVARCHAR 0 NULL 1 CHAR 2 NUMERIC 3 DECIMAL 4 INTEGER 5 SMALLINT 6 FLOAT 7 REAL 8 DOUBLE 12 VARCHAR 91 DATE 92 TIME 93 TIMESTAMP 1111 OTHER ... ResultSetMetaData oResultSetMetaData = oResultSet.getMetaData(); int numCols = oResultSetMetaData.getColumnCount();"jdbc:oracle:thin" - "thin driver" as it doesn't require Oracle native libs to be installed on clt jdbc:oracle:thin:@192.255.132.46:1521:orcl
for (int i = 0; rs.next(); i++) { selectedCheckBoxes[i] = rs.getString(1); }
try { conn = checkAndOpenTransaction(this); stmt = conn.createStatement(); rs = stmt.executeQuery(selectProcessorSQL); while (rs.next()) { ProcessorLogDTO dto = new ProcessorLogDTO(); dto.setName(rs.getString(PRTSConstants.NAME)); }... checkAndCommitTransaction(); } finally { DBUtil.cleanUp(conn, ps, rs); checkAndCloseTransaction(); } ... Obtaining Size of Scrollable ResultSet rs = ps.executeQuery(); // goto last row rs.last(); // obtain row position which is also number of rows in the result set. int numberRows = rs.getRow(); PRTSLogger.log( className, PRTSConstants.LOG_DEBUG, "size of resultset = " + numberRows); selectedCheckBoxes = new String[numberRows]; // reposition at beginning of resultset rs.beforeFirst();stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
ps = conn.prepareStatement( oString_sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); ps.setLong(1, Long.parseLong(requestServiceID) ); // requestServiceID query string .prtsdo?requestServiceID=5 + get/set in ActionForm + optnal hidden var) rs = ps.executeQuery(); rs.last(); // goto last line int i_nurows = rs.getRow(); // obtain row position which is also number of rows in the result set. String[] oStringArray = new String[i_nurows]; rs.beforeFirst(); // reposition at beginning of resultset for (int i = 0; rs.next(); i++) { oStringArray[i] = rs.getString(1); }
PreparedStatement - execute | executeQuery | executeUpdate = any kind of sql | return ResultSset | insert/update/delete - oConnection = checkAndOpenTransaction(this); // XA transactn, must be immediately before ps line PreparedStatement ps = oConnection.prepareStatement(sql); Connection conn = null; PreparedStatement ps = null; Statement stmt = null; ResultSet rs = null; try { conn = checkAndOpenTransaction(this); ps = conn.prepareStatement(insertProcessorSQL); ps.setString(NAME,procname); PRTSLogger.log(className,PRTSConstants.LOG_DEBUG,"MSG: ## added procname" ); ps.setLong(CUMULATIVE_HOURS,cumulative_hours); int rowsChanged = ps.executeUpdate(); checkAndCommitTransaction(); } catch(SQLException) ... org.postgresql.jdbc2.PreparedStatement ps2 = (org.postgresql.jdbc2.PreparedStatement) ps; Sop(ps2.toString() ); SQL errors - ORA-00001: unique constraint (PATH_DEV.PK_EM_TASK_DET_ID) violated: col_seq.nextval | currval already exists in the table. - ORA-01006: bind variable does not exist -> in preparedstmt remove single quotes from query while convertg from sql stmt to preparedstmt - error: 'pg cannot be displayed' + app not available before login --> eclipse compile error, stop sun one, recompile (as src/* cp'd to classes/, in turn used + locked by sun one)
TOAD - Extracting sql from gui insert: Tables > r(TABLE) > Export Data > Options : Destination = To File & Filename = _ ; then replace TO_Date(...) with sysdate.
PL-SQL select * from tab; select * from table order by col; | order by col DESC; INSERT INTO PTH_REQUEST_SERVICE ( REQUEST_SERVICE_ID, REQUEST_ID, SERVICE_TYPE_ID, INSTRUCTIONS, INSERT_USER, INSERT_DATE, UPDATE_USER, UPDATE_DATE, STATUS_ID, HAS_INSTRUCTION_CHANGED ) VALUES ( 901, 2, 1, 'new instructions', 1, sysdate, 1, sysdate, 1, NULL); select a.col1, b.col2 from table1 a, table2 b where a.col1 = b.col1 and a.col3 = b.col3 and a.col4 = 'ostring'; commit; (if sql+)
prts method signature method skeleton public ClinPathDTO get(long clinPathId) throws ApplicationException { PreparedStatement ps = null; ResultSet rs = null; ClinPathDTO clinPathDTO = new ClinPathDTO(); try { Connection conn = checkAndOpenTransaction(this); ps = conn.prepareStatement(insertClinPathSQL); ... checkAndCommitTransaction(); } catch(SQLException sqle) { rollbackTransaction(); throw new DataAccessException(sqle,0,"An error occured while accessing db"); } catch(ApplicationException ae) { rollbackTransaction(); throw new ApplicationException(ae,0,"An error occured in the get method"); } finally { DBUtil.cleanUp(ps,rs); checkAndCloseTransaction(); } return clinPathDTO; }
package ...
/**
* MyClass displays a square garden field using Graphics
.
*
* @author Samar Abbas
* @version %I%, %G%
* @param mapping the ActionMapping used to select this instance
* @param form the optional ActionForm bean for this request (if any)
* @return the ActionForward for the next view
* @exception {= @throws} an exception
* @see ProcessorLogController
* @see "A Java Book"
*/
II. Collections
a. Arrays (Array Lists, String Arrays)
Cloneable cloning:
ArrayList oArrayList = new ArrayList(); oArrayList.addAll(Arrays.asList(oStringArray) ); oArrayList.addAll( qArrayList ); oArrayList.removeAll( Arrays.asList(oStringrray) );
for(int i = 0; i < oArrayList.size(); i++) { System.out.println( oArrayList.get(i) ); }
for(int i = 0; i < oStringArray.length; i++) { System.out.println( oStringArray[i] ); }
if ((s == null) || (s.equalsIgnoreCase("null")) || (s.trim().length() == 0)) { ... } dont use s == ""
1. usg java.util.AbstractSet class. AbstractSet setA = new AbstractSet(); // error by samar! dec. 30/03 setA.addAll(Arrays.asList(arrayA)); // string array A AbstractSet setB = new AbstractSet(); setB.addAll(Arrays.asList(arrayB)); // string array B setA.removeAll(setB); String[] cleanedA = setA.toArray(new String[]{}); In Reply To: Re: Difference of two int arrays, help please! public static void oppositeIntersection(int[] arr1, int[] arr2) { for(int i = 0; i < arr1.length; ++i) { boolean foundIt = false; for(int j = 0; j < arr2.length; ++j) { if(arr1[i] == arr2[j]) { foundIt = true; break; } } if(foundIt) System.out.println(arr1[i] + " exists in both arrays"); } } .. for (int x=0; x
a.