Monday, August 09, 2010

Spicing your Code

In the road trying to develop in Java, i found that many things are repetitively useless.
Thus is how i thought that there must be a way for doing the same things, but in a simpler and faster way. And i was correct, with the introducing of JDK6, many features really became useful such as: annotations, generics and so on, this combined with power of the interfaces and abstract classes brought us all these necessary features to achieve such purpose.
Below i introduce two very interesting APIs that represent that i mean.

The first one is very interesting, because allows developers to reduce in the source code writing, avoiding waste of time implementing such that lines of code:

http://projectlombok.org/

For example: the most common case is to implement Settes/Getters, this can be easily implemented as follows:

01 import lombok.AccessLevel;
02 import lombok.Getter;
03 import lombok.Setter;
04
05 public class GetterSetterExample {
06 @Getter @Setter private int age = 10;
07 @Setter(AccessLevel.PROTECTED) private String name;
08
09 @Override public String toString() {
10 return String.format("%s (age: %d)", getName(), getAge());
11 }
12 }

An entire support is provided for Netbeans IDE.


The second one simplifies the usage of XML and Database Connections.

http://cjb.sourceforge.net/

Thus, an example of a connection looks like follows:


 39         JdbcConnection con = fvm.getDataStore().buildJdbcConnection();
40 //let's get the company ID to get the schema to which belogs
41 PreparedStatement ps = con.prepareStatement("select any_fied from any_table where id = ?");
42 ps.setString(1, request.getId());
43 QueryListener ql = new QueryListener() {
44 public String queryResult(ResultSet rs, JdbcConnection conn) throws SQLException {
45 if (rs.next()) {
46 return rs.getString(1);
47 }
48 return null;
49 }
50 };
51 String id = con.executeQuery(ql, ps);

This API Call your close() methods to connections, statements, etc safely with no hassle. Also allows to manually close
any connection object.
Provides a interesting XML schema to embed connection configurations and read it from any XML document.
Or just check out the following example:

 37         JdbcConnectionReader r = new JdbcConnectionReader();
38 r.parseDocument(getClass().getResourceAsStream("ComplexConn.xml"));
39 JdbcConnection con = r.buildJdbcConnection();

Where ComplexConn.xml resource looks like:
 1 <?xml version="1.0" encoding="UTF-8"?>
2 <jms:ServerDataContext
3 xmlns:mb="http://www.dacorpsoft.com/mapbeans"
4 xmlns:jms="http://www.dacorpsoft.com/jmapserver"
5 xmlns:jcore="http://cjb.sourceforge.net"
6 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
7 xsi:schemaLocation="http://www.dacorpsoft.com/jmapserver JMapServer2.0.xsd">
8 <jms:NameSpaceCatalog>
9 ....
28 </jms:NameSpaceCatalog>
29 <jms:DacorpDataSource>
30 <jcore:JdbcConnection jcore:alias="JNDI">
31 <jcore:Param>
32 <jcore:Key>jdniReferenceName</jcore:Key>
33 <jcore:Value>jdbc/geobase</jcore:Value>
34 </jcore:Param>
35 </jcore:JdbcConnection>
36 </jms:DacorpDataSource>
37 </jms:ServerDataContext>
38
where the Tag JdbcConnection contains information about a connection JNDI named geobase.

Try it and give'em a chance, both have good documentation to start to use them on your projects, may be they can save your time.

Saturday, June 26, 2010

Validate a document using JDom

Validate a document is easier in org.w3c.dom or even in JDom, just thanks to the usage of interfaces.
Here is a demo of how doing that:

public boolean validate(URL uschema) throws IOException {
try {
// 1. Lookup a factory for the W3C XML Schema language
SchemaFactory factory =
SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
// 2. Compile the schema.
// Here the schema is loaded from a java.io.File, but you could use
// a java.net.URL or a javax.xml.transform.Source instead.
// 3. Get a validator from the schema.
Schema schema = factory.newSchema(uschema);
Validator validator = schema.newValidator();
// 4. Parse the document you want to check.
//Source source = new StreamSource(in);
Source source = new org.jdom.transform.JDOMSource(document);
// 5. Check the document
validator.validate(source);
//System.out.println(file + " is valid.");
} catch (SAXException ex) {
this.validationMessage = ex.getMessage();
return false;
}
return true;
}

Thursday, May 13, 2010

org.geotools.data.jdbc.JDBCFeatureSource cannot be cast to org.geotools.data.FeatureStore

Using geotools 2.6.x, occurs an error in Postgis when a geo-table is not correctly structured for.

This error is thrown:

org.geotools.data.jdbc.JDBCFeatureSource cannot be cast to org.geotools.data.FeatureStore

To solve this, a table in POSTGIS always must have the GIST index, so a well formed table looks like as follows:


--drop table poi cascade;
create table poi(
pk_poi serial primary key,
name_poi varchar(10),
date_poi timestamp
);
SELECT AddGeometryColumn('', 'poi','the_geom',4326,'POINT',2);
CREATE INDEX poi_the_geom_gist
ON poi
USING gist
(the_geom);


problem solved!

Tuesday, March 02, 2010

Check your Windows port associations

Just when trying to discover, what application is using a port, i found this very interesting tool.

http://www.foundstone.com/us/resources/proddesc/fport.htm

Wednesday, February 10, 2010

Guarded Blocks in Java

In Java Threads, there are many times when it's necessary to wait until another process finishes. In this post, an example is below:

/*
* @author Miguel Angel Vega Pabon
* @version 1.0, Developed with Netbeans 6.8
*/
public class GuardedBlocks {

int times = 0;

/** Default constructor */
public GuardedBlocks() {
}

public synchronized void readData() {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(20);
times++;
System.out.println(times + "%");
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
notifyAll();
}

public synchronized void verify() {
if (times != 100) {
try {
wait();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
System.out.println("Data has been aquired successfully");
}

public static void main(String args[]) {
final GuardedBlocks gb = new GuardedBlocks();
Thread t = new Thread() {
public void run() {
gb.verify();
}
};
gb.readData();
t.start();
}
}


As you can see, the method readData is called first, and then the thread starts.
The method verify waits until the method readData finishes.
:)

Tuesday, August 19, 2008

Retrieving MAC address using JAVA

The next is a simple snippet to obtain the MAC address using a simple java routine.

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

public class MacAddress {

public static void main(String[] args) {
try {
InetAddress address = InetAddress.getLocalHost();

/*
* Get NetworkInterface for the current host and then read the
* hardware address.
*/
NetworkInterface ni = NetworkInterface.getByInetAddress(address);
byte[] mac = ni.getHardwareAddress();

/*
* Extract each array of mac address and convert it to hexa with the
* following format 08-00-27-DC-4A-9E.
*/
for (int i = 0; i < mac.length; i++) {
System.out.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "");
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
}
}
}

Monday, October 16, 2006

Creating a simple JSTL dynamic query?

Ok, maybe this seems to be very simple, but when anyone tries to make a query using JSTL figures out the following:

"As a rule, you should avoid using SELECT * FROM except for testing or debugging purposes, unless you really do need every column from the table. Performance will be enhanced if you request only those fields you actually intend to use. Additionally, SELECT * offers no control over the order of the returned fields because they're returned in the order in which they were declared in the CREATE TABLE statement."

The solution to this problem is following:

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<%@ taglib prefix="sql" uri="http://java.sun.com/jstl/sql_rt" %>

<sql:setDataSource var="datasource"
driver="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@192.168.1.11:1521:dacorp"
user="scott" password="tiger"/>
<sql:query var="emp" dataSource="${datasource}">
select * from VIEW_PERSONAL_EMS
</sql:query>
<html>
<head>
<title>Simple test</title
</head>
<body>
<br>
<br>
<table border="1" >
<%-- Get the column names for the header of the table --%>
<c:forEach var="columnName" items="${emp.columnNames}">
<th><c:out value="${columnName}"/></th>
</c:forEach>
<%-- Get the value of each column while iterating over rows --%>
<c:forEach var="row" items="${emp.rowsByIndex}">
<tr>
<c:forEach var="column" items="${row}">
<td><c:out value="${column}"/></td>
</c:forEach>
</tr>
</c:forEach>
</table>
</body>
</html>


This snippet will guide to some other who has this problem. When using this snippet, you'll see that the fetching of the results will be such as one desires.

I wish this could be helpful...

mikevegap@gmail.com