Monday, December 17, 2007

How to get the numbers out of a GRASS raster map in JGrass


// Get the current active region from the mapset path
Window originalActiveRegion = Window.getActiveWindowFromMapset(mapsetPath);

// adapt the region to a poligonal geometry extracted from a feature,
// let's say basinBounds
Window readRegion = Window.adaptActiveRegionToEnvelope(basinsBounds,
originalActiveRegion);

// shrink the active region to the needed part in order to make the scripts work
// without overhead
Window.writeActiveWindowToMapset(mapsetPath, readRegion);

// create the reader
JGrassRasterMapReader jgReader = new JGrassRasterMapReader(readRegion,
elevationMapName, mapsetName, locationPath, monitor);

// read the data
RasterData rasterData = null;
if (jgReader.open() && jgReader.hasMoreData()) {
rasterData = jgReader.getNextData();
}

// and rasterdata is just a wrapper around a matrix based dataset,
// so just loop over it with two nested for loop in rows and cols.
// this was done just to make migration to geotools coverage
// easier at some point

Friday, December 14, 2007

Hot to get mad with the paths in rcp environments

How do I get to a folder with a relative path to my installation? If this and many other questions about what is where came to your mind, read on:


// 1
// get the file path from resources in a bundle
try {
URL fileURL = FileLocator.find(Platform.getBundle("eu.hydrologis.jgrass.hydrocare"),
new Path("/icons/extract.png"), null);
fileURL = FileLocator.toFileURL(fileURL);
String fileUrlPath = fileURL.getPath();
System.out.println(fileUrlPath);
} catch (Exception e1) {
e1.printStackTrace();
}
// get paths in eclipse
// 2
URL pluginInternalURL = Platform.getInstanceLocation().getURL();
System.out.println(pluginInternalURL.getPath());
// 3
pluginInternalURL = Platform.getInstallLocation().getURL();
System.out.println(pluginInternalURL.getPath());
// 4
pluginInternalURL = Platform.getConfigurationLocation().getURL();
System.out.println(pluginInternalURL.getPath());
// 5
pluginInternalURL = Platform.getUserLocation().getURL();
System.out.println(pluginInternalURL.getPath());
// 6
try {
pluginInternalURL = Platform.getLocation().toFile().toURL();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IllegalStateException e1) {
e1.printStackTrace();
}
System.out.println(pluginInternalURL.getPath());


/*
* in the case I launch it from inside eclipse the following appears
*/
// 1
// the path is correctly transformed in a local path
/Users/moovida/rcpdevelopment/WORKSPACES/jgrassudig33workspace/eu.hydrologis.jgrass.hydrocare/icons/extract.png
// 2
// instancelocation seems to be the workspace folder
/Users/moovida/rcpdevelopment/WORKSPACES/runtime-New_configuration/
// 3
// the install location is the path to the folder inside which I keep the target platform
/Users/moovida/rcpdevelopment/jgrass-udig-sdk-delta/
// 4
// configuration location is inside the metadata folder inside the eclipse
// ide workspace location I defined for my development
/Users/moovida/rcpdevelopment/WORKSPACES/jgrassudig33workspace/.metadata/.plugins/org.eclipse.pde.core/jgrassudig/
// 5
// the userlocation is a strange path that doesn't even exist
/Users/moovida/user/
// 6
// the platform location is the same as the workspace folder
/Users/moovida/rcpdevelopment/WORKSPACES/runtime-New_configuration/


/*
* in the case I launch it from an installed JGrass version
* (install folder is /Applications/jgrass3.0alpha/)
*/
// 1
// the path is correctly transformed in a local path
/Applications/jgrass3.0alpha/plugins/eu.hydrologis.jgrass.hydrocare_1.0.0/icons/extract.png
// 2
// instancelocation seems to be the workspace folder
/Applications/jgrass3.0alpha/jgrass.app/Contents/MacOS/workspace/
// 3
// the install location is infact the path inside which the application resides
/Applications/jgrass3.0alpha/
// 4
// configuration location is the configuration folder inside the installation
/Applications/jgrass3.0alpha/configuration/
// 5
// again the userlocation is a strange path that doesn't even exist
/Users/moovida/user/
// 6
// and again the platform location is the same as the workspace folder
/Applications/jgrass3.0alpha/jgrass.app/Contents/MacOS/workspace/

Thursday, December 13, 2007

How to deal with timezones in hsqldb - no gap filled yet?

Working with timeseries of environmental data, there is a big need to have the daylight saving switched OFF, else the unique dates will appear more than once :)

For now, with hsqldb and java there is only one way I found to deal with that, i.e. setting another timezone.

In the Italian Job case, Africa answers the call for help:
-Duser.timezone="Africa/Kinshasa"
saves us by giving the same zone, but without the daylight saving.

Thank God there is Kinshasa! ;)

Wednesday, December 12, 2007

How to zip and unzip folders with pure java

Searching for some nice code to zip and unzip folders I gathered some. Thought it would be good to clean it up a bit and put the pieces together. It is not supersafe, but it does the thing:


/**
* @param srcFolder path to the folder to be zipped
* @param destZipFile path to the final zip file
*/
static public boolean zipFolder( String srcFolder, String destZipFile ) {
if (new File(srcFolder).isDirectory()) {

ZipOutputStream zip = null;
FileOutputStream fileWriter = null;
try {
fileWriter = new FileOutputStream(destZipFile);
zip = new ZipOutputStream(fileWriter);
} catch (Exception ex) {
ex.printStackTrace();
return false;
}

addFolderToZip("", srcFolder, zip); //$NON-NLS-1$
try {
zip.flush();
zip.close();
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
return true;
} else {
return false;
}
}



/**
* @param zipFile the zip file that needs to be unzipped
* @param destFolder the folder into which unzip the zip file and create the folder structure
*/
public static void unzipFolder( String zipFile, String destFolder ) {
try {
ZipFile zf = new ZipFile(zipFile);
Enumeration< ? extends ZipEntry> zipEnum = zf.entries();
String dir = destFolder;

while( zipEnum.hasMoreElements() ) {
ZipEntry item = (ZipEntry) zipEnum.nextElement();

if (item.isDirectory()) {
File newdir = new File(dir + File.separator + item.getName());
newdir.mkdir();
} else {
String newfilePath = dir + File.separator + item.getName();
File newFile = new File(newfilePath);
if (!newFile.getParentFile().exists()) {
newFile.getParentFile().mkdirs();
}

InputStream is = zf.getInputStream(item);
FileOutputStream fos = new FileOutputStream(newfilePath);
int ch;
while( (ch = is.read()) != -1 ) {
fos.write(ch);
}
is.close();
fos.close();
}
}
zf.close();
} catch (Exception e) {
e.printStackTrace();
}
}



static private void addToZip( String path, String srcFile, ZipOutputStream zip ) {
File folder = new File(srcFile);
if (folder.isDirectory()) {
addFolderToZip(path, srcFile, zip);
} else {
byte[] buf = new byte[1024];
int len;
try {
FileInputStream in = new FileInputStream(srcFile);
zip.putNextEntry(new ZipEntry(path + File.separator + folder.getName()));
while( (len = in.read(buf)) > 0 ) {
zip.write(buf, 0, len);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}



static private void addFolderToZip( String path, String srcFolder, ZipOutputStream zip ) {
File folder = new File(srcFolder);
String listOfFiles[] = folder.list();
try {
for( int i = 0; i < listOfFiles.length; i++ ) {
addToZip(path + File.separator + folder.getName(), srcFolder + File.separator
+ listOfFiles[i], zip);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}

How to "serialize to" and "retrieve from" objects from hsqldb

Assuming ChartData implements the serializable interface:


String insertGraph ="INSERT INTO GRAFICI_BLOB (ID, DATA) VALUES (##, ?)"

ChartData chartData = chartsPage.getChartData();
// Serialize to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(chartData);
out.close();
} catch (IOException e2) {
e2.printStackTrace();
}
byte[] chartDataBytes = bos.toByteArray();

PreparedStatement str1 = null;
try {
str1 = con.prepareStatement(insertGraph);
str1.setBytes(1, chartDataBytes);
str1.executeUpdate();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (null != str1)
str1.close();
} catch (Exception ex) {
}

}

/*
* and the way back
*/
Statement stmt = con.createStatement();
String sql = the query to select your blob field... (in my case GRAFICO)

ResultSet res = stmt.executeQuery(sql);
byte[] bytes = res0.getBytes("GRAFICO");
// Deserialize from byte array
try {
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
runProperties.chartData = (ChartData) in.readObject();
in.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

How to insert and retrieve files in hsqldb

How to save files into hsqldb? How to restore them back?


String calibrationZip = "calibrazione.zip";
String newcalibrationZip = "new_calibrazione.zip";
String insertStr = "INSERT INTO CALIBRAZIONE_BLOB (ID, DATA) VALUES (##, ?)"
String sql = "select data as DATA from CALIBRAZIONE_BLOB where id = ##"
int runId = 1;


/*
* insert into blob
*/
FileInputStream fis = null;
PreparedStatement st = null;
try {
File fl = new File(calibrationZip);
fis = new FileInputStream(fl);
insertStr = insertStr.replaceFirst("##", String.valueOf(runId));
st = con.prepareStatement(insertStr);
st.setBinaryStream(1, fis, (int) fl.length());
st.executeUpdate();
} catch (Exception ex) {
System.out.println(ex);
} finally {
try {
if (null != st)
st.close();
} catch (Exception ex) {
}
try {
if (null != fis)
fis.close();
} catch (Exception ex) {
}
}

/*
* extract the blob
*/
sql = sql.replaceFirst("##", String.valueOf(runId));
try {
Statement statement = con.createStatement();
ResultSet rs = statement.executeQuery(sql);
if (rs.next()) {
InputStream is = rs.getBinaryStream("DATA");
FileOutputStream fos = new FileOutputStream(newcalibrationZip);
byte[] buff = new byte[8192];
int len;
while( 0 < (len = is.read(buff)) )
fos.write(buff, 0, len);
fos.close();
is.close();
}
rs.close();
statement.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

How to start it once again... let's hope for good...

This is one of my tries to get on with documenting in a continuos way the development part of JGrass together with uDig.

I hope someone will find that usefull. For sure it will be helpfull for me at some point to write documentations.

Enjoy!