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

Sunday, May 29, 2016

Java Datagram/UDP Server and Client, run on raspberry Pi


A datagram is an independent, self-contained message sent over the network whose arrival, arrival time, and content are not guaranteed. It's simple exampls of Datagram/UDP Client and Server, modified from Java Tutorial - Writing a Datagram Client and Server.

It's assumed both server and client run on the same Raspberry Pi, so the IP is fixed "127.0.0.1", local loopback. And the port is arbitrarily chosen 4445.


In the Server side, JavaUdpServer.java, creates a DatagramSocket on port 4445. Wait for client connect, and reply with current date/time.
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Date;

/*
reference:
https://docs.oracle.com/javase/tutorial/networking/datagrams/clientServer.html
*/
public class JavaUdpServer {
    
    static UdpServerThread udpServerThread;

    public static void main(String[] args) throws IOException {
        System.out.println("Server start");
        System.out.println("Runtime Java: " 
                + System.getProperty("java.runtime.version"));
        
        
        new UdpServerThread().start();
    }

    private static class UdpServerThread extends Thread{
        
        final int serverport = 4445;
        
        protected DatagramSocket socket = null;
        
        public UdpServerThread() throws IOException {
            this("UdpServerThread");
        }
        
        public UdpServerThread(String name) throws IOException {
            super(name);
            socket = new DatagramSocket(serverport);
            System.out.println("JavaUdpServer run on: " + serverport);
        }

        @Override
        public void run() {
            
            while(true){
                
                try {
                    byte[] buf = new byte[256];
                    
                    // receive request
                    DatagramPacket packet = new DatagramPacket(buf, buf.length);
                    socket.receive(packet);
                    
                    String dString = new Date().toString();
                    buf = dString.getBytes();
                    
                    // send the response to the client at "address" and "port"
                    InetAddress address = packet.getAddress();
                    int port = packet.getPort();
                    System.out.println("Request from: " + address + ":" + port);
                    packet = new DatagramPacket(buf, buf.length, address, port);
                    socket.send(packet);
                    
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }
                
            }
            
        }
        
    }
    
}


In the client side, JavaUdpClient.java, sends a request to the Server, and waits for the response.
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

/*
reference:
https://docs.oracle.com/javase/tutorial/networking/datagrams/clientServer.html
*/
public class JavaUdpClient {

    public static void main(String[] args) 
            throws UnknownHostException, SocketException, IOException {
        
        //Hardcode ip:port
        String ipLocalLoopback = "127.0.0.1";
        int serverport = 4445;
        
        
        System.out.println("Runtime Java: " 
                + System.getProperty("java.runtime.version"));
        System.out.println("JavaUdpClient running, connect to: " 
                + ipLocalLoopback + ":" + serverport);
        
        // get a datagram socket
        DatagramSocket socket = new DatagramSocket();
        
        // send request
        byte[] buf = new byte[256];
        InetAddress address = InetAddress.getByName(ipLocalLoopback);
        DatagramPacket packet = 
                new DatagramPacket(buf, buf.length, address, serverport);
        socket.send(packet);
        
        // get response
        packet = new DatagramPacket(buf, buf.length);
        socket.receive(packet);
        
        String received = new String(packet.getData(), 0, packet.getLength());
        System.out.println(received);
        
        socket.close();
    }
    
}


Related:
- Android version Datagram/UDP Client
Android version Datagram/UDP Server

Monday, May 23, 2016

Java Network exercise: client and server - client send something to server

Refer to my old post of "Java exercise - Implement client and server to communicate using Socket", setup bold server and client. The server reply something to client once connected.


It's modified, client connect to server and send something. In server side, wait connected and print the received text to screen.


host.java
import java.io.BufferedReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;

class host
{
    public static void main(String srgs[])
    {   
        ServerSocket serverSocket = null;
        Socket socket = null;
        BufferedReader bufferedReader = null;
        PrintStream printStream = null;
        
        try{
            serverSocket = new ServerSocket(0);
            System.out.println("I'm waiting here: " 
                + serverSocket.getLocalPort());            
                                
            socket = serverSocket.accept();
            System.out.println("from " + 
                socket.getInetAddress() + ":" + socket.getPort());
            
            InputStreamReader inputStreamReader = 
                new InputStreamReader(socket.getInputStream());
            bufferedReader = new BufferedReader(inputStreamReader);
            
            String line;
            while((line=bufferedReader.readLine()) != null){
                System.out.println(line);
            }
        }catch(IOException e){
            System.out.println(e.toString());
        }finally{
            if(bufferedReader!=null){
                try {
                    bufferedReader.close();
                } catch (IOException ex) {
                    System.out.print(ex.toString());
                }
            }
            
            if(printStream!=null){
                printStream.close();
            }
            
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException ex) {
                    System.out.print(ex.toString());
                }
            }
        }
    }
}


client.java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class client {

    public static void main(String args[])
    { 
        if(args.length != 2){
            System.out.println("usage: java client <port> <something>");
            System.exit(1);
        }
        
        int port = isParseInt(args[0]);
        if(port == -1){
            System.out.println("usage: java client <port> <something>");
            System.out.println("<port>: integer");
            System.exit(1);
        }
        
        try{
            //IP is hard coded, Local Loopback = "127.0.0.1"
            //port is user entry
            Socket socket = new Socket("127.0.0.1", port);

            
            //Send msg to server
            OutputStream outputStream = socket.getOutputStream();
            PrintStream printStream = new PrintStream(outputStream);
            printStream.print(args[1]);
                
            socket.close();

        }catch(UnknownHostException e){
            System.out.println(e.toString());
        }catch(IOException e){
            System.out.println(e.toString());
        }

    }
    
    private static int isParseInt(String str){
        
        int num = -1;
        try{
             num = Integer.parseInt(str);
        } catch (NumberFormatException e) {
        }
        
        return num;
    }
    
}


It's Android version of the Client.

Next:
- bi-direction communication, between echo server and client

Sunday, February 7, 2016

Java to list Network Interface Parameters (include MAC address), run on Raspberry Pi/Raspbian Jessie


Java example code to list Network Interface Parameters (include MAC address), run on Raspberry Pi/Raspbian Jessie.


ListNetsEx.java
import java.io.*;
import java.net.*;
import java.util.*;
import static java.lang.System.out;

public class ListNetsEx {
    
    public static void main(String args[]) throws SocketException {
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netint : Collections.list(nets))
            displayInterfaceInformation(netint);
    }

    static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
        out.printf("Display name: %s\n", netint.getDisplayName());
        out.printf("Name: %s\n", netint.getName());
        Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
        
        for (InetAddress inetAddress : Collections.list(inetAddresses)) {
            out.printf("InetAddress: %s\n", inetAddress);
        }
       
        out.printf("Up? %s\n", netint.isUp());
        out.printf("Loopback? %s\n", netint.isLoopback());
        out.printf("PointToPoint? %s\n", netint.isPointToPoint());
        out.printf("Supports multicast? %s\n", netint.supportsMulticast());
        out.printf("Virtual? %s\n", netint.isVirtual());
        
        byte[] mac = netint.getHardwareAddress();
        
        out.printf("Hardware address: %s\n",
                    Arrays.toString(mac));
        
        //Print MAC (Hardware address) in HEX format
        if(mac != null){
            StringBuilder sbMac = new StringBuilder();
            for (int i = 0; i < mac.length; i++) {
                sbMac.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? ":" : ""));      
            }
            out.printf("Hardware address (HEX): [%s]\n", sbMac.toString());
        }
                    
        out.printf("MTU: %s\n", netint.getMTU());
        out.printf("\n");
     }
}


reference:
The Java Tutorials - Network Interface Parameters

Related:
Python to get MAC address using uuid, run on Raspberry Pi/Raspbian Jessie
c language to get MAC address, run on Raspberry Pi/Raspbian Jessie

Saturday, February 6, 2016

Java code to listing Network Interface Addresses, run on Raspberry Pi/Raspbian Jessie


The following example program lists all the network interfaces and their addresses on a machine, run on Raspberry Pi 2/Raspbian Jessie.


JavaListInetAddress.java
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;

public class JavaListInetAddress {

    public static void main(String[] args) throws SocketException {
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netint : Collections.list(nets))
            displayInterfaceInformation(netint);
    }
    
    static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
        System.out.printf("Display name: %s\n", netint.getDisplayName());
        System.out.printf("Name: %s\n", netint.getName());
        Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
        for (InetAddress inetAddress : Collections.list(inetAddresses)) {
            System.out.printf("InetAddress: %s\n", inetAddress);
        }
        System.out.printf("\n");
     }
    
}


reference: https://docs.oracle.com/javase/tutorial/networking/nifs/listing.html

Related:
Java code to listing Network Interface Addresses, run on Windows 10
Python code to find my IP address, run on Raspberry Pi/Raspbian Jessie
C example to getting IP address from a network interface, run on Raspberry Pi/Raspbian Jessie

Next:
Java to list Network Interface Parameters (include MAC address)

Saturday, April 11, 2015

Java 8 example: call between Java and Javascript

This example show how to call Javascript function from Java, and call Java method from Javascript.


JavaTryJavaScript.java
package javatryjavascript;

import java.io.FileNotFoundException;
import java.io.FileReader;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class JavaTryJavaScript {
    
    final static String myJavascript = "/home/pi/testJS/newjavascript.js";

    public static void main(String[] args) 
            throws FileNotFoundException, ScriptException, NoSuchMethodException {
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine nashornEngine = scriptEngineManager.getEngineByName("nashorn");
        
        FileReader fileReader = new FileReader(myJavascript);
        nashornEngine.eval(fileReader);
        
        Invocable invocable = (Invocable)nashornEngine;
        invocable.invokeFunction("testJavaScript1", "Hello from Java");
        
    }
    
    public static void JavaCalledFromJS(String s){
        System.out.println("Java method called from JavaScript: " + s);
    }
    
}

The Javascript in a separated file, /home/pi/testJS/newjavascript.js
var testJavaScript1 = function(a){
    print('testJavaScript1, called from Java: ' + a);
    testJavaScript2();
    return;
}

var testJavaScript2 = function(){
    print('testJavaScript2');
    var javaClass = Java.type("javatryjavascript.JavaTryJavaScript");
    javaClass.JavaCalledFromJS("message from JavaScript");
    return;
}

Read dweet.io JSON using Java, develop and run on Raspberry Pi

I have a previous exercise of "Python to send data to Cloud". It can be viewed on browser at: http://dweet.io/follow/helloRaspberryPi_RPi2_vcgencmd.


Or read the dweets in JSON at: https://dweet.io/get/dweets/for/helloRaspberryPi_RPi2_vcgencmd
(Note that dweet.io only holds on to the last 500 dweets over a 24 hour period. If the thing hasn't dweeted in the last 24 hours, its history will be removed.)


Here is a Java exercise to parse the dweets JSON, develop and run on Raspberry Pi 2 with Netbeans IDE. Suppose it can run on any other Java SE supported platform.

JavaDweetIO.java
package javadweetio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JavaDweetIO {

    public static void main(String[] args) {
        
        String myThing = "helloRaspberryPi_RPi2_vcgencmd";
        try {
            JSONObject json = 
                ReadJSON("http://dweet.io/get/dweets/for/" + myThing);

            JSONArray jsonArray_with = json.getJSONArray("with");
            
            for(int i=0; i<jsonArray_with.length(); i++){
                JSONObject jsonObject_with = (JSONObject) jsonArray_with.get(i);
                String created = jsonObject_with.getString("created");
                JSONObject jsonObject_with_content = 
                    jsonObject_with.getJSONObject("content");
                Double RaspberryPi2_core_temp = 
                    jsonObject_with_content.getDouble("RaspberryPi2_core_temp");
                
                System.out.println(created);
                System.out.println(RaspberryPi2_core_temp);
                System.out.println("-----");
            }
            
        } catch (IOException | JSONException e){
            System.out.println(e.toString());
        }
    }

    public static JSONObject ReadJSON(String url) 
            throws IOException, JSONException {
        
        try (InputStream inputStream = new URL(url).openStream()) {
            InputStreamReader inputStreamReader = 
                new InputStreamReader(inputStream, Charset.forName("UTF-8"));
            BufferedReader bufferedReader = 
                new BufferedReader(inputStreamReader);

            StringBuilder jsonBody = new StringBuilder();
            int singleChar;
            while ((singleChar = bufferedReader.read()) != -1) {
                jsonBody.append((char)singleChar);
            }

            JSONObject json = new JSONObject(jsonBody.toString());
            return json;
        }
    }
}


To import org.json in our Java code, we have to Add org.json library, java-json.jar, to NetBeans Java project.




If you want check the JSON online, before you parse it, you can try: http://jsonlint.com/



Monday, March 30, 2015

Java get CPU frequency by "cat /sys/.../scaling_cur_freq"

This example show Java program to get CPU frequency with Linux command "cat /sys/devices/system/cpu/cpu#/cpufreq/scaling_cur_freq", where # is the cpus' number.



Last post show a Python version to get CPU frequency, and the post in my another blog show a Android version. Here is a Java SE version.

JavaRead_scaling_cur_freq.java
package javaread_scaling_cur_freq;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;

public class JavaRead_scaling_cur_freq {

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

    static private void readCpuFreqNow() {
        File[] cpuFiles = getCPUs();
        System.out.println("number of cpu: " + cpuFiles.length);

        for (File cpuFile : cpuFiles) {
            String path_scaling_cur_freq 
                = cpuFile.getAbsolutePath() + "/cpufreq/scaling_cur_freq";
            System.out.println(path_scaling_cur_freq);
            System.out.println(cmdCat(path_scaling_cur_freq));
        }

    }
    
    //run Linux command 
    //$ cat f
    static private String cmdCat(String path){
        StringBuilder stringBuilder = new StringBuilder();
        
        Process process;
        try {
            process = Runtime.getRuntime().exec("cat " + path);
            process.waitFor();
            
            BufferedReader reader = 
                new BufferedReader(new InputStreamReader(process.getInputStream()));
            
            String line;   
            while ((line = reader.readLine())!= null) {
                stringBuilder.append(line).append("\n");
            }
            
        } catch (IOException | InterruptedException ex) {
            Logger.getLogger(JavaRead_scaling_cur_freq.class
                .getName()).log(Level.SEVERE, null, ex);
        }

        return stringBuilder.toString();
    }

    /*
     * Get file list of the pattern
     * /sys/devices/system/cpu/cpu[0..9]
     */
    static private File[] getCPUs() {

        class CpuFilter implements FileFilter {

            @Override
            public boolean accept(File pathname) {
                return Pattern.matches("cpu[0-9]+", pathname.getName());
            }
        }

        File dir = new File("/sys/devices/system/cpu/");
        File[] files = dir.listFiles(new CpuFilter());
        return files;
    }

}


This video show the code build on Raspberry Pi 2 using NetBeans IDE.



The code work on other Linux also, such as Ubuntu. This video show the jar build on Raspberry Pi 2, copy to Ubuntu Linux and run directly.




Related:
- Install NetBeans IDE on Raspberry Pi 2/Raspbian, to program using Java

Wednesday, September 3, 2014

Java serial communication with Arduino Uno with jSSC, on Raspberry Pi

jSSC (Java Simple Serial Connector) - library for working with serial ports from Java. jSSC support Win32(Win98-Win8), Win64, Linux(x86, x86-64, ARM), Solaris(x86, x86-64), Mac OS X 10.5 and higher(x86, x86-64, PPC, PPC64).

This post show a Java program run on Raspberry Pi, using jSSC library, to send message to USB connected Arduino Uno board.


The development platform is a PC running Ubuntu with Netbeans 8, and deploy the program to Raspberry Pi remotely.

- To add jSSC library to our Netbeans Java project, read the post "Install and test java-simple-serial-connector with Arduino".

- The program code is almost same as the code on the page. With 3 seconds delay after serialPort.openPort(), to wait Automatic (Software) Reset on Arduino Uno board.
package java_jssc_uno;

import java.util.logging.Level;
import java.util.logging.Logger;
import jssc.SerialPort;
import jssc.SerialPortException;

public class Java_jSSC_Uno {

    public static void main(String[] args) {
        SerialPort serialPort = new SerialPort("/dev/ttyACM0");
        try {
            System.out.println("Port opened: " + serialPort.openPort());

            try {
                Thread.sleep(3000);
            } catch (InterruptedException ex) {
                Logger.getLogger(Java_jSSC_Uno.class.getName()).log(Level.SEVERE, null, ex);
            }
            
            System.out.println("Params setted: " + serialPort.setParams(9600, 8, 1, 0));
            System.out.println("\"Hello World!!!\" successfully writen to port: " + serialPort.writeBytes("Java_jSSC_Uno".getBytes()));
            System.out.println("Port closed: " + serialPort.closePort());
        }
        catch (SerialPortException ex){
            System.out.println(ex);
        }
    }
    
}

- To deploy to Raspberry Pi remotely with Netbeans 8, refer to the post "Set up Java SE 8 Remote Platform on Netbeans 8 for Raspberry Pi".


For the sketch (and extra info) on Arduino Uno, read the post in my Arduino blog.


Sunday, April 27, 2014

Get number of memory in Java VM

Every Java application has a single instance of class java.lang.Runtime that allows the application to interface with the environment in which the application is running.
  • long freeMemory()
    Returns the amount of free memory in the Java Virtual Machine.
  • long maxMemory()
    Returns the maximum amount of memory that the Java virtual machine will attempt to use.
  • long totalMemory()
    Returns the total amount of memory in the Java virtual machine.
public class testMem {
    
    public static void main(String[] args){
        System.out.println("helloraspberrypi.blogspot.com");
        
        //the total amount of memory in the Java virtual machine
        long totalMem = Runtime.getRuntime().totalMemory();
        //the maximum amount of memory that the Java virtual machine will attempt to use
        long maxMem = Runtime.getRuntime().maxMemory();
        //the amount of free memory in the Java Virtual Machine
        long freeMem = Runtime.getRuntime().freeMemory();
        
        System.out.println("totalMemory() - " + totalMem);
        System.out.println("maxMemory() - " + maxMem);
        System.out.println("freeMemory() - " + freeMem);
        
    }
    
}

We can run java with -Xms and -Xmx options to set Java heap size:
  • -Xms<size> set initial Java heap size
  • -Xmx<size> set maximum Java heap size

Run on Raspberry Pi:

Sunday, February 9, 2014

Get my IP Address using Java

The below Java code, myIP.java, list my IP address.

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

class myIP {
    public static void main(String[] args) {
        System.out.println(getIpAddress());
    }
    
    private static String getIpAddress(){
        String ip = "";
        try {
            Enumeration<NetworkInterface> enumNetworkInterfaces = 
                NetworkInterface.getNetworkInterfaces();
            while(enumNetworkInterfaces.hasMoreElements()){
                NetworkInterface networkInterface = 
                    enumNetworkInterfaces.nextElement();
                Enumeration<InetAddress> enumInetAddress = 
                    networkInterface.getInetAddresses();
                while(enumInetAddress.hasMoreElements()){
                    InetAddress inetAddress = enumInetAddress.nextElement();
                    
                    String ipAddress = "";
                    if(inetAddress.isLoopbackAddress()){
                        ipAddress = "LoopbackAddress: ";
                    }else if(inetAddress.isSiteLocalAddress()){
                        ipAddress = "SiteLocalAddress: ";
                    }else if(inetAddress.isLinkLocalAddress()){
                        ipAddress = "LinkLocalAddress: ";
                    }else if(inetAddress.isMulticastAddress()){
                        ipAddress = "MulticastAddress: ";
                    }
                    
                    ip += ipAddress + inetAddress.getHostAddress() + "\n"; 
                }
            }    
        } catch (SocketException e) {
            ip += "Something Wrong! " + e.toString() + "\n";
        }
        
        return ip;
    }
}

Get my IP Address using Java
Get my IP Address using Java

Check System Properties of Raspberry Pi, using Java

Once installed Java 8 release candidate on Raspberry Pi, we can create a java program, listProperties.java, to list System Properties, to verify the installation.

listProperties.java
import java.util.Properties;
import java.util.Set;

class listProperties {
    
    public static void main(String[] args) {
        
        Properties properties = System.getProperties();
        System.out.println(properties.toString());
        System.out.println("\n");
        
        Set<String> setPropertyNames = 
            properties.stringPropertyNames();
        for (String propName : setPropertyNames) {
            System.out.println(
                propName + " : " +
                System.getProperty(propName));
        }
    }
}

To compile listProperties.java
$ javac listProperties.java

Run generated listProperties.class
$ java listProperties

The result will be something like:



pi@raspberrypi ~/worksJava $ java listProperties
{java.runtime.name=Java(TM) SE Runtime Environment, sun.boot.library.path=/opt/jdk1.8.0/jre/lib/arm, java.vm.version=25.0-b69, java.vm.vendor=Oracle Corporation, java.vendor.url=http://java.oracle.com/, path.separator=:, java.vm.name=Java HotSpot(TM) Client VM, file.encoding.pkg=sun.io, user.country=GB, sun.java.launcher=SUN_STANDARD, sun.os.patch.level=unknown, java.vm.specification.name=Java Virtual Machine Specification, user.dir=/home/pi/worksJava, java.runtime.version=1.8.0-b128, java.awt.graphicsenv=sun.awt.X11GraphicsEnvironment, java.endorsed.dirs=/opt/jdk1.8.0/jre/lib/endorsed, os.arch=arm, java.io.tmpdir=/tmp, line.separator=
, java.vm.specification.vendor=Oracle Corporation, os.name=Linux, sun.jnu.encoding=UTF-8, java.library.path=/usr/java/packages/lib/arm:/lib:/usr/lib, java.specification.name=Java Platform API Specification, java.class.version=52.0, sun.management.compiler=HotSpot Client Compiler, os.version=3.10.28+, user.home=/home/pi, sun.arch.abi=gnueabihf, user.timezone=Asia/Hong_Kong, java.awt.printerjob=sun.print.PSPrinterJob, file.encoding=UTF-8, java.specification.version=1.8, java.class.path=., user.name=pi, java.vm.specification.version=1.8, sun.java.command=listProperties, java.home=/opt/jdk1.8.0/jre, sun.arch.data.model=32, user.language=en, java.specification.vendor=Oracle Corporation, awt.toolkit=sun.awt.X11.XToolkit, java.vm.info=mixed mode, java.version=1.8.0, java.ext.dirs=/opt/jdk1.8.0/jre/lib/ext:/usr/java/packages/lib/ext, sun.boot.class.path=/opt/jdk1.8.0/jre/lib/resources.jar:/opt/jdk1.8.0/jre/lib/rt.jar:/opt/jdk1.8.0/jre/lib/sunrsasign.jar:/opt/jdk1.8.0/jre/lib/jsse.jar:/opt/jdk1.8.0/jre/lib/jce.jar:/opt/jdk1.8.0/jre/lib/charsets.jar:/opt/jdk1.8.0/jre/lib/jfr.jar:/opt/jdk1.8.0/jre/classes, java.vendor=Oracle Corporation, file.separator=/, java.vendor.url.bug=http://bugreport.sun.com/bugreport/, sun.io.unicode.encoding=UnicodeLittle, sun.cpu.endian=little, sun.cpu.isalist=}



java.runtime.name : Java(TM) SE Runtime Environment

sun.boot.library.path : /opt/jdk1.8.0/jre/lib/arm
java.vm.version : 25.0-b69
java.vm.vendor : Oracle Corporation
java.vendor.url : http://java.oracle.com/
path.separator : :
java.vm.name : Java HotSpot(TM) Client VM
file.encoding.pkg : sun.io
user.country : GB
sun.java.launcher : SUN_STANDARD
sun.os.patch.level : unknown
java.vm.specification.name : Java Virtual Machine Specification
user.dir : /home/pi/worksJava
java.runtime.version : 1.8.0-b128
java.awt.graphicsenv : sun.awt.X11GraphicsEnvironment
java.endorsed.dirs : /opt/jdk1.8.0/jre/lib/endorsed
os.arch : arm
java.io.tmpdir : /tmp
line.separator : 


java.vm.specification.vendor : Oracle Corporation

os.name : Linux
sun.jnu.encoding : UTF-8
java.library.path : /usr/java/packages/lib/arm:/lib:/usr/lib
java.specification.name : Java Platform API Specification
java.class.version : 52.0
sun.management.compiler : HotSpot Client Compiler
os.version : 3.10.28+
user.home : /home/pi
sun.arch.abi : gnueabihf
user.timezone : Asia/Hong_Kong
java.awt.printerjob : sun.print.PSPrinterJob
file.encoding : UTF-8
java.specification.version : 1.8
user.name : pi
java.class.path : .
java.vm.specification.version : 1.8
sun.arch.data.model : 32
java.home : /opt/jdk1.8.0/jre
sun.java.command : listProperties
java.specification.vendor : Oracle Corporation
user.language : en
awt.toolkit : sun.awt.X11.XToolkit
java.vm.info : mixed mode
java.version : 1.8.0
java.ext.dirs : /opt/jdk1.8.0/jre/lib/ext:/usr/java/packages/lib/ext
sun.boot.class.path : /opt/jdk1.8.0/jre/lib/resources.jar:/opt/jdk1.8.0/jre/lib/rt.jar:/opt/jdk1.8.0/jre/lib/sunrsasign.jar:/opt/jdk1.8.0/jre/lib/jsse.jar:/opt/jdk1.8.0/jre/lib/jce.jar:/opt/jdk1.8.0/jre/lib/charsets.jar:/opt/jdk1.8.0/jre/lib/jfr.jar:/opt/jdk1.8.0/jre/classes
java.vendor : Oracle Corporation
file.separator : /
java.vendor.url.bug : http://bugreport.sun.com/bugreport/
sun.cpu.endian : little
sun.io.unicode.encoding : UnicodeLittle
sun.cpu.isalist : 




Tuesday, December 31, 2013

Java exercise: Schedule tasks run in a background thread using java.util.Timer

This example run a background task repeatly in 5 seconds to print system time.
java.util.Timer
Example of using java.util.Timer
import java.util.Timer;
import java.util.TimerTask;
import java.io.IOException;
import java.util.Date;

/**
 * @web helloraspberrypi.blogspot.com
 */
class testTimer{

    public static void main(String[] args) {
        Timer timer = new Timer(); 
        TimerTask timeTask = new TimerTask() {
            
            @Override
            public void run() {
                System.out.println((new Date()).toString());
            }
        };
        timer.schedule(timeTask, 0, 5000);
        
        System.out.println("Press ENTER to exit");
        
        try{
            System.in.read();
        }catch(IOException ex){
            System.out.println(ex.toString());
        }
        
        System.out.println("-BYE-");
        timer.cancel();
    }
}


Wednesday, December 25, 2013

Read Raspberry Pi system temperature in Java

This exercise show how to read Pi's system temperature in Java, using ProcessBuilder with command of "vcgencmd measure_temp".

Read Raspberry Pi system temperature in Java
Read Raspberry Pi system temperature in Java

import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Scanner;

/**
 * @web helloraspberrypi.blogspot.com
 */
public class readTemp {

    public static void main(String[] args) {

        // Example to run "dir" in Windows
        String[] command = {"vcgencmd", "measure_temp"};
        StringBuilder cmdReturn = new StringBuilder();
        try {
            ProcessBuilder processBuilder = new ProcessBuilder(command);
            Process process = processBuilder.start();
            
            try (InputStream inputStream = process.getInputStream()) {
                int c;
                while ((c = inputStream.read()) != -1) {
                    cmdReturn.append((char) c);
                }
            }
            
            System.out.println(cmdReturn.toString());
            String stringTemp = measure_temp_toString(cmdReturn.toString());
            System.out.println("Get the numerical part as String: " + stringTemp);
            System.out.println("converte to float: " + cnvStringToFloat(stringTemp));

        } catch (IOException ex) {
            System.out.println(ex.toString());
        }
        
    }
    
    private static String measure_temp_toString(String src){
        return src.replaceAll("[^0123456789.]", "");
    }
    
    private static float cnvStringToFloat(String src){

        float result = (float)0.0;
        Scanner scanner = new Scanner(src);
        while(scanner.hasNext()){
            if(scanner.hasNextFloat()){
                result = scanner.nextFloat();
            }else{
                scanner.next(); //ignore
            }
        }
        return result;
    }
    
}

Sunday, December 22, 2013

Example of programming with java-gnome

Once installed libjava-gnome-java, we can prepare our "Hello World" using java-gnome. Basically it have the same function as "GTK+ exercise: GtkBox - A container box", a basic GTK+ Window with 3 Labels.

helloGnome
helloGnome
Edit helloGnome.java
import org.gnome.gtk.Gtk;
import org.gnome.gtk.Window;
import org.gnome.gtk.Widget;
import org.gnome.gdk.Event;
import org.gnome.gtk.Label;
import org.gnome.gtk.HBox;

public class helloGnome
{
    public static void main(String[] args) {
        final Window window;
        final HBox hBox;
        final Label label1, label2, label3;

        Gtk.init(args);

        window = new Window();
        window.setTitle("Hello Raspberry Pi - java-gnome exercise");
        window.connect(new Window.DeleteEvent() {
            public boolean onDeleteEvent(Widget source, Event event) {
                Gtk.mainQuit();
                return false;
            }
        });

        label1 = new Label("Label 1");
        label2 = new Label("Label 2");
        label3 = new Label("Label 3");

        hBox = new HBox(false, 3);
        hBox.add(label1);
        hBox.add(label2);
        hBox.add(label3);

        window.add(hBox);
        window.showAll();

        Gtk.main();
    }
}


Compile it with the command:
$ javac -classpath /usr/share/java/gtk-4.1.jar helloGnome.java

and run it:
$ java -classpath /usr/share/java/gtk-4.1.jar:. helloGnome

Saturday, December 21, 2013

Java program with Swing GUI run on Raspberry Pi

This exercise create a hello.java with Swing GUI, develop and run on Raspberry Pi with JDK 8 Early Access Releases.

Java program with Swing GUI run on Raspberry Pi
Java program with Swing GUI run on Raspberry Pi
hello.java
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
 
/**
 * @web http://helloraspberrypi.blogspot.com/
 */
public class hello extends JFrame 
    implements ActionListener{
 
    JTextArea textArea;
    JButton buttonHello;
     
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
 
    private static void createAndShowGUI() {
        hello myFrame = new hello();
 
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         
        myFrame.prepareUI();
 
        myFrame.pack();
        myFrame.setVisible(true);
    }
     
    private void prepareUI(){
        textArea = new JTextArea();
        textArea.setEditable(false);
        JScrollPane panel = new JScrollPane(textArea);
        panel.setPreferredSize(new Dimension(300, 100));
         
        buttonHello = new JButton("Hello");
        buttonHello.addActionListener(this);
         
        getContentPane().add(panel, BorderLayout.CENTER);
        getContentPane().add(buttonHello, BorderLayout.PAGE_END);
    }
 
    @Override
    public void actionPerformed(ActionEvent e) {
        textArea.setText("Hello from Raspberry Pi");
    }

}

Compile it:
$ javac hello.java

Run:
$ java hello



Friday, December 20, 2013

Java exercise - Client and Server example III, run socket operation in background thread

This exercise implement socket operation of host in background thread, modify from last exercise, "ServerSocket stay in loop".

run socket operation in background thread
run socket operation in background thread
host.java
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

public class host {

    public static void main(String srgs[]) {

        int count = 0;

        //hard code to use port 8080
        try (ServerSocket serverSocket = new ServerSocket(8080)) {
            
            System.out.println("I'm waiting here: " + serverSocket.getLocalPort());
            
            while (true) {
                
                try {
                    Socket socket = serverSocket.accept();
                            
                    count++;
                    System.out.println("#" + count + " from "
                            + socket.getInetAddress() + ":" 
                            + socket.getPort());
                    
                    /*  move to background thread
                    OutputStream outputStream = socket.getOutputStream();
                    try (PrintStream printStream = new PrintStream(outputStream)) {
                        printStream.print("Hello from Raspberry Pi, you are #" + count);
                    }
                    */
                    HostThread myHostThread = new HostThread(socket, count);
                    myHostThread.start();
                    
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }
            }
        } catch (IOException ex) {
            System.out.println(ex.toString());
        }
    }
    
    private static class HostThread extends Thread{
        
        private Socket hostThreadSocket;
        int cnt;
        
        HostThread(Socket socket, int c){
            hostThreadSocket = socket;
            cnt = c;
        }

        @Override
        public void run() {

            OutputStream outputStream;
            try {
                outputStream = hostThreadSocket.getOutputStream();
                
                try (PrintStream printStream = new PrintStream(outputStream)) {
                        printStream.print("Hello from Raspberry Pi in background thread, you are #" + cnt);
                }
            } catch (IOException ex) {
                Logger.getLogger(host.class.getName()).log(Level.SEVERE, null, ex);
            }finally{
                try {
                    hostThreadSocket.close();
                } catch (IOException ex) {
                    Logger.getLogger(host.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}


Keep using the client.java in last exercise of "client and server to communicate using Socket".

Tuesday, December 17, 2013

Java exercise - Client and Server example II, ServerSocket stay in loop

In the previous exercise of "client and server to communicate using Socket", the host.java stay waiting request from client.java, and terminate after responsed. In this step, it's modified to stay in loop, for next request; until user press Ctrl+C to terminate the program.

host stey in loop
host stey in loop, until Ctrl+C.

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class host {

    public static void main(String srgs[]) {

        int count = 0;

        //hard code to use port 8080
        try (ServerSocket serverSocket = new ServerSocket(8080)) {
            System.out.println("I'm waiting here: " 
                + serverSocket.getLocalPort());
            
            System.out.println(
                "This program will stay monitoring port 80.");
            System.out.println(
                "Until user press Ctrl+C to terminate.");
            
            while (true) {
                try (Socket socket = serverSocket.accept()) {
                    count++;
                    System.out.println("#" + count + " from "
                            + socket.getInetAddress() + ":" 
                            + socket.getPort());
                    OutputStream outputStream = socket.getOutputStream();
                    try (PrintStream printStream = 
                        new PrintStream(outputStream)) {
                            printStream.print(
                                "Hello from Raspberry Pi, you are #" 
                                + count);
                    }
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }
            }
        } catch (IOException ex) {
            System.out.println(ex.toString());
        }
    }
}

Keep using the client.java in last exercise of "client and server to communicate using Socket".



Next exercise: - Client and Server example III, run socket operation in background thread.

Sunday, December 15, 2013

Find a free port using Java with ServerSocket(0)

Use the constructor ServerSocket(int port) of java.net.ServerSocket class with 0 to request a free port automatically, typically from an ephemeral port range. This port number can then be retrieved by calling getLocalPort.

Example:
import java.net.ServerSocket;
import java.io.IOException;

class checkSocket
{
    public static void main(String srgs[])
    {
        System.out.println("Hello Raspberry Pi");
        
        try{
            ServerSocket socket0 = new ServerSocket(0);
            System.out.println("Automatically allocated port: " 
                                + socket0.getLocalPort());
        }catch(IOException e){
            System.out.println(e.toString());
        }
        
    }
}

Find a free port using Java with ServerSocket(0)
Find a free port using Java with ServerSocket(0)

Wednesday, December 11, 2013

Run system command and read output using Java

The exercise run system command with StringBuilder(), and read the output with InputStream.

import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @org java-buddy.blogspot.com
 * @web helloraspberrypi.blogspot.com
 */
public class df {

    public static void main(String[] args) {

        // Example to run "dir" in Windows
        String[] command = {"df", "-h", "/"};
        StringBuilder cmdReturn = new StringBuilder();
        try {
            ProcessBuilder processBuilder = new ProcessBuilder(command);
            Process process = processBuilder.start();
            
            try (InputStream inputStream = process.getInputStream()) {
                int c;
                while ((c = inputStream.read()) != -1) {
                    cmdReturn.append((char) c);
                }
            }
            System.out.println(cmdReturn.toString());

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

Run system command and read output using Java

The code from Java-Buddy: ProcessBuilder to create operating system processes

Related: Read Pi's system temperature in Java, using ProcessBuilder with command of "vcgencmd measure_temp".