Wednesday, July 20, 2016

Java example of SSL Server and Client, and how to generate keystore

Here are examples of Java SSL Server and Client.



JavaSSLServer.java
package javasslserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLServerSocketFactory;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaSSLServer {
    
    static final int port = 8000;

    public static void main(String[] args) {
        
        
        SSLServerSocketFactory sslServerSocketFactory = 
                (SSLServerSocketFactory)SSLServerSocketFactory.getDefault();
        
        try {
            ServerSocket sslServerSocket = 
                    sslServerSocketFactory.createServerSocket(port);
            System.out.println("SSL ServerSocket started");
            System.out.println(sslServerSocket.toString());
            
            Socket socket = sslServerSocket.accept();
            System.out.println("ServerSocket accepted");
            
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            try (BufferedReader bufferedReader = 
                    new BufferedReader(
                            new InputStreamReader(socket.getInputStream()))) {
                String line;
                while((line = bufferedReader.readLine()) != null){
                    System.out.println(line);
                    out.println(line);
                }
            }
            System.out.println("Closed");
            
        } catch (IOException ex) {
            Logger.getLogger(JavaSSLServer.class.getName())
                    .log(Level.SEVERE, null, ex);
        }
    }
    
}


JavaSSLClient.java
package javasslclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLSocketFactory;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaSSLClient {
    
    static final int port = 8000;

    public static void main(String[] args) {
        
        SSLSocketFactory sslSocketFactory = 
                (SSLSocketFactory)SSLSocketFactory.getDefault();
        try {
            Socket socket = sslSocketFactory.createSocket("localhost", port);
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            try (BufferedReader bufferedReader = 
                    new BufferedReader(
                            new InputStreamReader(socket.getInputStream()))) {
                Scanner scanner = new Scanner(System.in);
                while(true){
                    System.out.println("Enter something:");
                    String inputLine = scanner.nextLine();
                    if(inputLine.equals("q")){
                        break;
                    }
                    
                    out.println(inputLine);
                    System.out.println(bufferedReader.readLine());
                }
            }
            
        } catch (IOException ex) {
            Logger.getLogger(JavaSSLClient.class.getName())
                    .log(Level.SEVERE, null, ex);
        }
         
    }
    
}



Without keystore, both the server and client will fail. This video show how to generate keystore using keytool program. Then run server and client with keystore and password.


Type the following command in your command window to create a keystore named examplestore and to generate keys:

$ keytool -genkey -alias signFiles -keystore examplestore

You will be prompted to enter passwords for the key and keystore. The password in this example is "password".

(reference: https://docs.oracle.com/javase/tutorial/security/toolsign/step3.html)

Run SSL server and client by entering the commands:
$ java -jar -Djavax.net.ssl.keyStore=keystore -Djavax.net.ssl.keyStorePassword=password "...JavaSSLServer.jar"
$ java -jar -Djavax.net.ssl.trustStore=keystore -Djavax.net.ssl.trustStorePassword=password "...JavaSSLClient.jar"


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);
    }

}

Read csv file, display in JavaFX TableView

Java example read csv file and display the content in JavaFX TableView.

To know how to prepare the csv file, and simple read csv file, refer to last post.


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.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();
    }

    private void readCSV() {

        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);

            }

        } 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);
    }

}


Next post show how to do the job in background.

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));
    }
    
}



Sunday, April 17, 2016

Get my MAC address using NetworkInterface

Java example to get MAC address using NetworkInterface:



package javamyip;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;

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

    public static void main(String[] args) {
        displayMyIP();
    }
    
    static void displayMyIP(){
        Enumeration<NetworkInterface> nets;
        try {
            nets = NetworkInterface.getNetworkInterfaces();
            for (NetworkInterface netint : Collections.list(nets)){
                System.out.printf(netint.getDisplayName() +"\n");
                Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
                for (InetAddress inetAddress : Collections.list(inetAddresses)) {
                    System.out.printf("InetAddress: %s\n", inetAddress);
                }
                
                byte[] mac = netint.getHardwareAddress();
                if(mac != null){
                    StringBuilder macAddr = new StringBuilder();
                    for (int i = 0; i < mac.length; i++) {
                        macAddr.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? ":" : "")); 
                    }
                    System.out.printf("Hardware address (MAC): [%s]\n", macAddr.toString());
                }
                
                System.out.printf("\n");
            }
        } catch (SocketException ex) {
            Logger.getLogger(JavaMyIP.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

Friday, April 15, 2016

List my IP (inetAddress)


Java example to list Network Interface Addresses and IP:

package javamyip;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;

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

    public static void main(String[] args) {
        displayMyIP();
    }
    
    static void displayMyIP(){
        Enumeration<NetworkInterface> nets;
        try {
            nets = NetworkInterface.getNetworkInterfaces();
            for (NetworkInterface netint : Collections.list(nets)){
                System.out.printf(netint.getDisplayName() +"\n");
                Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
                for (InetAddress inetAddress : Collections.list(inetAddresses)) {
                    System.out.printf("InetAddress: %s\n", inetAddress);
                }
                System.out.printf("\n");
            }
        } catch (SocketException ex) {
            Logger.getLogger(JavaMyIP.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}



Can use functional operations in Java 8 (auto suggested by Netbeans):
package javamyip;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;

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

    public static void main(String[] args) {
        displayMyIP();
    }
    
    static void displayMyIP(){
        Enumeration<NetworkInterface> nets;
        try {
            nets = NetworkInterface.getNetworkInterfaces();
            Collections.list(nets).stream().map((netint) -> {
                System.out.printf(netint.getDisplayName() +"\n");
                return netint;
            }).map((netint) -> netint.getInetAddresses()).map((inetAddresses) -> {
                Collections.list(inetAddresses).stream().forEach((inetAddress) -> {
                    System.out.printf("InetAddress: %s\n", inetAddress);
                });
                return inetAddresses;
            }).forEach((_item) -> {
                System.out.printf("\n");
            });
        } catch (SocketException ex) {
            Logger.getLogger(JavaMyIP.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}


Wednesday, April 13, 2016

Create ServerSocket with automatically allocated port

Create ServerSocket by calling constructor ServerSocket(int port) with port = 0,  the port number is automatically allocated, typically from an ephemeral port range. This port number can then be retrieved by calling getLocalPort.

Example:
package javaechoserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.logging.Level;
import java.util.logging.Logger;

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

    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        try {
            //Get a available port by passing 0 
            serverSocket = new ServerSocket(0);
            int port = serverSocket.getLocalPort();
            System.out.println("Port : " + port);
            
        } catch (IOException ex) {
            Logger.getLogger(JavaEchoServer.class.getName())
                    .log(Level.SEVERE, null, ex);
        } finally {
            if (serverSocket != null){
                try {
                    serverSocket.close();
                } catch (IOException ex) {
                    Logger.getLogger(JavaEchoServer.class.getName())
                            .log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
}



Friday, March 25, 2016

Mastering Concurrency Programming with Java 8

Master the principles and techniques of multithreaded programming with the Java 8 Concurrency API

Mastering Concurrency Programming with Java 8

About This Book
  • Implement concurrent applications using the Java 8 Concurrency API and its new components
  • Improve the performance of your applications or process more data at the same time, taking advantage of all of your resources.
  • Construct real-world examples related to machine learning, data mining, image processing, and client/server environments
Who This Book Is For
If you are a competent Java developer with a good understanding of concurrency but have no knowledge of how to effectively implement concurrent programs or use streams to make processes more efficient, then this book is for you.

What You Will Learn
  • Design concurrent applications by converting a sequential algorithm into a concurrent one
  • Discover how to avoid all the possible problems you can get in concurrent algorithms
  • Use the Executor framework to manage concurrent tasks without creating threads
  • Extend and modify Executors to adapt their behavior to your needs
  • Solve problems using the divide and conquer technique and the Fork/Join framework
  • Process massive data sets with parallel streams and Map/Reduce implementation
  • Control data-race conditions using concurrent data structures and synchronization mechanisms
  • Test and monitor concurrent applications
In Detail
Concurrency programming allows several large tasks to be divided into smaller sub-tasks, which are further processed as individual tasks that run in parallel. All the sub-tasks are combined together once the required results are achieved; they are then merged to get the final output. The whole process is very complex. This process goes from the design of concurrent algorithms to the testing phase where concurrent applications need extra attention. Java includes a comprehensive API with a lot of ready-to-use components to implement powerful concurrency applications in an easy way, but with a high flexibility to adapt these components to your needs.

The book starts with a full description of design principles of concurrent applications and how to parallelize a sequential algorithm. We'll show you how to use all the components of the Java Concurrency API from basics to the most advanced techniques to implement them in powerful concurrency applications in Java.

You will be using real-world examples of complex algorithms related to machine learning, data mining, natural language processing, image processing in client / server environments. Next, you will learn how to use the most important components of the Java 8 Concurrency API: the Executor framework to execute multiple tasks in your applications, the phaser class to implement concurrent tasks divided into phases, and the Fork/Join framework to implement concurrent tasks that can be split into smaller problems (using the divide and conquer technique). Toward the end, we will cover the new inclusions in Java 8 API, the Map and Reduce model, and the Map and Collect model. The book will also teach you about the data structures and synchronization utilities to avoid data-race conditions and other critical problems. Finally, the book ends with a detailed description of the tools and techniques that you can use to test a Java concurrent application.

Style and approach
A complete guide implementing real-world examples with algorithms related to machine learning, data mining, and natural language processing in client/server environments. All the examples are explained in a step-by-step approach.

Monday, March 14, 2016

JavaFX example: open new Window and exit all when primary window close


JavaFX example to open new Window, and exit all when primary window close.

package javafxwindow;

import javafx.application.Application;
import javafx.application.Platform;
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.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFXWindow extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        Button btn = new Button();
        btn.setText("Open a New Window");
        btn.setOnAction((ActionEvent event) -> {
            Label secondLabel = new Label("Hello");
            
            StackPane secondaryLayout = new StackPane();
            secondaryLayout.getChildren().add(secondLabel);
            
            Scene secondScene = new Scene(secondaryLayout, 200, 100);
            
            Stage secondStage = new Stage();
            secondStage.setTitle("New Stage");
            secondStage.setScene(secondScene);
            
            secondStage.show();

        });
         
        StackPane root = new StackPane();
        root.getChildren().add(btn);
         
        Scene scene = new Scene(root, 300, 250);
         
        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();
        
        primaryStage.setOnCloseRequest(e -> Platform.exit());

    }

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


Sunday, March 6, 2016

Read from Internet using URLConnection and BufferedReader

Java example to read from Internet using URLConnection and BufferedReader. Thanks for Tomtom's comment in my last post "Read from Internet using URLConnection and ReadableByteChannel".



package javaurlconnection;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
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();
                }
            }
            */
            
            //using BufferedReader
            InputStream inputStream = urlConnection.getInputStream();
            InputStreamReader inputStreamReader = 
                    new InputStreamReader(inputStream);
            BufferedReader buffReader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = buffReader.readLine()) != null) {
                System.out.println(line);
            }
            
        } 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);
        }
    }
    
}

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)

Tuesday, March 1, 2016

Get IP address of Website using InetAddress

Java example to get IP address of Website using InetAddress:

package javainetaddress;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

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

    public static void main(String[] args) {
        try {
            InetAddress inetAddress = InetAddress.getByName("www.google.com");
            System.out.println(inetAddress);
            System.out.println(inetAddress.getHostName());
            System.out.println(inetAddress.getHostAddress());
        } catch (UnknownHostException ex) {
            Logger.getLogger(JavaInetAddress.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
}




Saturday, January 9, 2016

JavaFX example to capture screen/GUI nodes


JavaFX example to capture screen/GUI nodes:
package javafxcapturescreen;

import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.SnapshotParameters;
import javafx.scene.control.Button;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javax.imageio.ImageIO;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFXCaptureScreen extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        StackPane root = new StackPane();
        Scene scene = new Scene(root, 300, 250);
        
        Button btnCaptureScene = new Button();
        btnCaptureScene.setText("Capture scene");
        btnCaptureScene.setOnAction((ActionEvent event) -> {
            
            WritableImage writableImage = scene.snapshot(null);
            File file = new File("capturedScene.png");
            try {
                ImageIO.write(SwingFXUtils.fromFXImage(writableImage, null), "png", file);
                System.out.println("Captured: " + file.getAbsolutePath());
            } catch (IOException ex) {
                Logger.getLogger(JavaFXCaptureScreen.class.getName()).log(Level.SEVERE, null, ex);
            }
        });
        
        Button btnCaptureRoot = new Button();
        btnCaptureRoot.setText("Capture root");
        btnCaptureRoot.setOnAction((ActionEvent event) -> {
            WritableImage writableImage = root.snapshot(new SnapshotParameters(), null);

            File file = new File("capturedRoot.png");
            try {
                ImageIO.write(SwingFXUtils.fromFXImage(writableImage, null), "png", file);
                System.out.println("Captured: " + file.getAbsolutePath());
            } catch (IOException ex) {
                Logger.getLogger(JavaFXCaptureScreen.class.getName()).log(Level.SEVERE, null, ex);
            }
        });
        
        VBox vBox = new VBox();
        vBox.getChildren().addAll(btnCaptureScene, btnCaptureRoot);
        root.getChildren().add(vBox);
        
        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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



capturedScene.png

capturedRoot.png

Thursday, January 7, 2016

Capture screen using java.awt.Robot

Java example to capture screen using java.awt.Robot:

package javarobotcapturescreen;

import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;

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

    public static void main(String[] args) {
        try {
            Robot robot = new Robot();
            
            Toolkit myToolkit = Toolkit.getDefaultToolkit();
            Dimension screenSize = myToolkit.getScreenSize();
            
            Rectangle screen = new Rectangle(screenSize);
            
            BufferedImage screenFullImage = robot.createScreenCapture(screen);
            ImageIO.write(screenFullImage, "jpg", new File("screen.jpg"));
            
        } catch (AWTException | IOException ex) {
            Logger.getLogger(JavaRobotCaptureScreen.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
}




captured screen:


Get screen size and resolution, with java.awt.Toolkit

Java example to get screen size and resolution, with java.awt.Toolkit:

package javagetscreensize;

import java.awt.Dimension;
import java.awt.Toolkit;

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

    public static void main(String[] args) {
        Toolkit myToolkit = Toolkit.getDefaultToolkit();
        Dimension screenSize = myToolkit.getScreenSize();
        int screenResolution = myToolkit.getScreenResolution();
        System.out.println("Screen size = " + screenSize.width + " x " + screenSize.height);
        System.out.println("Screen Resolution: " + screenResolution + " dots-per-inch");
    }
    
}



Java Everywhere: Write Once run Anywhere with DukeScript

Java Everywhere: Write Once run Anywhere with DukeScript

Do you want to write Java apps that run on mobile phones, tablets as well as your desktop computer? In this book you'll learn how to design and develop apps and upload them to Google Play and Apples App Store. The technology we'll use for that is DukeScript, a new framework for single-source cross-platform development in Java.