Posts Tagged ‘Java’

Is the Java Store dead ?

Friday, June 4th, 2010

I’ve been waiting since Devoxx for the Java Store to become available in Belgium.Seemingly zero changes since then :-(

Although it might not be the most original idea, it does sound like a natural fit for the java platform on the desktop.

Anyone knows if Oracle killed this off or if it died when James Gosling left Oracle ?

I for one am still rooting for this to actually happen. Yes I’m a dreamer.

Compiling Spring 3 from SVN on Linux

Wednesday, November 11th, 2009

Mostly so I don’t forget myself next time :-)

Don’t forget to checkout only the wanted HEAD revision from svn:

svn co -r HEAD https://src.springframework.org/svn/spring-framework/trunk spring-framework

If you have ant as part of your distro (as is the case in gentoo), download a binary ant distribution and run <your_new_ant_path>/bin/ant instead of the ‘default’ ant to prevent any classpath issues.

Make sure you do

export ANT_OPTS=”-XX:PermSize=128m -XX:MaxPermSize=128m”

If necessary add -Xmx512m or more too.

Enter build-spring-framework and run

<your_new_ant_path>/bin/ant

to build Spring. In order for Eclipse to be able to find all required jar’s, you’re probably best running the resolve ant target in most of the subprojects.

Open import the projects to an Eclipse workspace, set the IVY_CACHE classpath var in Eclipse prefs to spring-framework/ivy-cache

I had a few errors in tests for the oxm bundle failing, but since I don’t really need them anyways I just removed the src/test source dirs from the oxm project in Eclipse :-)

It’s 2 AM so yea, the above is probably pretty messy :)

Can’t find the Capabilities prefs pane or Classic Update?

Wednesday, December 17th, 2008

Eclipse 3.4 Ganymede introduces a new UI for software updates.

In order for the Help->Software Updates submenu to show up again:

  1. install the Eclipse SDK plugin if needed
  2. enable Classic Update in Preferences->General->Capabilities

Easy as eating … fries! :-)

64bit Flash plugin for Linux, finally!

Monday, November 17th, 2008

Pigs seem to be able to fly as Adobe today released a preview 64bit release of it’s Flash plugin!

Are the days of using nspluginwrapper finally over? I suppose we can’t expect too much of a preview but those days seem to be coming!

If now we get a fast 64bit native java runtime (with a working -client option please), I guess the productive life in the 64bit Linux world is finally no more painful than the 32bit world.

Kudos Adobe, this is a step in the right direction!

Now, please also create a Linux version equivalent (or even something better maybe) to Digital Editions and I can actually take advantage of my digital subscribtion to www.standaard.be to read the entire paper digitally.

The pain of setting the classpath through the Jar Manifest

Wednesday, October 8th, 2008

I’ll keep this short: jar manifests suck. I just found out a jar wasn’t loaded as it was supposed to because my manifest classpath entry was 70 chars long (including the first space!). All other lines were 71 chars long, except this one because the entry was finished, so I was missing one space.

Netbeans handles this nicely when I build my app consisting of a number of projects with jar dependencies. Everything ends up ready to run in the dist dir of the main project root. Neat and simple. In Eclipse I seem to overlook the ability to export a Jar with it’s dependencies’ classpath preconfigured & packaged alongside the project code. I mean, am I *supposed* to do this myself?

I guess I really need to upgrade to using ant or maven and automate these kinds of things … and I will! Euhm … soon!

Since this is a clientside project, I’ll finally make the step and get the right kind of certificate to sign my code and WebStart enable the entire thing. And unless I solve these issues, I’ll return to netbeans for that purpose, although MyEclipse finally enabled me to stick with Eclipse :(

Until I switch to something automated of course :-)

Tired now. Need sleep.

Nite nite.

PS: I was about to reread but I’m too tired, so sorry, it’s probably badly written and ill-structured (or something)

‘Fixing’ the slow JFileChooser on Windows XP

Friday, September 26th, 2008

Ever used a Java Swing app on Windows XP that seemed to freeze when you open a JFileChooser dialog? Apparently it’s caused by calls being made to Windows’ infamous integrated ‘compressed folders’ utility when files are recognized as archives.

The bad news is that every stable Sun JVM on Windows XP up to today suffers from this issue.
The good news that the issue has been f fixed in Java 1.6u10b07. Although I don’t presume to know the entire history of this bug, it seems a little sad to see this one was reported against release 1.4.2.

To fix on java versions predating 6u10b7, the only fix is effectively unregistering the zip folder dll from windows. Since I won’t quite use 6u10 until it’s GA and I’ve been a happy 7zip user on every OS I use for quite some time now I decided to go for the uninstall.

To unregister (and disable ‘Compressed Folders’):
regsvr32 /u %windir%\system32\zipfldr.dll

If you decide for some reason you can’t live without it and want to re-enable, execute again from a cmd :
regsvr32 zipfldr.dll

and you’ll be sending things to compressed folders before you know it :-)

GPL’d Java vs. Gosling Emacs

Monday, June 23rd, 2008

A nice comment on a slashdot story reporting on made advances in opening up Java taught me a few nice trivias on the history between Richard Stallman and James Gosling in the early days:

“In the early years (1984 to 1988), the GNU Project did not have a single license to cover all its software. What led Stallman to the creation of this copyleft license was his experience with James Gosling, creator of NeWs and the Java programming language, and UniPress, over Emacs. While Stallman created the first Emacs in 1975, Gosling wrote the first C-based Emacs (Gosling Emacs) running on Unix in 1982. Gosling initally allowed free distribution of the Gosling Emacs source code, which Stallman used in early 1985 in the first version (15.34) of GNU Emacs. Gosling later sold rights to Gosling Emacs to UniPress, and Gosling Emacs became UniPress Emacs. UniPress threatened Stallman to stop distributing the Gosling source code, and Stallman was forced to comply. He later replace these parts with his own code. (Emacs version 16.56). (See the Emacs Timeline) To prevent free code from being proprietarized in this manner in the future, Stallman invented the GPL.”

Nice to see how (as the comment author puts it) ‘Richard was right.’

The rest of the comment ( & story) is equally worth a read. Long live the GPL & Java! & so many others :)

JDK 6u10 early access features Nimbus Look ‘n Feel

Monday, April 7th, 2008

Although I found the Ocean look to be a major improvement of the Metal look and feel (L&F), Nimbus seems a big step forward once again. And not an unwelcome one at that.

It does deserve to be said that a project with a Swing frontend I’ve been working on for a client for sometime now has been running Ocean as default look for a while now. It’s primary user group are users with no technical expertise whatsoever, and after I disabled the native theme for a while to do some Vista testing and forgot to re-enable it later for the next release build, they’ve specifically asked me to switch back to Ocean afterwards when I had ‘corrected’ the issue. I still need to ask whether that was due to use of colors, font, dpi or messy Swing native theming.

Which brings up a question that crossed my mind a few times; how many or few colors can/should a business app gui use in it’s UI, before it gets that screaming feeling or transforms to the written equivalent of The Box Factory?

Since I try to adhere to splitting the layers and reusing components (sort of), the use of color seems pretty important when designing editors and viewers of different sorts. I suppose it should all be abstracted out to the presentation model right :-)

Logging System.out and System.err to a file

Wednesday, April 2nd, 2008

For future self-reference, found a nice blog post on the topic :

Nick Stephen’s blog: Java: Redirecting System.out and System.err to a rolling log file

Dumping a MySQL database from Java

Saturday, March 29th, 2008

Either you call the mysqldump binary from java :

import java.io.File;
import java.io.InputStream;
import java.io.PrintStream;

public class MySQLDumper {

private static String ip="localhost";
private static String port="3306";
private static String database="dbname";
private static String user="root";
private static String pass="a";
private static String path="E:\\Users
dbname.sql";

public static void export(){
String dumpCommand = "mysqldump " + database + " -h " + ip + " -u " + user +" -p" + pass;
Runtime rt = Runtime.getRuntime();
File test=new File(path);
PrintStream ps;

try{
Process child = rt.exec(dumpCommand);
ps=new PrintStream(test);
InputStream in = child.getInputStream();
int ch;
while ((ch = in.read()) != -1) {
ps.write(ch);
System.out.write(ch); //to view it by console
}

InputStream err = child.getErrorStream();
while ((ch = err.read()) != -1) {
System.out.write(ch);
}
}catch(Exception exc) {
exc.printStackTrace();
}
}

public static void main(String args[]){
export();
}
}

or you use a java implementation of the tool itself:
MySQL Dump in Java

Which actually leads to the following code :

/**
* Copyright (c) 2007, Wave2 Limited
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Wave2 Limited nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.binarystor.mysql;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import org.kohsuke.args4j.*;
import static org.kohsuke.args4j.ExampleMode.ALL;

/**
 *
 * @author Alan Snelson
 */
public class MySQLDump {

    //Command Line Arguments
    @Option(name="--help")
    private boolean help;
    @Option(name="-h",usage="MySQL Server Hostname")
    private String hostname;
    @Option(name="-u",usage="MySQL Username")
    private String username;
    @Option(name="-p",usage="MySQL Password")
    private String password;
    // receives other command line parameters than options
    @Argument
    private List arguments = new ArrayList();

    private static String version = "0.1";
    private String database = null;
    private Connection conn = null;
    private DatabaseMetaData databaseMetaData;
    private String databaseProductVersion = null;
    private String mysqlVersion = null;

    /**
    * Default contructor for MySQLDump.
    */
    public MySQLDump() {

    }

    /**
    * Create a new instance of MySQLDump using default database.
    *
    * @param  host      MySQL Server Hostname
    * @param  username  MySQL Username
    * @param  password  MySQL Password
    */
    public MySQLDump(String host, String username, String password) throws SQLException {
        try{
            connect(host, username, password, "mysql");
        }
        catch (SQLException se){
            throw se;
        }

    }

    /**
    * Create a new instance of MySQLDump using supplied database.
    *
    * @param  host      MySQL Server Hostname
    * @param  username  MySQL Username
    * @param  password  MySQL Password
    * @param  db        Default database
    */
    public MySQLDump(String host, String username, String password, String db) throws SQLException{
        try{
            connect(host, username, password, db);
        }
        catch (SQLException se){
            throw se;
        }
    }

    /**
    * Connect to MySQL server
    *
    * @param  host      MySQL Server Hostname
    * @param  username  MySQL Username
    * @param  password  MySQL Password
    * @param  db        Default database
    */
    public void connect(String host, String username, String password, String db) throws SQLException{
        try
        {
            Class.forName ("com.mysql.jdbc.Driver").newInstance ();
            conn = DriverManager.getConnection ("jdbc:mysql://" + host + "/" + db, username, password);
            databaseMetaData = conn.getMetaData();
            databaseProductVersion = databaseMetaData.getDatabaseProductVersion();
            hostname = host;
            database = db;
            System.out.println ("Database connection established");
        }
        catch (SQLException se){
            throw se;
        }
        catch (Exception e)
        {
            System.err.println ("Cannot connect to database server");
        }
    }

    public File dumpAllDatabases(){
        return null;
    }

    public String dumpCreateDatabase(String database) {
        String createDatabase = null;
        try{
            Statement s = conn.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
            s.executeQuery ("SHOW CREATE DATABASE " + database);
            ResultSet rs = s.getResultSet ();
            while (rs.next ())
            {
                createDatabase = rs.getString("Create Database") + ";";
            }
        } catch (SQLException e) {

        }
        return createDatabase;
    } 

    public File dumpDatabase(String database){
        return null;
    }

    public File dumpAllTables(String database){
        return null;
    }

    public String dumpCreateTable(BufferedWriter out, String table) {
        String createTable = null;
        try{
            out.write("\n\n--\n-- Table structure for table `" + table + "`\n--\n\n");
            Statement s = conn.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
            s.executeQuery ("SHOW CREATE TABLE " + table);
            ResultSet rs = s.getResultSet ();
            while (rs.next ())
            {
                createTable = rs.getString("Create Table") + ";";
            }
        } catch (SQLException e) {

        } catch(IOException e){
            System.err.println (e.getMessage());
        }
        return createTable;
    }

    public void dumpTable(BufferedWriter out, String table){
         try{
            Statement s = conn.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
            out.write("\n\n--\n-- Dumping data for table `" + table + "`\n--\n\n");
            s.executeQuery ("SELECT /*!40001 SQL_NO_CACHE */ * FROM " + table);
            ResultSet rs = s.getResultSet ();
            ResultSetMetaData rsMetaData = rs.getMetaData();
            int columnCount = rsMetaData.getColumnCount();
            String prefix = new String("INSERT INTO " + table + " (");
            for (int i = 1; i <= columnCount; i++) {
                if (i == columnCount){
                    prefix += rsMetaData.getColumnName(i) + ") VALUES(";
                }else{
                    prefix += rsMetaData.getColumnName(i) + ",";
                }
            }
            String postfix = new String();
            int count = 0;
            while (rs.next ())
            {

                postfix = "";
                for (int i = 1; i <= columnCount; i++) {
                    if (i == columnCount){
                        System.err.println(rs.getMetaData().getColumnClassName(i));
                        postfix += "'" + rs.getString(i) + "');\n";
                    }else{

                        System.err.println(rs.getMetaData().getColumnTypeName(i));
                        if (rs.getMetaData().getColumnTypeName(i).equalsIgnoreCase("LONGBLOB")){
                            try{
                                postfix += "'" + escapeString(rs.getBytes(i)).toString() + "',";
                            }catch (Exception e){
                                postfix += "NULL,";
                            }
                        }else{
                            try{
                                postfix += "'" + rs.getString(i).replaceAll("\n","\\\\n").replaceAll("'","\\\\'") + "',";
                            }catch (Exception e){
                                postfix += "NULL,";
                            }
                    }   }
                }
                out.write(prefix + postfix + "\n");
                ++count;
            }
            rs.close ();
            s.close();
        }catch(IOException e){
            System.err.println (e.getMessage());
        }catch(SQLException e){
            System.err.println (e.getMessage());
        }
    }

    public File dumpAllViews(String database) {
        return null;
    }

    public String dumpCreateView(String view) {
        return null;
    }

    public File dumpView(String view) {
        return null;
    }

    /**
    * Escape string ready for insert via mysql client
    *
    * @param  bIn       String to be escaped passed in as byte array
    * @return bOut      MySQL compatible insert ready ByteArrayOutputStream
    */
    private ByteArrayOutputStream escapeString(byte[] bIn){
        int numBytes = bIn.length;
        ByteArrayOutputStream bOut = new ByteArrayOutputStream(numBytes+ 2);
        for (int i = 0; i < numBytes; ++i) {
            byte b = bIn[i];

            switch (b) {
            case 0: /* Must be escaped for 'mysql' */
                    bOut.write('\\');
                    bOut.write('0');
                    break;

            case '\n': /* Must be escaped for logs */
                    bOut.write('\\');
                    bOut.write('n');
                    break;

            case '\r':
                    bOut.write('\\');
                    bOut.write('r');
                    break;

            case '\\':
                    bOut.write('\\');
                    bOut.write('\\');

                    break;

            case '\'':
                    bOut.write('\\');
                    bOut.write('\'');

                    break;

            case '"': /* Better safe than sorry */
                    bOut.write('\\');
                    bOut.write('"');
                    break;

            case '\032': /* This gives problems on Win32 */
                    bOut.write('\\');
                    bOut.write('Z');
                    break;

            default:
                    bOut.write(b);
            }
        }
        return bOut;
    }

    private String getHeader(){
        //return Dump Header
        return "-- BinaryStor MySQL Dump " + version + "\n--\n-- Host: " + hostname + "    " + "Database: " + database + "\n-- ------------------------------------------------------\n-- Server Version: " + databaseProductVersion + "\n--";
    }

    /**
    * Main entry point for MySQLDump when run from command line
    *
    * @param  args  Command line arguments
    */
    public static void main (String[] args) throws IOException {
        new MySQLDump().doMain(args);
    }

    /**
    * Parse command line arguments and run MySQLDump
    *
    * @param  args  Command line arguments
    */
    public void doMain(String[] args) throws IOException {

        String usage = "Usage: java -jar MySQLDump.jar [OPTIONS] database [tables]\nOR     java -jar MySQLDump.jar [OPTIONS] --databases [OPTIONS] DB1 [DB2 DB3...]\nOR     java -jar MySQLDump.jar [OPTIONS] --all-databases [OPTIONS]\nFor more options, use java -jar MySQLDump.jar --help";
        CmdLineParser parser = new CmdLineParser(this);

        // if you have a wider console, you could increase the value;
        // here 80 is also the default
        parser.setUsageWidth(80);

        try {
            // parse the arguments.
            parser.parseArgument(args);

            if (help) {
                throw new CmdLineException("Print Help");
            }

            // after parsing arguments, you should check
            // if enough arguments are given.
            if( arguments.isEmpty() )
                throw new CmdLineException("No argument is given");

        } catch( CmdLineException e ) {
            if (e.getMessage().equalsIgnoreCase("Print Help")){
                System.err.println("MySQLDump.java Ver " + version + "\nThis software comes with ABSOLUTELY NO WARRANTY. This is free software,\nand you are welcome to modify and redistribute it under the BSD license" + "\n\n" + usage);
                return;
            }
            // if there's a problem in the command line,
            // you'll get this exception. this will report
            // an error message.
            System.err.println(e.getMessage());
            // print usage.
            System.err.println(usage);
            return;
        }

        //Do we have a hostname? if not use localhost as default
        if (hostname == null){
            hostname = "localhost";
        }
        //First argument here should be database
        database = arguments.remove(0);

        try{
            //Create temporary file to hold SQL output.
            File temp = File.createTempFile(database, ".sql");
            BufferedWriter out = new BufferedWriter(new FileWriter(temp));
            this.connect(hostname, username, password, database);
            out.write(getHeader());
            for( String arg : arguments )
                System.out.println(arg);
            out.write(dumpCreateTable(out,"blobdump"));
            this.dumpTable(out,"blobdump");
            out.close();
            this.cleanup();
        }
        catch (SQLException se){
            System.err.println (se.getMessage());
        }
    }

    public int cleanup(){
        try
        {
            conn.close ();
            System.out.println ("Database connection terminated");
        }
        catch (Exception e) { /* ignore close errors */ }
        return 1;
    }

}