Sunday, October 27, 2013

How Java Helped Oracle Team USA Win the America's Cup

To know how Oracle Team USA relies on a wireless Java system for real-time data to improve performance on the racecourse. Read on Java Magazine.




Oracle Team USA wins America's Cup - CNN Newsroom Sep 26, 2013

Saturday, October 26, 2013

Check running Java and JavaFX version using Java code at run-time

To check the version of running Java and JavaFX in your Java code, you can get property of "java.version" and "javafx.runtime.version" by calling System.getProperty() method.

System.getProperty("java.version");
System.getProperty("javafx.runtime.version");

Example in Java Application:
Example in Java Application

package java_version;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class Java_version {

    public static void main(String[] args) {
        
        System.out.println("java.version: " + System.getProperty("java.version"));
        System.out.println("javafx.runtime.version: " + System.getProperty("javafx.runtime.version"));
    }
    
}


Example in JavaFX Application:
Example in JavaFX Application

package javafx_version;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_version extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        
        System.out.println("java.version: " + System.getProperty("java.version"));
        System.out.println("javafx.runtime.version: " + System.getProperty("javafx.runtime.version"));
        
        Button btn = new Button();
        btn.setText("Say 'Hello World'");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            
            @Override
            public void handle(ActionEvent event) {
                System.out.println("Hello World!");
            }
        });
        
        StackPane root = new StackPane();
        root.getChildren().add(btn);
        
        Scene scene = new Scene(root, 300, 250);
        
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

Saturday, October 19, 2013

Decompress files from .zip using java.util.zip

Example to decompress multi files from .zip using java.util.zip, with JavaFX UI.

Decompress files from .zip using java.util.zip
Decompress files from .zip using java.util.zip

package javafx_zip;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_Zip extends Application {

    File fileSrc;
    private static final int bufferSize = 8192;

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Hello World!");

        final Label labelFile = new Label();

        Button btn = new Button();
        btn.setText("Open FileChooser'");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {

                FileChooser fileChooser = new FileChooser();

                //Set extension filter
                FileChooser.ExtensionFilter extFilter =
                        new FileChooser.ExtensionFilter("Zip files (*.zip)", "*.zip");
                fileChooser.getExtensionFilters().add(extFilter);
                File fileSrc = fileChooser.showOpenDialog(null);

                String source = fileSrc.getPath();
                String targetUnZipPath = fileSrc.getParent();

                try {
                    //Compress file
                    FileInputStream fileInputStream =
                            new FileInputStream(source);
                    BufferedInputStream bufferedInputStream =
                            new BufferedInputStream(fileInputStream);
                    ZipInputStream zipInputStream =
                            new ZipInputStream(bufferedInputStream);

                    ZipEntry zipEntry;
                    
                    String unzippedMsg = "";

                    while ((zipEntry = zipInputStream.getNextEntry()) != null) {
                        try {
                            byte[] buffer = new byte[bufferSize];
                            String unzippedFile = targetUnZipPath + "/" + zipEntry.getName();
                            FileOutputStream fileOutputStream = 
                                    new FileOutputStream(unzippedFile);
                            int size;
                            while ((size = zipInputStream.read(buffer)) != -1) {
                                fileOutputStream.write(buffer, 0, size);
                            }
                            fileOutputStream.flush();
                            fileOutputStream.close();
                            unzippedMsg += unzippedFile + "\n";
                        } catch (Exception ex) {
                        }
                    }
                    zipInputStream.close();
                    labelFile.setText("Unzipped files: \n" + unzippedMsg);
                } catch (IOException ex) {
                    Logger.getLogger(JavaFX_Zip.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });

        VBox vBox = new VBox();
        vBox.getChildren().addAll(btn, labelFile);

        StackPane root = new StackPane();
        root.getChildren().add(vBox);
        primaryStage.setScene(new Scene(root, 300, 250));
        primaryStage.show();
    }

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

Thursday, October 17, 2013

JDK 8 in NetBeans IDE 7.4

This screencast demonstrates how to set up NetBeans IDE 7.4 to use JDK 8, together with how to use JDK 8 profile support and lambda expressions.

Java SE 7 Update 45 and Java SE Embedded 7 Update 45 released

Java SE 7 Update 45 released: visit Java SE Downloads page (Java Platform (JDK) 7u45/JDK 7u45 & NetBeans 7.4)

Java SE Embedded 7 Update 45 released: visit Oracle Java SE Embedded Download page

NetBeans IDE 7.4

NetBeans IDE 7.4 extends the advanced HTML5 development support introduced in NetBeans IDE 7.3 to Java EE and PHP application development, while offering new support for hybrid HTML5 application development on the Android and iOS platforms. In addition, this release provides support for working with preview versions of JDK 8, and includes continued enhancements to JavaFX, C/C++ and more.

NetBeans IDE 7.4 is available in English, Brazilian Portuguese, Japanese, Russian, and Simplified Chinese.

Download NetBeans IDE 7.4

Wednesday, October 16, 2013

Compress multi files to .zip

Compress multi files to .zip
Compress multi files to .zip


package javafx_zip;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_Zip extends Application {

    File fileSrc;
    private static final int bufferSize = 8192;

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Hello World!");

        final Label labelFile = new Label();

        Button btn = new Button();
        btn.setText("Open FileChooser'");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {

                FileChooser fileChooser = new FileChooser();

                //Set extension filter
                FileChooser.ExtensionFilter extFilter =
                        new FileChooser.ExtensionFilter("files (*.*)", "*.*");
                fileChooser.getExtensionFilters().add(extFilter);
                List<File> fileSrcList = fileChooser.showOpenMultipleDialog(null);

                String targetZipFile = fileSrcList.get(0).getParent() + "/compressed.zip";

                try {
                    //Compress file
                    ZipOutputStream zipOutputStream;

                    FileOutputStream fileOutputStream =
                            new FileOutputStream(targetZipFile);
                    zipOutputStream = new ZipOutputStream(fileOutputStream);

                    for (File f : fileSrcList) {
                        String source = f.getPath();
                        String entryName = f.getName();
                        
                        ZipEntry zipEntry = new ZipEntry(entryName);
                        zipOutputStream.putNextEntry(zipEntry);

                        byte[] buffer = new byte[bufferSize];
                        try (FileInputStream fileInputStream = new FileInputStream(source)) {
                            int numberOfByte;

                            while ((numberOfByte = fileInputStream.read(buffer, 0, bufferSize))
                                    != -1) {
                                zipOutputStream.write(buffer, 0, numberOfByte);
                            }
                        }
                    }
                    zipOutputStream.close();
                    labelFile.setText("Compressed file saved as: " + targetZipFile);
                } catch (IOException ex) {
                    Logger.getLogger(JavaFX_Zip.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });

        VBox vBox = new VBox();
        vBox.getChildren().addAll(labelFile, btn);

        StackPane root = new StackPane();
        root.getChildren().add(vBox);
        primaryStage.setScene(new Scene(root, 300, 250));
        primaryStage.show();
    }

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


Monday, October 14, 2013

Decompress file (.gz) using java.util.zip, with JavaFX interface

Example to decompress .gz archives using Package java.util.zip, JavaFX File Chooser.

package javafx_zip;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_Zip extends Application {

    File fileSrc;
    private static final int bufferSize = 8192;

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Hello World!");

        final Label labelFile = new Label();

        Button btn = new Button();
        btn.setText("Open FileChooser'");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {

                FileChooser fileChooser = new FileChooser();

                //Set extension filter
                FileChooser.ExtensionFilter extFilter = 
                        new FileChooser.ExtensionFilter("gz files (*.gz)", "*.gz");
                fileChooser.getExtensionFilters().add(extFilter);

                //Show open file dialog
                fileSrc = fileChooser.showOpenDialog(null);

                String source = fileSrc.getPath();
                //remove ".gz" from the path
                String targetUnGzFile = source.substring(0, source.length()-3);
                
                try {
                    //UnCompress file
                    
                    GZIPInputStream gZIPInputStream;

                    FileInputStream fileInputStream = 
                            new FileInputStream(source);
                    gZIPInputStream = new GZIPInputStream(fileInputStream);
                    
                    byte[] buffer = new byte[bufferSize];
                    try (FileOutputStream fileOutputStream = new FileOutputStream(targetUnGzFile)) {
                        int numberOfByte;
                        
                        while((numberOfByte = gZIPInputStream.read(buffer, 0, bufferSize)) 
                                != -1){
                            fileOutputStream.write(buffer, 0, numberOfByte);
                        }
                        
                        fileOutputStream.close();
                    }
                    
                    labelFile.setText("UnCompressed file saved as: " + targetUnGzFile);
                    
                } catch (IOException ex) {
                    Logger.getLogger(JavaFX_Zip.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });

        VBox vBox = new VBox();
        vBox.getChildren().addAll(labelFile, btn);

        StackPane root = new StackPane();
        root.getChildren().add(vBox);
        primaryStage.setScene(new Scene(root, 300, 250));
        primaryStage.show();
    }

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


Decompress file (.gz) using java.util.zip, with JavaFX interface
Decompress file (.gz) using java.util.zip, with JavaFX interface


Related: Compress file (.gz) using java.util.zip, with JavaFX interface

Sunday, October 13, 2013

Compress file (.gz) using java.util.zip, with JavaFX interface

The Package java.util.zip provides classes for reading and writing the standard ZIP and GZIP file formats. This example demonstrate how to open file with JavaFX FileChooser, and compress to .gz file with java.util.zip.GZIPOutputStream.

package javafx_zip;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPOutputStream;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_Zip extends Application {

    File fileSrc;
    private static final int bufferSize = 8192;

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Hello World!");

        final Label labelFile = new Label();

        Button btn = new Button();
        btn.setText("Open FileChooser'");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {

                FileChooser fileChooser = new FileChooser();

                //Set extension filter
                FileChooser.ExtensionFilter extFilter = 
                        new FileChooser.ExtensionFilter("files (*.*)", "*.*");
                fileChooser.getExtensionFilters().add(extFilter);

                //Show open file dialog
                fileSrc = fileChooser.showOpenDialog(null);

                String source = fileSrc.getPath();
                String targetZipFile = source + ".gz";
                
                try {
                    //Compress file
                    
                    GZIPOutputStream gZIPOutputStream;

                    FileOutputStream fileOutputStream = 
                            new FileOutputStream(targetZipFile);
                    gZIPOutputStream = new GZIPOutputStream(fileOutputStream);
                    
                    byte[] buffer = new byte[bufferSize];
                    try (FileInputStream fileInputStream = new FileInputStream(source)) {
                        int numberOfByte;
                        
                        while((numberOfByte = fileInputStream.read(buffer, 0, bufferSize)) 
                                != -1){
                            gZIPOutputStream.write(buffer, 0, numberOfByte);
                        }
                    }
                    gZIPOutputStream.close();
                    
                    labelFile.setText("Compressed file saved as: " + targetZipFile);
                    
                } catch (IOException ex) {
                    Logger.getLogger(JavaFX_Zip.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
        });

        VBox vBox = new VBox();
        vBox.getChildren().addAll(labelFile, btn);

        StackPane root = new StackPane();
        root.getChildren().add(vBox);
        primaryStage.setScene(new Scene(root, 300, 250));
        primaryStage.show();
    }

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


Compress file using java.util.zip, with JavaFX interface
Compress file using java.util.zip, with JavaFX interface


Related: Decompress file (.gz) using java.util.zip, with JavaFX interface

Thursday, October 10, 2013

Intro to JavaFX on Raspberry Pi

Product Manager Bruno Borges explains how to use JavaFX with the Raspberry Pi. This presentation was given during the Java Embedded challenge at JavaOne 2013.

Part I


Part II


Tuesday, October 8, 2013

Prevent ArrayIndexOutOfBoundsException with try/catch

Example to to use a try/catch to prevent ArrayIndexOutOfBoundsException:

package java_testarray;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class Java_testArray {

    public static void main(String[] args) {
        int[] intArray = {1, 2, 3, 4, 5};
        int ans;

        //ans = intArray[-1]; //java.lang.ArrayIndexOutOfBoundsException
        //ans = intArray[5];  //java.lang.ArrayIndexOutOfBoundsException

        for (int i = -2; i < intArray.length + 2; i++) {
            try {
                ans = intArray[i];
            } catch (ArrayIndexOutOfBoundsException e) {
                ans = 0;
            }
            System.out.println(i + " : " + ans);
        }

    }
}


Prevent ArrayIndexOutOfBoundsException with try/catch
Prevent ArrayIndexOutOfBoundsException with try/catch

Monday, October 7, 2013

Store and retrieve preference with java.util.prefs package

The java.util.prefs package provides a way for applications to store and retrieve user and system preference and configuration data. The data is stored persistently in an implementation-dependent backing store. ~ reference: Core Java™ Preferences API

Simple example using Preferences:

package javapreferences;

import java.util.prefs.Preferences;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaPreferences {
    
    static final String KeyWeb = "KEY_WEB";
    static final String KeyInt = "KEY_INT";
    static final String KeyBoolean = "KEY_BOOLEAN";

    public static void main(String[] args) {
        Preferences preferences = Preferences.userRoot().node("java-buddy");
        
        String prefWeb = preferences.get(KeyWeb, "");
        int prefInt = preferences.getInt(KeyInt, 0);
        boolean prefBoolean = preferences.getBoolean(KeyBoolean, false);
        
        System.out.println("Stored KEY_WEB: " + prefWeb);
        System.out.println("Stored KEY_INT: " + prefInt);
        System.out.println("Stored KEY_BOOLEAN: " + prefBoolean);
        
        System.out.println("Save something to Preferences");
        preferences.put(KeyWeb, "http://java-buddy.blogspot.com/");
        preferences.putInt(KeyInt, 1234567890);
        preferences.putBoolean(KeyBoolean, true);
    }
}


Simple example using Preferences
Simple example using Preferences

Get system properties with System.getProperties()

The getProperties() method of java.lang.System class return a Properties object. With this Properties object, we can get all the keys in this property list by calling its propertyNames() method. Then gets the system property indicated by the specified key by calling its System.getProperty(String key)/or getProperty(String key) method of the Properties object.

Get system properties with System.getProperties()
Get system properties with System.getProperties()

package java_systemproperties;

import java.util.Enumeration;
import java.util.Properties;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class Java_SystemProperties {

    public static void main(String[] args) {
        Properties properties = System.getProperties();
        System.out.println(properties.toString());
        System.out.println("\n");
        
        Enumeration<String> prop = 
                (Enumeration<String>) properties.propertyNames();
        
        while(prop.hasMoreElements()){
            String propName = prop.nextElement();
            System.out.println(
                    propName + " : " +
                    System.getProperty(propName));
        }
    }
}


Related: Get info of running jvm, os and cpu - tested on Windows 10

Sunday, October 6, 2013

15 Sorting Algorithms in 6 Minutes

15 Sorting Algorithms in 6 Minutes

Visualization and "audibilization" of 15 Sorting Algorithms in 6 Minutes. Sorts random shuffles of integers, with both speed and the number of items adapted to each algorithm's complexity.

The algorithms are: selection sort, insertion sort, quick sort, merge sort, heap sort, radix sort (LSD), radix sort (MSD), std::sort (intro sort), std::stable_sort (adaptive merge sort), shell sort, bubble sort, cocktail shaker sort, gnome sort, bitonic sort and bogo sort (30 seconds of it).

More information on the "Sound of Sorting" at http://panthema.net/2013/sound-of-sorting

Wednesday, October 2, 2013

Access List elements with Iterator and short form of for-loop

Example to access List elements with Iterator and short form of for-loop
package java_list;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class Java_List {

    public static void main(String[] args) {

        //Convert from Array of String to List of String
        List<String> list = 
                Arrays.asList("One", "Two", "Three", "Four", "Five");
        
        System.out.println("Access List using Iterator");
        Iterator iterator = list.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
        System.out.println();
        System.out.println("Access List using Short form of for-loop");
        for(String s: list){
            System.out.println(s);
        }
    }
}


Access List elements with Iterator and short form of for-loop
Access List elements with Iterator and short form of for-loop


Converting between List and Array

Example to convert between List and Array:

Converting between List and Array
Converting between List and Array


package java_list;

import java.util.Arrays;
import java.util.List;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class Java_List {

    public static void main(String[] args) {

        String[] stringArrayOrg = {
            "One", "Two", "Three", "Four", "Five"
        };
        
        //Convert from Array of String to List of String
        List<String> stringList = Arrays.asList(stringArrayOrg);
        
        //Convert from List of String to Array of String
        String[] stringArray = (String[])stringList.toArray();
        
        System.out.println("stringList (List of String):");
        for(int i=0; i<stringList.size(); i++){
            System.out.println(stringList.get(i));
        }
        System.out.println();
        
        System.out.println("stringArray (Array of String):");
        for(int i=0; i<stringArray.length; i++){
            System.out.println(stringArray[i]);
        }
        System.out.println();
        
    }
}


Tuesday, October 1, 2013

Example of inserting data of different type to List

package java_list;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class Java_List {

    public static void main(String[] args) {
        
        //List with type specified
        List<String> list1 = new ArrayList<String>();
        list1.add("ABC");
        //list1.add(123);
        //list1.add(12345.678);
        //list1.add(new Date());
        /* compile time error:
         * - no suitable method found for add(int)
         * - no suitable method found for add(double)
         * - no suitable method found for add(Date)
         */
        
        //List without type specified
        List list2 = new ArrayList();
        list2.add("ABC");
        list2.add(123);
        list2.add(12345.678);
        list2.add(new Date());
        for(int i = 0; i < list2.size(); i++){
            System.out.println(
                    list2.get(i).getClass().getName() + " : " +
                    list2.get(i));
        }
        
        //List without type specified
        //Returns a dynamically typesafe view with Collections.checkedList()
        List list3 = new ArrayList();
        list3 = Collections.checkedList(list3, String.class);
        list3.add("ABC");
        //list3.add(123);
        //list3.add(12345.678);
        //list3.add(new Date());
        /* runtime error:
         * java.lang.ClassCastException: Attempt to insert class 
         * java.lang.Integer/Double/Date element into collection with element 
         * type class java.lang.String
         */
        
    }
}



JavaOne Community Highlights 9-26-2013


JavaOne Community Highlights 9-26-2013
Java Community Keynote Highlights including talks from Stephen Chin, Java Technology Ambassador and JavaOne Content Chair, Donald Smith, Senior Director of Java Product Management, and Henrik Stahl, Vice President of Java Product Management.