Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

2013-07-31

How to use Gradle to generate Eclipse files with relative paths to libraries

First, apply the Gradle Eclipse plug-in to your build.gradle file:

apply plugin: 'java'
apply plugin: 'eclipse'

You can now execute the following command to generate the Eclipse configuration files .project and .classpath:

$ gradle eclipse

You can now import and existing project into Eclipse, and enjoy all the correct configurations!

However, in the current Gradle version (1.6), the generated library paths are absolute, for example:

C:/Users/Miguel/.gradle/caches/artifacts-24/filestore/
junit/junit/4.11/source/
28e0ad201304e4a4abf999ca0570b7cffc352c3c/junit-4.11-sources.jar

This leads to problems because if you commit these files in source code control, your specific user settings will be imposed on other developers.

One way to avoid this is to use an Eclipse Classpath Variable and customize the Eclipse plug-in output.

eclipse {
    // find gradle cache location
    def gradleCache = null
    for (o in configurations.compile) {
        if (o.toString().indexOf(".gradle") != -1) {
            final def token = "filestore"
            def s = o.toString()
            def idx = s.indexOf(token)
            if (idx != -1) {
                gradleCache = new File(s.substring(0, idx + token.length()))
                break
            }
        }
    }
    assert gradleCache && gradleCache.exists()
    println "GRADLE_CACHE: " + gradleCache

    // replace absolute paths with classpath variable GRADLE_CACHE
    pathVariables 'GRADLE_CACHE': gradleCache

    // make sure GRADLE_CACHE is defined in 
    // Eclipse, Preferences, Java, Build Path, Classpath Variables

}

Note: an alternative solution could use Eclipse workspace Path variables (referred using the ${...} notation) but without DSL support like the pathVariables statement above.

2013-05-23

Common MySQL / JDBC programming error that causes unexpected syntax errors

What is wrong with this code?

...
    String sql = "INSERT INTO PRODUCT (CODE, DESCRIPTION) VALUES(?,?)";
    PreparedStatement pstmt = connection.prepareStatement(sql);
        
    pstmt.setString(1, "A1");
    pstmt.setString(2, "Soccer ball");
        
    pstmt.executeUpdate(sql);
...

On execution, the execute method returns a com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException.

Why is that? The syntax looks OK...

It's tricky, but since the statement is prepared in advance, the method to call is pstmt.executeUpdate() without parameters.
If the SQL query is provided, the compiler accepts the code, but the '?' produce syntax errors.

PreparedStatement is preferred over Statement because it can give better performance and prevent many SQL Injection attacks.

The correct code is:

...
    String sql = "INSERT INTO PRODUCT (CODE, DESCRIPTION) VALUES(?,?)";
    PreparedStatement pstmt = connection.prepareStatement(sql);
        
    pstmt.setString(1, "A1");
    pstmt.setString(2, "Soccer ball");
        
    pstmt.executeUpdate();
...


Credits: Mark Matthews

2013-04-16

How to copy all files in classpath to a directory using Ant?

Try something like the following target:

...

    <target name=copy-deps">
        <copy todir="." flatten="true">
            <path refid="my-classpath"/>
        </copy>
    </target>

...

To execute (assuming that my-classpath is defined, of course):

ant copy-deps

2013-03-06

Eclipse power shortcuts

Eclipse is a Java Integrated Development Environment (IDE) that has many problems, in my view, but also many good things.

Here are a few time-savers:

Type:
sysout CTRL+space

and Eclipse completes to:
System.out.println()


Type:
throw new NPE CTRL+space

and Eclipse presents a list of Exception classes whose capital letters start with N, P, and E.
In this case, we want to complete to:
throw new NullPointerException()

Again:
throw new IArE CTRL+space

and complete to:
throw new IllegalArgumentException()


Nice! :)

2013-02-28

How to write the end-of-file character in a Java String?

Use the \u001a unicode character.

There is a character called EOF. It's also called control-Z.
If you want to include it in a string, you have to type it as "\u001a" as in:

String iHaveAnEof = "file ends here\u001a";

Credits:

Ed Staub

http://stackoverflow.com/a/7591594/129497

2012-11-30

How to install the Java Developer Kit on Windows?

The first step is to download the installation package.
The file to get is the Java Developer Kit (JDK)
http://www.oracle.com/technetwork/java/javase/downloads/index.html

The second step is to execute the installer.

To compile and execute Java programs in the console, a few environment variables must be set.

Set JAVA_HOME to the installation folder.
For example, C:\Java\jdk\1.7.0_09

Then, edit the PATH variable, to add, in the beginning:
%JAVA_HOME%\bin;

Finally, to check if everything is OK, open a new console and execute the following commands that should print the installed Java version number:
javac -version
java -version 

That's it! Happy coding!

2012-09-21

You code, you learn - flat Java files

"I don't need to keep my java files in all those boring package name folders (e.g. /net/proj/...). I'll just keep them all in a single folder then let the compiler worry about it"

The above statement is true, but you should known that the IDEs like Eclipse, Netbeans, IntelliJ, assume that the java files are stored in folders according to the package structure.

The IDEs will report errors when you try to open the project in them. And sooner or later, you or someone on your team will want to do it.

The renaming process can be eased using the Eclipse refactor-move functionality, but it will be a pain, especially if your are using version control.

I wasted 2 days to rearrange the Java files to the standard structure using Eclipse and SVN.

You code, you learn!

2012-09-20

You code, you learn - Groovy to Java

Here is one mistake you might end up doing:

"I'll code in Groovy first and then convert to Java. It should be a piece of cake!"

Be prepared for a bitter and hard to chew cake!

Groovy is very loose on typing so you'll end up doing all sorts of accidental programming errors, for instance, you can easily use methods that are not accessible on a static context. Generics are also a pain.

To convert the code you will have to do major refactoring with redesign of the class hierarchies.

I wasted 2 weeks on a project when I had to convert a 200 class application from Groovy to Java.

You code, you learn!

2012-09-17

Removing accented characters

Here are two ways to replace accented characters by their equivalents in Java:

A basic solution with probably bad performance:
public static String removeAccents(String s) {
    s = s.replaceAll("[áàâãä]","a");
    s = s.replaceAll("[éèêë]","e");
    s = s.replaceAll("[íìîï]","i");
    s = s.replaceAll("[óòôõö]","o");
    s = s.replaceAll("[úùûü]","u");
    s = s.replaceAll("ç","c");

    s = s.replaceAll("[ÁÀÂÃÄ]","A");
    s = s.replaceAll("[ÉÈÊË]","E");
    s = s.replaceAll("[ÍÌÎÏ]","I");
    s = s.replaceAll("[ÓÒÔÕÖ]","O");
    s = s.replaceAll("[ÚÙÛÜ]","U");
    s = s.replaceAll("Ç","C");

    return s;
}

Another one, with JDK support that does not appear to work properly on the Mac implementation. Test carefully first.

public static String removeAccentsAlt(String s) {
    String temp = java.text.Normalizer.normalize(s, java.text.Normalizer.Form.NFD);
    return temp.replaceAll("[^\\p{ASCII}]","");
}
credits: http://www.rgagnon.com/javadetails/java-0456.html

For comparing text, there is java.text.Collator:

Collator collator = Collator.getInstance(locale);
        collator.setStrength(Collator.PRIMARY);
        collator.setDecomposition(Collator.FULL_DECOMPOSITION);

2012-06-20

Java memory options

On a 32-bit Windows 7 machine running Oracle JDK 7, the default Java heap size is around 256M.

The JVM memory settings are the following:
-Xms        set initial Java heap size
-Xmx        set maximum Java heap size
-Xss        set java thread stack size

This means that we can change the initial and maximum heap size using:

java -Xms512M -Xmx1G MyMainClass

M stands for MegaByte and G for GigaByte.
There is also a "standard" way of defining these parameters using the JAVA_OPTS environment variable:

SET JAVA_OPTS=-Xms1G -Xmx1G

For instance, execution scripts created using gradle install will apply the options specified in JAVA_OPTS and in an application-specific variable (e.g. MY_APP_OPTS).

This in practice, does:

java %JAVA_OPTS% MyMainClass


The following Java program can query the memory using the Runtime object.

// credits: mike http://stackoverflow.com/a/7019624
public class MyMainClass {

    public static void main(String[] args) {
        Runtime rt = Runtime.getRuntime();
        long totalMem = rt.totalMemory();
        long maxMem = rt.maxMemory();
        long freeMem = rt.freeMemory();
        double megs = 1048576.0;

        System.out.println ("Total Memory: " + totalMem + 
" (" + (totalMem/megs) + " MiB)");
        System.out.println ("Max Memory:   " + maxMem +
" (" + (maxMem/megs) + " MiB)");
        System.out.println ("Free Memory:  " + freeMem + 
" (" + (freeMem/megs) + " MiB)");
    }

}

2012-05-03

Java String print tip

Are you getting confused with all the substring() indices during a debug session?
Try the following code:
System.err.println(myStr);
for (int i=0; i < myStr.length(); i++)
    System.err.print(i % 10);

You will get the following output:
my string value
012345678901234

% performs a division remainder operation, giving, in this case, always a number between 0 and 9.
And the numbers in the next line make it so much easier to see the string indices! :)

2012-04-13

Java vs Groovy on overriden method call

In Java, suppose we have the following class:

public class Do {
    public void doSomething(Object arg) {
        System.out.println("Do " + arg.toString());
    }
}

We then extend it in the following class:

public class DoDifferently extends Do {
    public void doSomething(Object arg) {
        System.out.println("Do different " + arg.toString());
    }
    public void doSomething(String arg) {
        System.out.println("Do different string " + arg.toString());
    }
}

Now let's use these classes in our program:

Do o = new Do();
o.doSomething("x");

executes the Object method.

DoDifferently o2 = new DoDifferently();
o2.doSomething("x");

executes the String method because it is more specific.

What about the following code?

Do o3 = new DoDifferently();
o3.doSomething("x");

It will execute the Object method, because Java uses the reference type to determine which method to call.

What about Groovy?

The code above is also valid in Groovy.

The String method is always executed when available, because Groovy uses the most specific method for the argument type, determined dynamically at run-time.

2012-03-05

REST in Java

Most of my work with Web Services has been with SOAP-based Web Services. However, there is an alternative, called REST.

There is Java library for RESTful Web Services, called JAX-RS.

JAX-RS RESTful principles are:
- assign everything an ID
- link things together
- use common set of methods
- allow multiple representations
- stateless communications

Classes and methods are annotated to generate REST service.
Here is an example:

@Path("/atm")
public class AtmService {

    @GET @PATH("/balance")
    @Produces("text/plain")
    public String balance(@QueryParam("card") String card,
                          @QueryParam("pin") String pin) {

        ...
    }

...

There also annotations for using HTTP POST (@POST) and specifying the data type that is consumes (@Consumes).

This example was taken from a Java ONE presentation.

2012-02-29

Groovy

I have been using Groovy for almost 2 years now, and it has been a great experience.

I have a preference for typed languages, but there is no doubt that scripting languages have enormous utility too. Groovy is very flexible in this aspect. You can program using types - in this case Groovy is just Java with some nice syntax sugar - or you can program without types - in this case Groovy is a scripting language with an incredible set of libraries: anything that runs on the Java Virtual Machine.

I read that the Groovy team is considering adding more features to allow better performance in the type-based programs. This is expected for the 2.0 release.

Even Java is becoming easier to use with the Project Coin language changes.
By the way, Groovy 1.9 will include JDK 7 support including project coin language changes and invokeDynamic to improve performance.

2012-02-24

Setting up a Java programming environment

Author of this guide: Joana

Software needed for the programming environment.

Note:
- to avoid discrepancies, please install exactly the versions mentioned here as they are the same provided in the laboratory machines
- also deactivate all auto-update options in Eclipse to keep your environment as similar as possible to the one provided in the laboratory

----------------------------------

Software:

Requirements:
- You can install the needed software in your preferred operating system, including Windows, Linux and Mac OS X.

--- --- --- ---

Most tools have a command line (shell) interface that needs to be installed in order to solve some problems along the way during our course.
In Windows XP consider installing the PowerToy "Open Command Here".
http://www.microsoft.com/windowsxp/downloads/powertoys/xppowertoys.mspx
Windows 7 already provides that feature built-in in the secondary context menu (available when holding shift and right-clicking a folder).
In Mac OX there is a similar tool called 'Go2Shell'
http://itunes.apple.com/us/app/go2shell/id445770608?mt=12

--- --- --- ---

Environment variables:
You can define system and user environment variables.
Each operating system provides this through different ways.
The main variables are:

PATH
To allow the operating system to found the binaries of the programs you want to be running in the shell (console) you need to include all the relevant paths in the system's environment variable PATH. This allows you to call just 'javac', 'java', 'ant', and 'svn' and the system will know where to find the necessary binaries.

CLASSPATH
When using Java's Development Kit (JDK) another interesting variable is the CLASSPATH. It informs the java program where to look for the needed libraries. However there are better ways to achieve this goal, namely using the Ant build files.

To further explore this topic, consider reading the article on Wikipedia:
http://en.wikipedia.org/wiki/Environment_variable

--- --- --- ---

LIST:

Java Developer Kit ~ JDK
Java Runtime Environment ~ JRE
-> follow the installation instructions on official webpage:
http://www.oracle.com/technetwork/java/index.html
http://www.oracle.com/technetwork/java/javase/index-137561.html
You must have a copy of the JRE (Java Runtime Environment) on your system to run Java applications and applets. To develop Java applications and applets, you need the JDK (Java Development Kit), which includes the JRE.

--- ---

Eclipse IDE for Java EE Developers
Tools for Java developers creating Java EE and Web applications, including a Java IDE, tools for Java EE, JPA, JSF, Mylyn and others. It requires JRE to run.
Instructions can be found here: http://wiki.eclipse.org/Eclipse/Installation

It needs to be enriched with 2 plugins:

- Eclipse Subversive - SVN Plugin that allows the integration of eclipse with SVN tools and visually navigate SVN repositories like the one where the group's projects will be hosted.
It consists in two parts: Subversive plug-in and Subversive SVN Connectors. Both parts are required in order to work with Subversive, so you need to install Subversive plug-in and pure Java SVNKit connector.
http://www.eclipse.org/subversive/downloads.php#indigo_stable

- Google Plugin for Eclipse (GPE) adds functionality to Eclipse for creating and developing Google Web Toolkit (GWT) applications. GWT is downloaded with the GPE. It will assist the developers in the building of browser-based applications (user interface) for the project. GWT compiles your Java source code into optimized, stand-alone JavaScript files that automatically run on all major browsers, as well as mobile browsers for Android and the iPhone. It will also be used by the distributed systems course students with the JBoss Application Server.

A third plugin can also be useful:
- Log Watcher adds a view to Eclipse that allows log files to be monitored for changes, similar to the Unix tail utility.
http://graysky.sourceforge.net/

--- ---

- GWT browser plugin - GWT Development Mode needs a browser plugin to operate. Please install the appropriate one for your browser. It integrates with a variety of browsers and lets you debug GWT code from within the Eclipse IDE.

--- ---

- Apache Ant 1.8.2 - Ant is a Java library and command-line build tool similar in purpose to Make. It helps with the typical tasks of software development: compile, build, deploy, install and clean. It can be run from inside the Eclipse IDE (in the proper View) but you also need to run it in the command line.

--- ---

- Apache Subversion 1.7.2 - Subversion is a free/open source version control system (VCS). It manages files and directories, and the changes made to them, over time. This allows you to recover older versions of your data or examine the history of how your data changed and who changed it.
Eclipse Subversive plugin (Eclipse section) provides a graphical interface. You need a client that can run in the shell. There are other standalone graphical interfaces like TortoiseSVN, SVNx, etc. In any case, you need a working command line version.

In this page you can find several clients binary packages:
http://subversion.apache.org/packages.html
We do not need you to install a server because the project will be hosted in the sigma server machine and will be accessed through the SVN+SSH protocol.

----------------------------------





2011-11-03

Groovy and Gradle

The next generation of Java and Ant (+Maven): Groovy and Gradle.



There are still some improvements required but these tools represent major steps forward in programmer productivity.

2011-10-28

Java list tricks

Most of the times the simplest way to traverse a list in Java is to use an Iterator.

If your List is a LinkedList, then you can also use a descendingIterator.

For more list-specific methods, there is ListIterator, that can move forward and backward among other things.

2011-06-07

Energy-efficient programming

A University of Washington project sees a role for programmers to reduce the energy appetite of the ones and zeroes in the code itself. Researchers have created a system, called EnerJ, that reduces energy consumption in simulations by up to 50 percent, and has the potential to cut energy by as much as 90 percent.

Source: Code green: Energy-efficient programming to curb computers’ power use

2010-10-11

Groovy regular expression operators

The Java regular expression (regex) typical invocation sequence is:

     Pattern p = Pattern.compile("a*b");
     Matcher m = p.matcher("aaaaab");
     boolean b = m.matches();

A matches method is defined by the Pattern class as a convenience for when a regular expression is used just once. This method compiles an expression and matches an input sequence against it in a single invocation. The statement

    boolean b = Pattern.matches("a*b", "aaaaab");

Groovy is a promising new language for the Java platform that includes the following regular expressions operators that greatly simplify the use of java.util.regex:

~ creates a Pattern from String

=~ creates a Matcher, and in a boolean context, it is "true" if it has at least one match, "false" otherwise.

==~ tests if String matches the pattern

2010-04-30

Java regular expressions testbed

Regular expressions are one of the most useful programming tools, particularly for text processing. Java has a nice implementation, stored in the java.util.regex package.

The following page by David Matuszek contains a Java Applet to test regular expressions. I use it a lot and recommend it!

http://www.cis.upenn.edu/~matuszek/General/RegexTester/regex-tester.html

Have fun!