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

Thursday, June 16, 2016

Read csv, run in background thread and update JavaFX TableView dynamically


It's modified version of last example "Read csv file, display in JavaFX TableView", with the job run in background thread. I also add dummy delay to simulate long time operation in background thread.


JavaFXCSVTableView.java
package javafxcsvtableview;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

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

    public class Record {
        //Assume each record have 6 elements, all String

        private SimpleStringProperty f1, f2, f3, f4, f5, f6;

        public String getF1() {
            return f1.get();
        }

        public String getF2() {
            return f2.get();
        }

        public String getF3() {
            return f3.get();
        }

        public String getF4() {
            return f4.get();
        }

        public String getF5() {
            return f5.get();
        }

        public String getF6() {
            return f6.get();
        }

        Record(String f1, String f2, String f3, String f4,
                String f5, String f6) {
            this.f1 = new SimpleStringProperty(f1);
            this.f2 = new SimpleStringProperty(f2);
            this.f3 = new SimpleStringProperty(f3);
            this.f4 = new SimpleStringProperty(f4);
            this.f5 = new SimpleStringProperty(f5);
            this.f6 = new SimpleStringProperty(f6);
        }

    }

    private final TableView<Record> tableView = new TableView<>();

    private final ObservableList<Record> dataList
            = FXCollections.observableArrayList();

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("java-buddy.blogspot.com");

        Group root = new Group();

        TableColumn columnF1 = new TableColumn("f1");
        columnF1.setCellValueFactory(
                new PropertyValueFactory<>("f1"));

        TableColumn columnF2 = new TableColumn("f2");
        columnF2.setCellValueFactory(
                new PropertyValueFactory<>("f2"));

        TableColumn columnF3 = new TableColumn("f3");
        columnF3.setCellValueFactory(
                new PropertyValueFactory<>("f3"));

        TableColumn columnF4 = new TableColumn("f4");
        columnF4.setCellValueFactory(
                new PropertyValueFactory<>("f4"));

        TableColumn columnF5 = new TableColumn("f5");
        columnF5.setCellValueFactory(
                new PropertyValueFactory<>("f5"));

        TableColumn columnF6 = new TableColumn("f6");
        columnF6.setCellValueFactory(
                new PropertyValueFactory<>("f6"));

        tableView.setItems(dataList);
        tableView.getColumns().addAll(
                columnF1, columnF2, columnF3, columnF4, columnF5, columnF6);

        VBox vBox = new VBox();
        vBox.setSpacing(10);
        vBox.getChildren().add(tableView);

        root.getChildren().add(vBox);

        primaryStage.setScene(new Scene(root, 700, 250));
        primaryStage.show();

        //readCSV();
        
        //run in background thread
        new Thread() {
            
            @Override
            public void run() {
                readCSV();
            };
            
        }.start();
        
    }

    private void readCSV() {
        
        System.out.println("Platform.isFxApplicationThread(): "
                        + Platform.isFxApplicationThread());

        String CsvFile = "/home/buddy/test/test.csv";
        String FieldDelimiter = ",";

        BufferedReader br;

        try {
            br = new BufferedReader(new FileReader(CsvFile));

            String line;
            while ((line = br.readLine()) != null) {
                String[] fields = line.split(FieldDelimiter, -1);

                Record record = new Record(fields[0], fields[1], fields[2],
                        fields[3], fields[4], fields[5]);
                dataList.add(record);

                //Add delay to simulate long time operation
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(JavaFXCSVTableView.class.getName())
                            .log(Level.SEVERE, null, ex);
                }
            }

        } catch (FileNotFoundException ex) {
            Logger.getLogger(JavaFXCSVTableView.class.getName())
                    .log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(JavaFXCSVTableView.class.getName())
                    .log(Level.SEVERE, null, ex);
        }

    }

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

}

Wednesday, June 15, 2016

Java to read csv file

This example show how to read csv file using Java.


Prepare:
- Create a spreadsheet:


- Export as csv file:


- The exported csv file in text format:


Using java to read the csv file and print the content:
package javareadcsv;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaReadCSV {
    
    static String CsvFile = "/home/buddy/test/test.csv";
    static String FieldDelimiter = ",";

    public static void main(String[] args) throws IOException {
        BufferedReader br;
        
        try {
            br = new BufferedReader(new FileReader(CsvFile));
            
            String line;
            while ((line = br.readLine()) != null) {
                String[] fields = line.split(FieldDelimiter, -1);
                System.out.print(fields.length + "-");
                for(String s : fields){
                    System.out.print(s);
                    System.out.print(":");
                }
                System.out.println();
            }
            
        } catch (FileNotFoundException ex) {
            Logger.getLogger(JavaReadCSV.class.getName())
                    .log(Level.SEVERE, null, ex);
        }
        
    }
    
}



To display the content with JavaFX TableView, read next post.

Tuesday, June 7, 2016

Java example using Supplier to get input from Scanner

Java example using java.util.function.Supplier to get input from java.util.Scanner.


JavaSupplier.java
package javasupplier;

import java.util.Scanner;
import java.util.function.Supplier;
import java.util.stream.Stream;

public class JavaSupplier {

    public static void main(String[] args) {
        Supplier<String> msg  = ()-> "http://java-buddy.blogspot.com/";
        System.out.println(msg.get());
        System.out.println();
        
        Scanner scanner = new Scanner(System.in);
        Supplier<String> scannerNext = () -> scanner.next();
        System.out.println("Enter something, 'q' to quit");
        
        Stream.generate(scannerNext)
                .map(s -> {
                    System.out.println(s);
                    return s;
                })
                .allMatch(s -> !"q".equals(s));
    }
    
}



Thursday, March 3, 2016

Read from Internet using URLConnection and ReadableByteChannel

Java example to read from Internet, "http://java-buddy.blogspot.com", using URLConnection and ReadableByteChannel.


Example:
package javaurlconnection;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.logging.Level;
import java.util.logging.Logger;

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

    public static void main(String[] args) {
        try {
            URL url = new URL("http://java-buddy.blogspot.com");
            URLConnection urlConnection = url.openConnection();
            InputStream inputStream = urlConnection.getInputStream();
            try (ReadableByteChannel readableByteChannel = Channels.newChannel(inputStream)) {
                ByteBuffer buffer = ByteBuffer.allocate(1024);

                while (readableByteChannel.read(buffer) > 0)
                {
                    String bufferString = new String(buffer.array());
                    System.out.println(bufferString);
                    buffer.clear();
                }
            }
        } catch (MalformedURLException ex) {
            Logger.getLogger(JavaURLConnection.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(JavaURLConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
}



Related:
- Read from Internet using URLConnection and BufferedReader (Thanks Tomtom comment)

Saturday, January 24, 2015

Java example to copy file

This example show copy file in Java, with JavaFX interface.


package javafx_copyfile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.event.ActionEvent;
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_CopyFile extends Application {

    File srcFile, destFile;

    @Override
    public void start(Stage primaryStage) {

        FileChooser openFileChooser = new FileChooser();
        FileChooser saveFileChooser = new FileChooser();
        File openFile;
        File saveFile;

        Button btnOpenFile = new Button("Open File");
        Label labelOpenFile = new Label();
        Button btnSaveFile = new Button("Save File");
        Label labelSaveFile = new Label();
        Button btnCopyFile = new Button("Copy File...");

        btnOpenFile.setOnAction((ActionEvent event) -> {
            File file = openFileChooser.showOpenDialog(null);
            if (file != null) {
                srcFile = file;
                labelOpenFile.setText(srcFile.getName());
            }
        });

        btnSaveFile.setOnAction((ActionEvent event) -> {
            File file = openFileChooser.showSaveDialog(null);
            if (file != null) {
                destFile = file;
                labelSaveFile.setText(destFile.getName());
            }
        });

        btnCopyFile.setOnAction((ActionEvent event) -> {
            if (srcFile != null && destFile != null) {
                copyFile(srcFile, destFile);
            }
        });

        VBox vBox = new VBox();
        vBox.getChildren().addAll(btnOpenFile, labelOpenFile,
                btnSaveFile, labelSaveFile, btnCopyFile);

        StackPane root = new StackPane();
        root.getChildren().add(vBox);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

    private void copyFile(File src, File dest) {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        int len;
        byte buffer[] = new byte[512];

        try {
            inputStream = new FileInputStream(src);
            outputStream = new FileOutputStream(dest);

            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(JavaFX_CopyFile.class.getName())
                    .log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(JavaFX_CopyFile.class.getName())
                    .log(Level.SEVERE, null, ex);
        } finally {
            try {
                if(inputStream != null){
                    inputStream.close();
                }
                if(outputStream != null){
                    outputStream.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(JavaFX_CopyFile.class.getName())
                        .log(Level.SEVERE, null, ex);
            }
        }

    }

}

Wednesday, January 14, 2015

Various Effect on JavaFX ImageView

This post show various Effect applied on ImageView.



package javafximage;

import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.SnapshotParameters;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.effect.Blend;
import javafx.scene.effect.BlendMode;
import javafx.scene.effect.Bloom;
import javafx.scene.effect.BlurType;
import javafx.scene.effect.BoxBlur;
import javafx.scene.effect.ColorAdjust;
import javafx.scene.effect.ColorInput;
import javafx.scene.effect.DisplacementMap;
import javafx.scene.effect.DropShadow;
import javafx.scene.effect.Effect;
import javafx.scene.effect.FloatMap;
import javafx.scene.effect.GaussianBlur;
import javafx.scene.effect.Glow;
import javafx.scene.effect.ImageInput;
import javafx.scene.effect.InnerShadow;
import javafx.scene.effect.Light;
import javafx.scene.effect.Lighting;
import javafx.scene.effect.MotionBlur;
import javafx.scene.effect.PerspectiveTransform;
import javafx.scene.effect.Reflection;
import javafx.scene.effect.SepiaTone;
import javafx.scene.effect.Shadow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javax.imageio.ImageIO;

/**
 *
 * @web http://java-buddy.blogspot.com
 */
public class JavaFXImage extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        
        Image image = new Image("http://goo.gl/kYEQl");
        ImageView imageView = new ImageView();
        imageView.setImage(image);
        
        Image secondImage = new Image("http://goo.gl/Z6Qiw0");
        
        int imageWidth = (int) image.getWidth();
        int imageHeight = (int) image.getHeight();
        
        //Blend effect
        Blend blend = new Blend();
        blend.setMode(BlendMode.COLOR_BURN);
        ColorInput blendColorInput = new ColorInput();
        blendColorInput.setPaint(Color.STEELBLUE);
        blendColorInput.setX(0);
        blendColorInput.setY(0);
        blendColorInput.setWidth(imageWidth);
        blendColorInput.setHeight(imageHeight);
        blend.setTopInput(blendColorInput);
        
        //Bloom effect
        Bloom bloom = new Bloom(0.1);
        
        //BoxBlur effect
        BoxBlur boxBlur = new BoxBlur();
        boxBlur.setWidth(3);
        boxBlur.setHeight(3);
        boxBlur.setIterations(3);
        
        //ColorAdjust effect
        ColorAdjust colorAdjust = new ColorAdjust();
        colorAdjust.setContrast(0.1);
        colorAdjust.setHue(-0.05);
        colorAdjust.setBrightness(0.1);
        colorAdjust.setSaturation(0.2);
        
        //ColorInput effect
        ColorInput colorInput;
        colorInput = new ColorInput(0, 0, 
                imageWidth, imageHeight, Color.STEELBLUE);

        //DisplacementMap effect
        FloatMap floatMap = new FloatMap();
        floatMap.setWidth(imageWidth);
        floatMap.setHeight(imageHeight);

        for (int i = 0; i < imageWidth; i++) {
            double v = (Math.sin(i / 20.0 * Math.PI) - 0.5) / 40.0;
            for (int j = 0; j < imageHeight; j++) {
                floatMap.setSamples(i, j, 0.0f, (float) v);
            }
        }
        DisplacementMap displacementMap = new DisplacementMap();
        displacementMap.setMapData(floatMap);
        
        //DropShadow effect
        DropShadow dropShadow = new DropShadow();
        dropShadow.setRadius(5.0);
        dropShadow.setOffsetX(10.0);
        dropShadow.setOffsetY(5.0);
        dropShadow.setColor(Color.GREY);
        
        //GaussianBlur effect
        GaussianBlur gaussianBlur = new GaussianBlur();
        
        //Glow effect
        Glow glow = new Glow(1.0);
        
        //ImageInput effect
        ImageInput imageInput = new ImageInput(secondImage);
        
        //InnerShadow effect
        InnerShadow innerShadow = new InnerShadow(5.0, 5.0, 5.0, Color.AZURE);
        
        //Lighting effect
        Light.Distant light = new Light.Distant();
        light.setAzimuth(50.0);
        light.setElevation(30.0);
        light.setColor(Color.YELLOW);
        
        Lighting lighting = new Lighting();
        lighting.setLight(light);
        lighting.setSurfaceScale(50.0);
        
        //MotionBlur effect
        MotionBlur motionBlur = new MotionBlur();
        motionBlur.setRadius(30);
        motionBlur.setAngle(-15.0);
        
        //PerspectiveTransform effect
        PerspectiveTransform perspectiveTrasform = new PerspectiveTransform();
        perspectiveTrasform.setUlx(0.0);
        perspectiveTrasform.setUly(0.0);
        perspectiveTrasform.setUrx(imageWidth*1.5);
        perspectiveTrasform.setUry(0.0);
        perspectiveTrasform.setLrx(imageWidth*3);
        perspectiveTrasform.setLry(imageHeight*2);
        perspectiveTrasform.setLlx(0);
        perspectiveTrasform.setLly(imageHeight);
        
        //Reflection effect
        Reflection reflection = new Reflection();
        reflection.setFraction(0.7);
        
        //SepiaTone effect
        SepiaTone sepiaTone = new SepiaTone();
        
        //Shadow effect
        Shadow shadow = new Shadow(BlurType.THREE_PASS_BOX, Color.BLUE, 10.0);
        
        Effect effects[] = {
            null,
            blend,
            bloom,
            boxBlur,
            colorAdjust,
            colorInput,
            displacementMap,
            dropShadow,
            gaussianBlur,
            glow,
            imageInput,
            innerShadow,
            lighting,
            motionBlur,
            perspectiveTrasform,
            reflection,
            sepiaTone,
            shadow
        };
        
        ChoiceBox choiceBox = new ChoiceBox(
            FXCollections.observableArrayList(
                "null", "Blend", "Bloom", "BoxBlur", "ColorAdjust",
                "ColorInput", "DisplacementMap", "DropShadow",
                "GaussianBlur", "Glow", "ImageInput", "InnerShadow",
                "Lighting", "MotionBlur", "PerspectiveTransform",
                "Reflection", "SepiaTone", "Shadow"
            ));
        choiceBox.getSelectionModel().selectFirst();
        
        choiceBox.getSelectionModel().selectedIndexProperty()
            .addListener((ObservableValue<? extends Number> observable, 
                Number oldValue, Number newValue) -> {
            imageView.setEffect(effects[newValue.intValue()]);
        });
        
        ImageView retrievedImage = new ImageView();
        Label labelPath = new Label();
        
        Button btnSnapShot = new Button("Take SnapShot");
        btnSnapShot.setOnAction((ActionEvent event) -> {
            File savedFile = takeSnapShot(imageView);
            retrieveImage(savedFile, retrievedImage, labelPath);
        });
        
        Button btnSaveImage = new Button("Save");
        btnSaveImage.setOnAction((ActionEvent event) -> {
            File savedFile = saveImage(imageView);
            retrieveImage(savedFile, retrievedImage, labelPath);
        });

        VBox vBox = new VBox();
        vBox.setSpacing(5);
        vBox.setPadding(new Insets(5, 5, 5, 5));
        vBox.getChildren().addAll(choiceBox, imageView, btnSnapShot, 
                btnSaveImage, retrievedImage, labelPath);
        
        StackPane root = new StackPane();
        root.getChildren().add(vBox);

        Scene scene = new Scene(root, 400, 350);
        
        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
    
    //Take SnapShot and save
    private File takeSnapShot(Node node){

        WritableImage writableImage = node.snapshot(new SnapshotParameters(), null);
        
        File file = new File("snapshot.png");
        
        try {
            ImageIO.write(SwingFXUtils.fromFXImage(writableImage, null), "png", file);
            System.out.println("snapshot saved: " + file.getAbsolutePath());
            return file;
        } catch (IOException ex) {
            Logger.getLogger(JavaFXImage.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }
    
    //Save Image of ImageView
    private File saveImage(ImageView iv){
        Image img = iv.getImage();
        File file = new File("savedImage.png");
        RenderedImage renderedImage = SwingFXUtils.fromFXImage(img, null);
        try {
            ImageIO.write(renderedImage, "png", file);
            System.out.println("Image saved: " + file.getAbsolutePath());
            return file;
        } catch (IOException ex) {
            Logger.getLogger(JavaFXImage.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }
    
    //Retrieve saved image
    private void retrieveImage(File file, ImageView imageView, Label label){
        if(file != null){
            Image image = new Image(file.toURI().toString());
            imageView.setImage(image);
            
            label.setText(file.getName() + "\n"
                    + image.getWidth() + " x " + image.getHeight());
        }else{
            label.setText("");
            imageView.setImage(null);
        }
    }
}

Thursday, August 21, 2014

Parse /proc/meminfo using Java code

The example "Read text file using Stream" return result as String. It is hard to use. To make use of it, we always have to parse as meanful items. This example show how to parse the file "/proc/meminfo".



package java_meminfo;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class Java_meminfo {
    
    final static String FILE_MEMINFO = "/proc/meminfo";

    public static void main(String[] args) {

        Stream<String> streamMemInfo = readFile(FILE_MEMINFO);
        streamMemInfo.forEach((line) -> {
            System.out.println(line);
            
            //split one line by whitespace/grouped whitespaces
            String[] oneLine = line.split("\\s+");

            for (String ele : oneLine) {
                System.out.println(ele);
            }

            System.out.println("---");
        });

    }
    
    static private Stream<String> readFile(String filePath){
        Path path = Paths.get(FILE_MEMINFO);
        
        Stream<String> fileLines = null;
        try {
            fileLines = Files.lines(path);
        } catch (IOException ex) {
            Logger.getLogger(Java_meminfo.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return fileLines;
    }
    
}


Next post show how to display it on TableView.

Monday, August 18, 2014

Example of using ExecutorService/Executors

This example show how to use ExecutorService/Executors.


Executor is an object that executes submitted Runnable tasks. This interface provides a way of decoupling task submission from the mechanics of how each task will be run, including details of thread use, scheduling, etc. An Executor is normally used instead of explicitly creating threads.

ExecutorService is an Executor that provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks.

An ExecutorService can be shut down, which will cause it to reject new tasks. Two different methods are provided for shutting down an ExecutorService. The shutdown() method will allow previously submitted tasks to execute before terminating, while the shutdownNow() method prevents waiting tasks from starting and attempts to stop currently executing tasks. Upon termination, an executor has no tasks actively executing, no tasks awaiting execution, and no new tasks can be submitted. An unused ExecutorService should be shut down to allow reclamation of its resources.


Example:
package javafxexecutorservice;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFXExecutorService extends Application {
    
    ExecutorService executorService = null;

    @Override
    public void start(Stage primaryStage) {
        
        CountDownLatch countDownLatch1 = new CountDownLatch(5);
        CountThread countThread1 = new CountThread("A", countDownLatch1, 5);
        ProgressBar progressBar1 = new ProgressBar();
        progressBar1.progressProperty().bind(countThread1.processProperty);
        
        CountDownLatch countDownLatch2 = new CountDownLatch(10);
        CountThread countThread2 = new CountThread("B", countDownLatch2, 10);
        ProgressBar progressBar2 = new ProgressBar();
        progressBar2.progressProperty().bind(countThread2.processProperty);
        
        CountDownLatch countDownLatch3 = new CountDownLatch(5);
        CountThread countThread3 = new CountThread("C", countDownLatch3, 5);
        ProgressBar progressBar3 = new ProgressBar();
        progressBar3.progressProperty().bind(countThread3.processProperty);
        
        CountDownLatch countDownLatch4 = new CountDownLatch(5);
        CountThread countThread4 = new CountThread("D", countDownLatch4, 5);
        ProgressBar progressBar4 = new ProgressBar();
        progressBar4.progressProperty().bind(countThread4.processProperty);
        
        CountDownLatch countDownLatch5 = new CountDownLatch(5);
        CountThread countThread5 = new CountThread("E", countDownLatch5, 5);
        ProgressBar progressBar5 = new ProgressBar();
        progressBar5.progressProperty().bind(countThread5.processProperty);

        Button btnStart = new Button();
        btnStart.setText("Start");
        btnStart.setOnAction(new EventHandler<ActionEvent>() {
            
            @Override
            public void handle(ActionEvent event) {
                System.out.println("Start");
                executorService = Executors.newFixedThreadPool(2);
                executorService.execute(countThread1);
                executorService.execute(countThread2);
                executorService.execute(countThread3);
                executorService.execute(countThread4);
                executorService.execute(countThread5);
            }
        });
        
        Button btnShutdown = new Button();
        btnShutdown.setText("Shut Down");
        btnShutdown.setOnAction(new EventHandler<ActionEvent>() {
            
            @Override
            public void handle(ActionEvent event) {
                if(executorService != null){
                    System.out.println("Shut Down");
                    executorService.shutdown();
                }
            }
        });
        
        Button btnShutdownNow = new Button();
        btnShutdownNow.setText("Shut Down Now");
        btnShutdownNow.setOnAction(new EventHandler<ActionEvent>() {
            
            @Override
            public void handle(ActionEvent event) {
                if(executorService != null){
                    System.out.println("Shut Down Now");
                    executorService.shutdownNow();
                }
            }
        });
        
        VBox vBox = new VBox();
        vBox.getChildren().addAll(btnStart, btnShutdown, 
            btnShutdownNow, progressBar1, progressBar2, 
            progressBar3, progressBar4, progressBar5);
        
        StackPane root = new StackPane();
        root.getChildren().add(vBox);
        
        Scene scene = new Scene(root, 300, 250);
        
        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

class CountThread implements Runnable {

    int num_of_count = 5;
    CountDownLatch counter;
    String name;
    
    DoubleProperty processProperty;

    CountThread(String n, CountDownLatch c, int num) {
        name = n;
        counter = c;
        num_of_count = num;
        processProperty = new SimpleDoubleProperty(num_of_count);
    }

    @Override
    public void run() {

        for (int i = 0; i < num_of_count; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(CountThread.class.getName()).log(Level.SEVERE, null, ex);
            }
            
            processProperty.set((double)(counter.getCount())/(double)num_of_count);
            System.out.println(name + " : " + counter.getCount());
            counter.countDown();
            
        }
    }

}

Thursday, August 14, 2014

Read text file using Stream

This example show how to read text file using Stream<String> by calling Files.lines(path); to read the file /proc/cpuinfo, /proc/version or /proc/meminfo or Linux.

package java_streamreadtextfile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;

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

    //final static String FILE_NAME = "/proc/cpuinfo";
    //final static String FILE_NAME = "/proc/version";
    final static String FILE_NAME = "/proc/meminfo";

    public static void main(String[] args) {
        
        Path path = Paths.get(FILE_NAME);
        try {
            Stream<String> fileLines = Files.lines(path);
            fileLines.forEach((line) -> System.out.println(line));

        } catch (IOException ex) {
            Logger.getLogger(Java_StreamReadTextFile.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
}



- Parse /proc/meminfo using Java code

Tuesday, August 12, 2014

Example of using java.util.function.Consumer

Java 8 introduce java.util.function.Consumer, a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

This example show ways to print all elements in a List. Also show how to implement our Consumer.

package java8consumer;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

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

    public static void main(String[] args) {
        List myList = new ArrayList();
        for(int i=0; i<=5; i++){
            myList.add(i);
        }
        
        for(int i=0; i<myList.size(); i++){
            System.out.println(myList.get(i));
        }
        
        for (Object ele : myList) {
            System.out.println(ele);
        }
        
        myList.forEach((ele) -> System.out.println(ele)); 
        
        //Use Consumer
        MyConsumer myConsumer = new MyConsumer();
        myList.forEach(myConsumer);
    }
    
}

class MyConsumer implements Consumer{

    @Override
    public void accept(Object t) {
        System.out.println(t);
    }

}


java.util.function.Consumer example

Saturday, May 10, 2014

print ZonedDateTime with format



package javazoneddatetime;

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @web java-buddy.blogspot.com
 */
public class JavaZonedDateTime {

    public static void main(String[] args) {
        ZonedDateTime zdt = 
            ZonedDateTime.parse("2007-12-03T10:15:30+01:00[Europe/Paris]");
        
        System.out.println("BASIC_ISO_DATE: \t" + zdt.format(DateTimeFormatter.BASIC_ISO_DATE));
        System.out.println("ISO_LOCAL_DATE: \t" + zdt.format(DateTimeFormatter.ISO_LOCAL_DATE));
        System.out.println("ISO_OFFSET_DATE: \t" + zdt.format(DateTimeFormatter.ISO_OFFSET_DATE));
        System.out.println("ISO_DATE: \t\t" + zdt.format(DateTimeFormatter.ISO_DATE));
        System.out.println("ISO_LOCAL_TIME: \t" + zdt.format(DateTimeFormatter.ISO_LOCAL_TIME));
        System.out.println("ISO_OFFSET_TIME: \t" + zdt.format(DateTimeFormatter.ISO_OFFSET_TIME));
        System.out.println("ISO_TIME: \t\t" + zdt.format(DateTimeFormatter.ISO_TIME));
        System.out.println("ISO_LOCAL_DATE_TIME: \t" + zdt.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
        System.out.println("ISO_OFFSET_DATE_TIME: \t" + zdt.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
        System.out.println("ISO_ZONED_DATE_TIME: \t" + zdt.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
        System.out.println("ISO_DATE_TIME: \t\t" + zdt.format(DateTimeFormatter.ISO_DATE_TIME));
        System.out.println("ISO_ORDINAL_DATE: \t" + zdt.format(DateTimeFormatter.ISO_ORDINAL_DATE));
        System.out.println("ISO_WEEK_DATE: \t\t" + zdt.format(DateTimeFormatter.ISO_WEEK_DATE));
        System.out.println("ISO_INSTANT: \t\t" + zdt.format(DateTimeFormatter.ISO_INSTANT));
        System.out.println("RFC_1123_DATE_TIME: \t" + zdt.format(DateTimeFormatter.RFC_1123_DATE_TIME));
    }
    
}

Friday, May 9, 2014

Conversion between ZonedDateTime and GregorianCalendar

package javazoneddatetime;

import java.time.ZonedDateTime;
import java.util.GregorianCalendar;

/**
 * @web java-buddy.blogspot.com
 */
public class JavaZonedDateTime {

    public static void main(String[] args) {
        ZonedDateTime zonedDateTime1 = 
            ZonedDateTime.parse("2007-12-03T10:15:30+01:00[Europe/Paris]");
        GregorianCalendar gregorianCalendar = GregorianCalendar.from(zonedDateTime1);
        ZonedDateTime zonedDateTime2 = gregorianCalendar.toZonedDateTime();
        
        System.out.println("zonedDateTime1: " + zonedDateTime1.toString());
        System.out.println("gregorianCalendar: " + gregorianCalendar);
        System.out.println("zonedDateTime2: " + zonedDateTime2.toString());
    }
    
}


Conversion between ZonedDateTime and GregorianCalendar

Wednesday, May 7, 2014

ZonedDateTime example

Example of using ZonedDateTime:

ZonedDateTime
ZonedDateTime example

package javazoneddatetime;

import java.time.ZonedDateTime;

/**
 * @web java-buddy.blogspot.com
 */
public class JavaZonedDateTime {

    public static void main(String[] args) {
        ZonedDateTime zonedDateTime = 
            ZonedDateTime.parse("2007-12-03T10:15:30+01:00[Europe/Paris]");
        System.out.println("zonedDateTime: " + zonedDateTime.toString());
        System.out.println("Zone: " + zonedDateTime.getZone());
        System.out.println("Offset: " + zonedDateTime.getOffset());
        System.out.println("Year: " + zonedDateTime.getYear());
        System.out.println("Month: " + zonedDateTime.getMonth());
        System.out.println("DayOfMonth: " + zonedDateTime.getDayOfMonth());
        System.out.println("Hour: " + zonedDateTime.getHour());
        System.out.println("Minute: " + zonedDateTime.getMinute());
        System.out.println("Second: " + zonedDateTime.getSecond());
        System.out.println("MonthValue: " + zonedDateTime.getMonthValue());
        System.out.println("DayOfYear: " + zonedDateTime.getDayOfYear());
        System.out.println("DayOfWeek: " + zonedDateTime.getDayOfWeek());
        System.out.println("Nano: " + zonedDateTime.getNano());
        
    }
    
}


Thursday, April 17, 2014

Some examples of using Stream of Java 8

This post show some example of using Stream<String> of Java 8; such as splite String to Stream<String> of words, print all element in Stream, count number of element, sort Stream, convert to lower case, find the maximum, and Find the first word starts with.

package java8stream;

import java.util.Optional;
import java.util.stream.Stream;

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

    static String lyrics = "Hello darkness, my old friend,\n"
            + "I've come to talk with you again,\n"
            + "Because a vision softly creeping,\n"
            + "Left its seeds while I was sleeping,\n"
            + "And the vision that was planted in my brain\n"
            + "Still remains\n"
            + "Within the sound of silence.";

    public static void main(String[] args) {
        System.out.println("--- lyrics ---");
        System.out.println(lyrics);

        System.out.println("--- Some examples of using Stream ---");
        
        //print all element in Stream<String>
        Stream.of(lyrics.split("[\\P{L}]+"))
            .forEach((String element) -> System.out.println(element));
        
        //count number of element in Stream
        System.out.println("count of words = " + 
            Stream.of(lyrics.split("[\\P{L}]+")).count());
        
        System.out.println("--- Sorted Stream ---");
        Stream<String> sortedStream = Stream.of(lyrics.split("[\\P{L}]+")).sorted();
        sortedStream.forEach((String element) -> System.out.println(element));
        
        System.out.println("--- Convert to lower case ---");
        Stream<String> sortedStreamLower = Stream.of(lyrics.split("[\\P{L}]+"))
                .map(String::toLowerCase);
        sortedStreamLower.forEach((String element) -> System.out.println(element));
        
        System.out.println("--- Find the maximum, ignore case, in Stream<String> ---");
        Optional<String> max = Stream.of(lyrics.split("[\\P{L}]+"))
                .max(String::compareToIgnoreCase);
        if(max.isPresent()){
            System.out.println("max = " + max.get());
        }
        
        System.out.println("--- Find the first word starts with 'c' ---");
        Optional<String> startsWithC = Stream.of(lyrics.split("[\\P{L}]+"))
                .filter(s->s.startsWith("c")).findFirst();
        if(startsWithC.isPresent()){
            System.out.println("the first word starts with 'c' = " + startsWithC.get());
        }
    }

}



Tuesday, April 8, 2014

nashorn JavaScript exercise, call Java method from JavaScript

This example show how to call Java javaStaticMethod() in "javatestnashornjavascript.JavaTestNashornJavascript" class.

JavaTestNashornJavascript.java
package javatestnashornjavascript;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.net.URISyntaxException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaTestNashornJavascript {
    
    final String myJavascript = "<path to myjavascript.js>";
    
    JavaTestNashornJavascript(){
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");

        try {
            FileReader fileReader = new FileReader(myJavascript);
            nashorn.eval(fileReader);

            Invocable invocable = (Invocable) nashorn;

            Object jsResult = invocable.invokeFunction(
                    "javascriptFunction", "Java-Buddy");
            System.out.println("result returned to Java from JavaScript: " + jsResult);

        } catch (FileNotFoundException 
                | ScriptException 
                | NoSuchMethodException ex) {
            Logger.getLogger(JavaTestNashornJavascript
                    .class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public static String javaStaticMethod(String para){
        System.out.println("javaStaticMethod("+para+") called");
        String rev = new StringBuilder(para).reverse().toString();
        return rev;
    };

    public static void main(String[] args) throws URISyntaxException {
        
        JavaTestNashornJavascript javaTestNashornJavascript = 
                new JavaTestNashornJavascript();

    }

}


myjavascript.js
var javascriptFunction = function(para){
    
    print("para passed from Java to JavaScript: " + para);
    
    var myClass = Java.type("javatestnashornjavascript.JavaTestNashornJavascript");
    var revPara = myClass.javaStaticMethod(para);
    
    return "Hello " + revPara;
};



Monday, April 7, 2014

nashorn JavaScript exercise, call JavaScript function from Java

Example to call function and get result in Javascript, from Java code:

JavaTestNashornJavascript.java
package javatestnashornjavascript;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.net.URISyntaxException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaTestNashornJavascript {
    
    final String myJavascript = "<path to myjavascript.js>";
    
    JavaTestNashornJavascript(){
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");

        try {
            FileReader fileReader = new FileReader(myJavascript);
            nashorn.eval(fileReader);

            Invocable invocable = (Invocable) nashorn;

            Object jsResult = invocable.invokeFunction(
                    "javascriptFunction", "Java-Buddy");
            System.out.println("result returned to Java from JavaScript: " + jsResult);

        } catch (FileNotFoundException 
                | ScriptException 
                | NoSuchMethodException ex) {
            Logger.getLogger(JavaTestNashornJavascript
                    .class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void main(String[] args) throws URISyntaxException {
        
        JavaTestNashornJavascript javaTestNashornJavascript = 
                new JavaTestNashornJavascript();

    }

}


myjavascript.js
var javascriptFunction = function(para){
    print("para passed from Java to JavaScript: " + para);
    return "Hello " + para;
}



more nashorn JavaScript exercise:


Hello from java-buddy, with nashorn JavaScript Engine.

JDK 8 introduces a new Nashorn JavaScript engine written in Java, which is an implementation of the ECMAScript Edition 5.1 Language Specification. Know more by reading Java Platform, Standard Edition Nashorn User's Guide.

it's a simple example to print hello message using "nashorn" ScriptEngine.



package javatestnashornjavascript;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

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

    public static void main(String[] args) {
        
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");
        
        try {
            nashorn.eval(
                "print('Hello from java-buddy, with nashorn JavaScript Engine.');");
        } catch (ScriptException ex) {
            Logger.getLogger(JavaTestNashornJavascript.class
                    .getName()).log(Level.SEVERE, null, ex);
        }
        
    }
    
}


more nashorn JavaScript exercise:


Thursday, March 13, 2014

Implement event handler using Lambda Expression

The following code replace traditional EventHandler with Lambda Expression in GUI application, JavaFX:
package javafx8_hello;

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 JavaFX8_Hello extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        Button btn = new Button();
        btn.setText("Say 'Hello World'");
        
        /* Normal 
        btn.setOnAction(new EventHandler<ActionEvent>() {
            
            @Override
            public void handle(ActionEvent event) {
                System.out.println("Hello World!");
            }
        });
        */
        
        /*
        In Lambda Expression
        */
        btn.setOnAction((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);
    }
    
}

Sunday, March 9, 2014

Get second of Day and nano decond of day with LocalTime

java.time.LocalTime is a time without time-zone in the ISO-8601 calendar system, such as 10:15:30.

LocalTime is an immutable date-time object that represents a time, often viewed as hour-minute-second. Time is represented to nanosecond precision. For example, the value "13:45.30.123456789" can be stored in a LocalTime.

The method toSecondOfDay() and toNanoOfDay() extracts the time as seconds of day/nanos of day.

Example:
package java8localtime;

import java.time.LocalTime;

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

    public static void main(String[] args) {
        LocalTime now = LocalTime.now();
        System.out.println("now.toString(): " + now.toString());
        System.out.println("now.toSecondOfDay(): " + now.toSecondOfDay());
        System.out.println("now.toNanoOfDay(): " + now.toNanoOfDay());
    }
}

Get second of Day and nano decond of day with LocalTime
Get second of Day and nano decond of day with LocalTime