Java

Why to use File.separator and File.pathSeparator

Java programmers knows about methods quoted in title, but many doesn’t care with them.

These methods are useful for programmer that do not knows wich characters represents file separator and path separator at OS that supports your application.

Linux/Unix, the methods File.separator and File.pathSeparator returns “/” and “.”, while in Windows, these methods returns “\” (or “\\” – escape) and “;”.

In recent case, the code below threw exception FileNotFoundException running over Linux, but not running over Windows:

String appPath = ctx.getRealPath();
String filePath = appPath + "\\" + "WEB-INF/classes/my/application/packages/";

File file = new File(filePath, "report.pdf");
OutputStream out = new FileOutputStream(file);
...

Worked in both systems after to replace “\\” by File.separator in line 2:

String appPath = ctx.getRealPath();
String filePath = appPath + File.separator + "WEB-INF/classes/my/application/packages/";

File file = new File(filePath, "report.pdf");
OutputStream out = new FileOutputStream(file);
...

Utilization of these methods, besides a good practice, is very usefull when same version of an application is running over differents operacional systems.


How to read and write CLOB fields

The Character Large Object (or CLOB) is a commonly found in databases and used to store high quantity of characters.

At MySQL, for example, this field is called MEMO.

Writing CLOB field

The method setAsciiStream of PreparedStatement allow to pass data to a CLOB.

ps.setAsciiStream(bindPosition, inputStream, textLength);

bindPosition – Position in PreparedStatment’s CLOB field.
inputStream – Used to pass data.
textLength – Data (text) length.

Full code:

String sql = "INSERT INTO TABLE (text) VALUES(?)";
		try{
			String txt = readTxtFile();
			ByteArrayInputStream bais = new ByteArrayInputStream(txt.getBytes());

			PreparedStatement ps = conexao.prepareStatement(sql);
			//CLOB is '?' at first position
			ps.setAsciiStream(1, bais, txt.length());

			ps.execute();

			ps.close();
		}catch (Exception e) {
			e.printStackTrace();
		}

Retrieving CLOB data

We’re using SELECT clause, this clause returns a ResultSet to fetch data and, calling getClob method, passing column name or your position in the query, it give to you a Clob object.

rs.getClob("xml");

Full code:

String sql = "SELECT xml FROM TEST";
		try{
			PreparedStatement ps = conexao.prepareStatement(sql);
			ResultSet rs = ps.executeQuery();

			while(rs.next()){
				Clob clob = rs.getClob("xml");
				BufferedReader reader = new BufferedReader(clob.getCharacterStream());
				StringBuffer strBuf = new StringBuffer();

				String linha = null;
				while((linha = reader.readLine()) != null){
					strBuf.append(linha);
//Character.LINE_SEPARATOR insert break line
					strBuf.append((char)Character.LINE_SEPARATOR);
				}

				System.out.println("=========== CLOB ===========");
				System.out.println(strBuf.toString());
			}

			rs.close();
			ps.close();
		}catch (Exception e) {
			e.printStackTrace();
		}

That’s it! Easy and painless ;)

Download full code here

To write a BLOB see this tutorial.


Setting up internet access through proxy server

Today I had a trouble in my workplace when a client application, running through a terminal (DOS prompt), not reach the server hosted in the internet, this is because the company where I work use proxy.

After some tries I found two solutions to solve my access problem: first was pass as Java parameters the proxy’s configurations.

$ java -Dhttp.proxyHost=serv -Dhttp.proxyPort=port -Dhttp.proxyUser=user -Dhttp.proxyPassword=pass  ClassJava

-Dhttp.proxyHost = IP or host name of server proxy
-Dhttp.proxyPort = Proxy port
-Dhttp.proxyUser = User
-Dhttp.proxyPassword = Password

This way the class ClassJava will have access to internet through proxy server.

Another way, was insert the settings in own class:

public static void main(String[] args){
...
System.getProperties().put("proxySet", "true");
System.getProperties().put("http.proxyHost", "serv");
System.getProperties().put("http.proxyPort", "port");
System.getProperties().put("http.proxyUser", "user");
System.getProperties().put("http.proxyPassword", "password");
...
}

proxySet = Connect, or not, through proxy server
http.proxyHost = IP or host name of server proxy
http.proxyPortt = Proxy port
http.proxyUse = User
http.proxyPassword = Password

Using this resource you can set your application to access the internet through proxy server.

I hope help you.  Bye! ;)


Creating transparent and shaped windows using Java Swing/AWT

The Java AWT offer various possibilities about window manipulation. Today I’ll talk about two possibilities using class AWTUtilities.

Building a transparent window

To make a Window (JFrame, JDialog …) with alpha effect, you should invoke the method AWTUtilities.setWindowOpacity. This method parameters are: the window to apply transparency and transparency degree, that can be between 0 (zero) and 1, being 0 invisible and 1 totally visible.

JFrame  window = new JFrame("My Window");

//70% of transparency
AWTUtilities.setWindowOpacity(window, .7f);
window.setSize(800,600);
window.setVisible(true);

The result will be:

Changing window shape

To change the window shape you should use the method AWTUtilities.setWindowShape. This method parameters are: window that will be changed and the new shape (java.awt.Shape) of the window.

The most efficiently form to use is to implement the method componentResized(), cause you may recompute the window and components size

Here I’ll use a triangle with 70% of transparency.

final JFrame  window = new JFrame("My Window");

try {
	//Add the ComponentListener to implement componentResized method
	window.addComponentListener(new ComponentAdapter(){
		@Override
		//building componentResized
		public void componentResized(ComponentEvent e) {
			int[] x = {0,400,800}; //Pontos X do polígono
			int[] y = {600,0,600}; //Pontos Y do polígono

			//Triangle with 800 w x 600 h
			Shape shape = new Polygon(x, y, 3);

			AWTUtilities.setWindowShape(window, shape);

			//70% of transparency
			AWTUtilities.setWindowOpacity(window, 0.7f);
		}
	});
} catch (SecurityException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
} catch (IllegalArgumentException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
}

window.setUndecorated(true); //removing title bar
window.setSize(800,600);
window.setVisible(true);

Notice that the method setUndecorated( ) was invoked with true as value. This method are responsible by hide the title bar (one with icon and the maximize, minimize and close buttons). This is really necessary, because with title bar visible the window are not be shaped.

The result:

I hope you enjoy… ;)


Saving files in BLOB table column of a data base

To insert a file, is it in any format, you need call the method setBinaryStream, implemented by PreparedStatement.

PreparedStatemente.setBinaryStream(int index, Inputstream is, int length);

In sample, we set a table called FILEthat contains BLOB column called BIN.

//Normal connection, as any JDBC connection
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@<IP>:<PORT>:<SID>","<USER>","<PASSWORD>");

//Reading the file and retrieving an InputStream
File file= new File("<COMPLETE_FILE_PATH>");
FileInputStream fis = new FileInputStream(file);

//Preparing statement
PreparedStatement ps = conn.prepareStatement("INSERT INTO FILE(bin) VALUES(?)");

//Passing InputStream and file length
ps.setBinaryStream(1, fis, (int)file.length());

ps.execute();

ps.close();
conn.close();

I used Oracle 8i to execute this sample. I haven’t a MySQL/PostgreSQL/MS SQL Server in my dispose, then you’ll responsible for testing in this data bases and send me the results, OK ;)

Thanks! Until next time!


  • AdSense

  • Copyright © 1996-2010 André L. S.. All rights reserved.
    iDream theme by Templates Next | Powered by WordPress