Tuesday, January 27, 2015

Java HttpServer to download image

The example implement HttpServer to download image.


package java_httpserver;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class Java_HttpServer {
    
    static final int responseCode_OK = 200;

    public static void main(String[] args) {
        try {
            HttpServer httpServer = HttpServer.create(new InetSocketAddress(8000), 0);
            httpServer.createContext("/", new MyHttpHandler());
            httpServer.createContext("/image", new GetHttpHandler());
            httpServer.setExecutor(null);
            httpServer.start();
        } catch (IOException ex) {
            Logger.getLogger(Java_HttpServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    static class MyHttpHandler implements HttpHandler{

        @Override
        public void handle(HttpExchange he) throws IOException {
            
            String response = "Hello from java-buddy";
            he.sendResponseHeaders(responseCode_OK, response.length());
            
            OutputStream outputStream = he.getResponseBody();
            outputStream.write(response.getBytes());
            outputStream.close();
        }
    }
    
    static class GetHttpHandler implements HttpHandler{

        @Override
        public void handle(HttpExchange he) throws IOException {

            Headers headers = he.getResponseHeaders();
            headers.add("Content-Type", "image/png");
            
            File file = new File ("duke.png");
            byte[] bytes  = new byte [(int)file.length()];
            System.out.println(file.getAbsolutePath());
            System.out.println("length:" + file.length());
            
            FileInputStream fileInputStream = new FileInputStream(file);
            BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
            bufferedInputStream.read(bytes, 0, bytes.length);

            he.sendResponseHeaders(responseCode_OK, file.length());
            OutputStream outputStream = he.getResponseBody();
            outputStream.write(bytes, 0, bytes.length);
            outputStream.close();
        }
    }
    
}

Simple example of Java HttpServer

com.sun.net.httpserver.HttpServer  implements a simple HTTP server. A HttpServer is bound to an IP address and port number and listens for incoming TCP connections from clients on this address.


It's a simple example of using HttpServer.
package java_httpserver;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.logging.Level;
import java.util.logging.Logger;

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

    public static void main(String[] args) {
        try {
            HttpServer httpServer = HttpServer.create(new InetSocketAddress(8000), 0);
            httpServer.createContext("/", new MyHttpHandler());
            httpServer.setExecutor(null);
            httpServer.start();
        } catch (IOException ex) {
            Logger.getLogger(Java_HttpServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    static class MyHttpHandler implements HttpHandler{

        @Override
        public void handle(HttpExchange he) throws IOException {
            int responseCode_OK = 200;
            String response = "Hello from java-buddy";
            he.sendResponseHeaders(responseCode_OK, response.length());
            
            OutputStream outputStream = he.getResponseBody();
            outputStream.write(response.getBytes());
            outputStream.close();
            
            //try-with-resources form
            /*
            try (OutputStream outputStream = he.getResponseBody()) {
                outputStream.write(response.getBytes());
            }
            */

        }
        
    }
    
}

To access the server, open a browser and visit: http://localhost:8000/



Next example show how to implement HttpServer to download image.

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

    }

}