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

Saturday, October 3, 2015

Monday, September 14, 2015

Java example - scan connected IP in the same network

Last post advise use Advanced IP Scanner to scan connected host in the same network. Here is a Java example to scan connected IP in the same network, using isReachable(int timeout) method of java.net.InetAddress.


public boolean isReachable(int timeout) throws IOException

Test whether that address is reachable. Best effort is made by the implementation to try to reach the host, but firewalls and server configuration may block requests resulting in a unreachable status while some specific ports may be accessible. A typical implementation will use ICMP ECHO REQUESTs if the privilege can be obtained, otherwise it will try to establish a TCP connection on port 7 (Echo) of the destination host.

The timeout value, in milliseconds, indicates the maximum amount of time the try should take. If the operation times out before getting an answer, the host is deemed unreachable. A negative value will result in an IllegalArgumentException being thrown.


JavaIpScanner.java
package javaipscanner;

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

public class JavaIpScanner {

    /*
    Example to scan ip 192.168.1.100~120
    check if any ip is reachable, means connected host
    */
    static final String SUB_NET = "192.168.1.";

    public static void main(String[] args) {
        scanHost(SUB_NET, 100, 120);
    }

    private static void scanHost(String subnet, int lower, int upper) {
        final int timeout = 3000;

        for (int i = lower; i <= upper; i++) {
            String host = subnet + i;
            try {
                InetAddress inetAddress = InetAddress.getByName(host);
                
                if (inetAddress.isReachable(timeout)){
                    System.out.println(inetAddress.getHostName() 
                            + " isReachable");
                    System.out.println(inetAddress.toString());
                    System.out.println("--------------------");
                }
                
            } catch (UnknownHostException ex) {
                Logger.getLogger(JavaIpScanner.class.getName())
                        .log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(JavaIpScanner.class.getName())
                        .log(Level.SEVERE, null, ex);
            }
        }
    }

}



Related:
- Android version Scan Reachable IP to discover devices in network

Thursday, September 10, 2015

Remote run Java on Raspberry Pi, host from NetBeans on Windows 10

This video show how to develop Java application with NetBeans IDE 8.0.2 running on Windows 10, create Remote Java SE platform, remote run/debug on Raspberry Pi/Raspbian Wheezy .




The following java code list system by calling System.getProperties().
package javaapplication14;

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

public class JavaApplication14 {

    public static void main(String[] args) {

        System.out.println("\nSystem Properties\n");
        System.out.println("=================\n");
        
        Properties properties = System.getProperties();
        System.out.println(properties.toString());
        System.out.println("\n");

        Enumeration<String> prop
                = (Enumeration<String>) properties.propertyNames();

        while (prop.hasMoreElements()) {
            String propName = prop.nextElement();
            System.out.println(
                    propName + " : "
                    + System.getProperty(propName));
        }
    }

}


How it run on Windows 10/Intel i5 vs Raspbian/Raspberry Pi 2.




Updated@2015-10-04: Appliable on Raspbian Jessie.

Saturday, April 11, 2015

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/



Add org.json library, java-json.jar, to NetBeans Java project. Run on Raspberry Pi

In next example, I will retrieve my dweet.io thing in JSON format. I will use JSON in Java (org.json) to parse JSON. The java-json.jar can be download here: http://www.java2s.com/Code/Jar/j/Downloadjavajsonjar.htm

This video show how to download and add java-json.jar (org.json) to Netbeans Java project, run on Raspberry Pi 2/Raspbian. Suppose it is same in NetBeans run on other platforms.

Monday, March 23, 2015

Set JAVA_HOME for Raspbian pre-loaded java 1.8.0

Current Raspbian (version 2015-02-16) preload with java 1.8.0. By default, both java and javac are in PATH (that's why we can run java and javac directly), but no JAVA_HOME set.

This video show how to verify java location, set JAVA_HOME in .bashrc, and verify using jEdit.


- By default, java should be in /usr

- Edit hidden file .bashrc with command:
$ nano .bashrc

- Add the line:
export JAVA_HOME=/usr

- Save and reboot.


Sunday, March 22, 2015

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

NetBeans IDE is the official IDE for Java 8. With quad-core ARM Cortex-A7 CPU on Raspberry Pi 2, pre-loaded Java 8 on Raspbian, it's easy to install NetBeans 8 on Raspberry Pi.


Visit NetBeans Download page (https://netbeans.org/downloads/), select Platform of OS Independent Zip, download and un-zip to any folder you want.

Switch to the unzipped /netbeans/bin folder, run the executable file netbeans:
$ ./netbeans

This video show how to download and install NetBeans IDE 8.0.2 on Raspberry Pi 2.



It is seem JavaFX not supported currently




x Error of failed request: BadMatch (invalid parameter attributes)

In the above demo video, I log-in Raspberry Pi 2 remotely with xrdp run on RPi 2, and remmina (Remote Desktop Client) on another PC running Ubuntu Linux.

Originally, I set Color depth of High color (15 bpp), it work once only. After then, I run netbeans next time, it fail with following error:

x Error of failed request: BadMatch (invalid parameter attributes)
  Major opcode of failed request: 72 (x_PutImage)
  Serial number of failed request: 51
  Current serial number in output stream: 55

To fix it in my case, set Color depth of High color (16 bpp).



Next:
- Install C/C++ plugins for NetBeans on Raspberry Pi 2/Raspbian

Related:
- A example of Java to get CPU frequency, build with NetBeans on Raspberry Pi, the jar run on other Linux machine also.

Thursday, March 19, 2015

Install Eclipse JDT on Raspberry Pi 2/Raspbian


To install Eclipse with JDT (Java development tools) on Raspberry Pi 2/Raspbian, enter the commands:
$ sudo apt-get install eclipse
$ sudo apt-get install eclipse-jdt

This video show how to:


Please notice:
- The installed version of Eclipse 3.8.0
- After installed, the default java and javac will be changed to 1.6.0 of OpenJDK!


This video show example of "Hello World" using Eclipse JDT.

Thursday, November 27, 2014

Code Java on the Raspberry Pi, BlueJ on the Raspberry Pi

BlueJ, start from version 3.14, fully supports the Raspberry Pi. BlueJ is a Java development environment that allows development as well as program execution on the Pi.

BlueJ on the Raspberry Pi provides full access to hardware attached to the Raspberry Pi via the open source Pi4J library, from the the familiar Java SE language, including the new Java 8.

link:
http://bluej.org/raspberrypi/index.html



Current issue of Java Magazine, november/december 2014, have a charter of "Code Java on Raspberry Pi" introduce how BlueJ brings Java SE 8 development directly to the Raspberry Pi.



Saturday, September 6, 2014

java-google-translate-text-to-speech, unofficial API for Google Translate in Java.

java-google-translate-text-to-speech is API unofficial with the main features of Google Translate in Java. I will add text-to-speech (tts) function in my next Yahoo Weather exercise.

This video show how to download jars, and add library to Netbeans Java project.

Friday, September 5, 2014

Download and add Apache HttpComponents jar to Netbeans Project

In the coming post, I have to use Apache HttpComponents jar in my code. The Apache HttpComponents™ project is responsible for creating and maintaining a toolset of low level Java components focused on HTTP and associated protocols.

It can be download here: http://hc.apache.org/.

This video show how to download and add the Apache HttpComponents jar to your project in Netbeans.

Sunday, August 10, 2014

Cross compile Java/Swing program for Raspberry Pi, with Netbeans 8

This video show how to cross compile Java/Swing program for Raspberry Pi, on PC running Netbeans.



Currently, I cannot remote run the Java/Swing program on Raspberry Pi within Netbeans IDE, caused by "No X11 DISPLAY variable was set, but this program performed an operation which requires it". But it can create the runnable jar in Raspberry Pi. You can login Raspberry Pi and run the jar locally.

You need to:
Install JDK 8 on Raspberry Pi
Set up Java SE 8 Remote Platform on Netbeans 8 for Raspberry Pi
- and know how to Run/Build JavaFX application on Raspberry Pi remotely from Netbeans 8

Code of this example:
package helloworldswing;

import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class HelloWorldSwing {

    private static void createAndShowGUI() {

        JFrame frame = new JFrame("Hello Swing@Raspberry Pi");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setPreferredSize(new Dimension(400, 300));

        JLabel label = new JLabel();
        label.setText(
            "Hello: " 
            + System.getProperty("os.arch") + "/"
            + System.getProperty("os.name"));
        
        frame.getContentPane().add(label);

        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
    
}



Updated@2015-12-06: Solution of "No X11 DISPLAY variable was set, but this program performed an operation which requires it":

Refer to karczas' comment in YouTube video, The solution of 0:50 error (No X11 DISPLAY variable was set, but this program performed an operation which requires it) which will allow you to run and debug GUI application directly from NetBeans and display their content on your RaspPi (or BeagleBone Black): 
https://mkarczewski.wordpress.com/2015/12/05/netbeans-remote-java-arm-debugging-with-gui



Friday, August 1, 2014

Java 8 and Embedded JavaFX

Presentation on using the new embedded features in Java 8, including JavaFX on devices like the Raspberry Pi and Lego Mindstorms EV3. Also covers JavaFX on tablets and smartphones.

Tuesday, April 8, 2014

Internet of Things, Java and Raspberry Pi

In this session, we invited Oracle engineer Gary Collins, who is responsible for testing and running Java SE Embedded in many many different types of boards, single board computers, plug computers and other. Vinicius Senger and Gary Collins will be talking about IoT and how all those different types of small computers can help us to implement nice solutions. Gary will be showing about at least 10 different computers and they will be sharing experiences like the JavaOne 2013 chess machine and Vinicius's new project involving sailing boats and IoT!

Internet of Things, Java and Raspberry Pi

Thursday, March 27, 2014

Getting Started with JavaFX Embedded on a Raspberry Pi

Learn how to quickly get a JavaFX simple application up and running on a Raspberry Pi development board.

Java 8 on the Raspberry Pi

Watch how a full version of Java SE & JavaFX run on Raspberry Pi.

Saturday, March 22, 2014

Video playlist - IoT and Java

Playlist for IoT and Java, include the following title:
  • Introduction to the Internet of Things
    What are some of the applications and devices in IoT space? In which industries are we seeing innovations? What kind of hardware can you use? What do you need to create your own project?
  • Java and the Internet of Things
    An Overview of the Java Embedded Platform, including Java SE Embedded, Java ME Embedded, and more.
  • Introduction to Raspberry Pi
    What is the Raspberry Pi? What do you need to install?
  • Java Embedded and Raspberry Pi - Part 1
  • Java Embedded and Raspberry Pi - Part 2
  • Gemalto Board Demo
    Build a Gemalto app and submit it to IoT Developer Challenge 

Enter the IoT Developer Challenge by May 30th, 2014 www.java.net/challenge.

Tuesday, March 18, 2014

Install Oracle JDK 8 on Raspberry Pi

This post show how to download Oracle JDK 8 on a host PC running Ubuntu Linux, copy to, install and set default java and javac on Raspberry Pi.


Visit http://www.oracle.com/technetwork/java/javase/downloads/index.html, click the download button of Java Platform (JDK) 8. Click to Accept License Agreement, download jdk-8-linux-arm-vfp-hflt.tar.gz for Linux ARM v6/v7 Hard Float ABI.

Open terminal, enter the command to copy the download file to Raspberry Pi using scp.
$ scp jdk-8-linux-arm-vfp-hflt.tar.gz pi@<Raspberry Pi>:

Log-in Raspberry Pi, enter the command to extract jdk-8-linux-arm-vfp-hflt.tar.gz to /opt directory.
$ sudo tar zxvf jdk-8-linux-arm-vfp-hflt.tar.gz -C /opt

Set default java and javac to the new installed jdk8.
$ sudo update-alternatives --install /usr/bin/javac javac /opt/jdk1.8.0/bin/javac 1
$ sudo update-alternatives --install /usr/bin/java java /opt/jdk1.8.0/bin/java 1

$ sudo update-alternatives --config javac
$ sudo update-alternatives --config java

After all, verify with the commands with -verion option.
$ java -version
$ javac -version

Monday, March 10, 2014

FREE Oracle Online Course: Develop Java Embedded Applications Using a Raspberry Pi

The FREE Oracle Massive Open Online Course: Develop Java Embedded Applications Using a Raspberry Pi is now open for enrollment, will start March 31st!

Java Embedded leverages your experience with Java to open the world of the Internet of Things by providing direct access to electronic sensors and mechanical devices.

This free course, designed for Java developers, is delivered over 5-weeks. Take the course at your own pace - weekly we will add new lessons, quizzes and homework assignments.

You will work on a real-world application to:

  • Read input data from switches and drive LED's using the GPIO interface
  • Read temperature and barometric pressure from an I2C device
  • Read the device's current location using a GPS UART device
  • Store and manage data collected
  • Report data to a client through a variety of communication options
  • And more!

To Enroll...