Java Code Samples
Check Null ======> System.out.println( "actualValue ======> " + ( (actualValue != null)? actualValue: "NULL") );
Dynamically Getting parameters from a property file:
A Value in Property File:
FILE_NAME = ABC-rpt_{0}_{1}_WXD_{2}.out
How to populate FILE_NAME dynamically in Java:
Object[] args = {"Frank","Wang","2011-07-10"};
theFileName = PropertyFileHandler.getInstance().getProperty("FILE_NAME",args);
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Properties;
import org.apache.log4j.Logger;
public class PropertyFileHandler
{
private static final PropertyFileHandler instance = new PropertyFileHandler();
private static final String PROPERTY_PATH = "/myPropertyFile.properties";
private static final Logger log = Logger.getLogger(PropertyFileHandler.class);
private Properties props;
private PropertyFileHandler()
{
props = new Properties();
InputStream inputStream = getClass.getResourceAsStream(PROPERTY_PATH);
try {
props.load(inputStream);
}
catch(IOException ex) {
log.error( ex.getMessage() );
}
}
private PrppertyFileHandler(String filePath)
{
props = new Properties();
FileInputStream fileInputStream = getClass.getResourceAsStream(filePath);
try {
props.load(fileInputStream);
}
catch(IOException ex) {
log.error( ex.getMessage() );
}
}
private PrppertyFileHandler(Properties preperties)
{
props = properties;
}
public static PropertyFileHandler getInstance()
{
return instance;
}
public String getProperty(String propertyKey, Object[] args)
{
String theResult = "";
try {
theResult = props.getProperty(propertyKey);
theResult = MessageFormat.format( theResult, args);
}
catch(Exception ex) {
{
log.error( ex.getMessage() );
}
return theResult;
}
} //end of class
UNIX Commands
To see my current directory:
$ pwd
$ ls -l
$ mkdir input
Change mode to a directory to [write permitted]:
$ sudo chmod 777 /home/usr/frank
To Change Directory:
$ cd ..
$ cd opt/frank/input
To display the users currently logged in:
$ who
To see current login user name:
$ who am i
Dynamically monitor a log file in UNIX:
$ tail -f system.out
Copy files to upper directory:
$ cp *.* ..
Copy files to a directory:
$ cp *.* /home/devuser/frank
Search a file for a pattern (e.g.: looking for a file in which String "sue" is contained in it):
$ grep sue temp
Display contents of a file:
$ cat myfile
Move files (from one location to another. e.g.: move 3 files --- section1, section2, section3 --- to the sub-directory called Chapter1):
$ mv section1 section2 section3 Chapter1
$ mv sec* Ch*1
Find Files (e.g: search the entire system for files whose names contain String "data" in them):
$ / find -name "*data*" -print
$ find -mtime -6 ===> get all files that were modified within 6 days
Remove / Delete Files (remove/delete all files in current directory):
$ rm *
$ rm *.docx
$ rm -i * ===> prints the name of each file and waits for your response before deleting it.
Remove/Delete a directory:
$ rm -r /home/usr/temp
Remove Files that were modified within 6 days:
$ find -mtime -6 -exec rm -f {} \
Edit a File:
vi filename
a --- append mode
x --- delete mode
[ESC] key --- escape from current mode
:q! --- quit without saving
:wq! --- quit and save changes
Parser:
try
{
BufferedReader reader = new BufferedRead( new InputStreamReader( new FileInputStream("C:\\TEMP\\data.csv") ) );
String workStr = "";
while( (workStr = reader.readLine()) != null )
{
workStr.trim();
}
catch( FileNotFoundException ex ) {
...... }
Generator:
try {
PrintWrintWriter writer = new PrintWriter( new FileOutputStream(
output_filePath ) );
writer.write(
outputStringBuffer.toString );
writer.close();
}
catch( IOException ex ) {
......
}
Zip / un-zip a JAR file:
$ jar -cvf myJarFile.jar *.*
$ jar -xvf myJarFile.jar
Database BLOB issue:
Connection conn = DBConnection.getConnection();
PreparedStatement pstmt = null;
String filename = "index.dat";
String input_blob_file_path = "C:/TEMP/" + filename;
String output_blob_file_path = "C:/DATA/" + filename;
int MAX_BYTE_ARRAY_SIZE = 30720;
int sizeOfBlobFile = 16360;
// insert BLOB data into database table:
try {
pstmt = conn.prepareStatement( "insert into TABLE2(id, file_name, blob_size, blob_data, is_valid_flag, create_user, update_user)" +
+ " values(ATTACHMENT_SEQ.NEXTVAL, ?,?,?,?,?,?)" );
pstmt.setString(1, filename);
pstmt.setString(2, sizeOfBlobFile);
File blobFile = new File( input_blob_file_path );
FileInputStream fileInputStream = new FileInputStream( blobFile );
pstmt.setBinaryStream(3, fileInputStream, (int) blobFile.length() );
pstmt.setString( 4, "true" );
pstmt.setString( 5, "Frank Wang" );
pstmt.setString( 6, Frank Wang" );
pstmt.execute();
pstmt.close();
}
catch(Exception ex) {
...... }
// select BLOB data from database table:
//
InputStream blobFile_inputStream = null;
int current_row_number = 0;
try {
Statement stmt = conn.createStatement();
ResultSet resultSet = stmt.executeQuery( "select max(ID) from TABLE2" );
if( resultSet.next() ) {
current_row_number = resultSet.getInt( 1 );
}
resultSet.close();
ResultSet resultSet2 = stmt.execute( "select BLOB_DATA from TABLE2 where id = " + current_row_number );
while( resultSet2.next() ) {
java.sql.Blob blobData = resultSet2.getBlob( "BLOB_DATA" );
blobFile_inputStream = blobData.getBinaryStream();
}
resultSet2.close();
stmt.close();
FileOutputStream fileOutputStream = new FileOutputStream( output_blob_file_path );
PrintWriter writer = new PrintWriter( fileOutputStream );
byte byteArray[] = new byte[MAX_BYTE_ARRAY_SIZE];
int index = blobFile_inputStream.read( byteArray, 0, MAX_BYTE_ARRAY_SIZE );
while( index != -1 )
{
fileOutputStream.write( byteArray, 0, index );
index = blobFile_inputStream.read( byteArray, 0, MAX_BYTE_ARRAY_SIZE );
}
fileOutputStream.flush();
writer.flush();
writer.close();
}
catch(Exception ex) {
ex.printStackTrace();
}
How to convert a Base64Encoded-String to a file?
To save a Binary-String as a File, Always convert it to [InputStream] first!!
1. fileContentByte[] = Base64Decoder.decodeBuffer(inputBinaryString);
2. InputStream inputStream = new ByteArrayInputStream( fileContentByte[] );
3. Where to save:
FileOutputStream outputStream = new FileOutputStream( filePath_for_output );
4. Write the content to the file and save it:
byte[] buffer = new byte[4*1024] ;
int bytesRead = 0;
while( (bytesRead = inputStream.read(buffer)) != -1 ) {
outputStream.write( buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
outputstream.close();
Performance Evaluation:
long startTime =
System.currentTimeMillis();
....................
long endTime =
System.currentTimeMillis();
System.out.println(
"Process time = " + (endTime - startTime) );
GIT Commands:
Create a working copy of a local repository:
$ git clone /path/to/repository
$ git clone username@host:/path/to/repository
Create a new branch:
$ git branch my_new_branch/dev
Create or switch to a new branch:
$ git checkout -b feature/frank
Setup a branch to tract the remote branch 'develop' from 'origin':
$ git branch --set-upstream-to=origin/develop
Commit changes to a branch:
$ git commit -a -m "feature frank OK"
Push all changes to branch:
$ git push origin HEAD
Others:
$ git status
$ git switch origin/frank-dev
$ git pull --rebase
Java Enum Sample Code