Saturday 22 February 2014

JavaFX Create a button

Create a simple JavaFX application which displays a button.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;


public class TestApp extends Application {

 @Override
 public void start(Stage primaryStage) throws Exception {
  primaryStage.setWidth(600);
  primaryStage.setHeight(400);
  
  Button playButton = new Button("Button");
  Group group = new Group();
  group.getChildren().add(playButton);
  BorderPane root = new BorderPane();
  root.setCenter(group);
  Scene scene = new Scene(root);
  primaryStage.setScene(scene);
  
  primaryStage.show();
 }
 
 public static void main(String[] args) {
  launch(args);
 }

}

Friday 21 February 2014

Java - Check if X509Certificate is a CA certificate

How to check in Java if an X509Certificate is a Certificate Authority trust certificate
 public boolean isCA(X509Certificate x509Cert) {
  if(x509Cert.getBasicConstraints() != -1) {
   return true;
  }
  return false;
 }

Saturday 8 February 2014

Create Simple Soap Messages with JAXB

I want to create a SOAP Message with Java. I will use JAXB to construct the SOAP message.



  ...
  ...



  ...
  ...
 


We'll start with creating the soap envelope. First we will create two packages, tutorial, and tutorial.soap. tutorial will contain the main file. tutorial.soap will contain the JAXB files that will be used to construct the SOAP messages. We will start by creating a skeleton for the SOAP Envelope. tutorial.soap.SoapEnvelope.java
package tutorial.soap;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="envelope")
public class SoapEnvelope {

}
We'll create the class which creates the SoapEnvelope using JAXB and converts it to a string. tutorial.Test.java
package tutorial;

import java.io.StringWriter;

import tutorial.soap.SoapEnvelope;

public class Test {

 public static void main(String[] args) {
  SoapEnvelope envelope = new SoapEnvelope();
  
  try {            
            javax.xml.bind.JAXBContext jaxbCtx = javax.xml.bind.JAXBContext.newInstance(envelope.getClass().getPackage().getName());
            javax.xml.bind.Marshaller marshaller = jaxbCtx.createMarshaller();
            marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_ENCODING, "UTF-8"); 
            marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            
            StringWriter writer = new StringWriter();
            
            marshaller.marshal(envelope, writer);
            
            System.out.println(writer.toString());
  }
  catch(Exception e) {
   e.printStackTrace();
  }
 }
}
This creates the following SOAP Message



Now we will create the namespace, xmlns:SOAP-ENV="http://www.w3.org/2001/12/soap-envelope". To do this, create a new Java file in the tutorial.soap package called package-info.java
@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.w3.org/2001/12/soap-envelope", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED,
        xmlns={@XmlNs(prefix="soap-env", namespaceURI="http://www.w3.org/2001/12/soap-envelope")})

package tutorial.soap;

import javax.xml.bind.annotation.XmlNs;
This will create the following XML


Next we will create the SOAP-ENV:encodingStyle="http://www.w3.org/2001/12/soap-encoding" attribute. To do this, add an XmlAttribute to the SoapEnvelope class.
package tutorial.soap;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="envelope")
public class SoapEnvelope {
 @XmlAttribute(name="SOAP-ENV:encodingStyle")
 private String soapEnvEncodingStyle;
 
 public SoapEnvelope() {
  soapEnvEncodingStyle = "http://www.w3.org/2001/12/soap-encoding";
 }
}
That will create the following SOAP Message




Now we will create the Soap Header and the SoapBody. For this we will add two Strings to the SoapEnvelope, soapHeader and soapBody. Will initialize the strings in the constructor.
package tutorial.soap;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="envelope")
public class SoapEnvelope {
 @XmlAttribute(name="SOAP-ENV:encodingStyle")
 private String soapEnvEncodingStyle;
 
 @XmlElement(name="header")
 private String soapHeader;
 
 @XmlElement(name="body")
 private String soapBody;
 
 public SoapEnvelope() {
  soapEnvEncodingStyle = "http://www.w3.org/2001/12/soap-encoding";
  soapHeader = new String();
  soapBody = new String();
 }
}
This creates the following SOAP Message.


    
    

Thursday 6 February 2014

Using ANT on Raspberry Pi

Install the Java Runtime
pi@raspberrypi ~/testProject $ sudo apt-get install openjdk-7-jre
Install the Java Development Kit
pi@raspberrypi ~/testProject $ sudo apt-get install openjdk-7-jdk

Check where Java is installed
pi@raspberrypi ~/testProject $ which java
It was installed in /usr/bin/java on my Pi
Set up the JAVA_HOME environment variable
pi@raspberrypi ~/testProject $ export JAVA_HOME=/usr 
Install ANT
pi@raspberrypi ~/testProject $ sudo apt-get install ant
Make a directory for the Java project
pi@raspberrypi ~/testProject $ mkdir ~/testProject 
Change to the testProject directory
pi@raspberrypi ~/testProject $ cd ~/testProject 
Create a simple Java file Test.java. This just prints a message saying "Test.java is running".
public class Test {
        public static void main(String[] args) {
                System.out.println("Test.java is running");
        }
}

Create an ANT build file, build.xml

        
                
        

There is just one target in the build file to compile the source code. You can run the build file with ant by just running ant
pi@raspberrypi ~/testProject $ ant
After this finishes building, check the contents of the directory for the java class file
pi@raspberrypi ~/testProject $ ls
build.xml Test.class Test.java
Run the Java program
pi@raspberrypi ~/testProject $ java Test
Test.java is running

Java Web Services on Raspberry Pi

These are the steps for setting up a Simple Java Web Service on the Raspberry Pi.
The Raspberry Pi might not be the most suitable device for hosting a web service but it is suitable for educational purposes.

http://www.javatutoronline.com/webservice/Axis2-Web-Service.jsp
http://axis.apache.org/axis2/java/core/docs/quickstartguide.html

Install Java
Install the java run time environment and the java development kit
sudo apt-get install openjdk-7-jre
sudo apt-get install openjdk-7-jdk

Check where java is installed
pi@raspberrypi:~/webService$ which java
/usr/bin/java

Then set up the JAVA_HOME environment variable
export JAVA_HOME=/usr

Install Tomcat
sudo apt-get install tomcat7

Install ANT
sudo apt-get install ant

Install AXIS2
Download the axis2 file (attached to this page) and unzip the axis2 to /home/pi

Set up the AXIS2_HOME environment variable
export AXIS2_HOME=/home/pi/axis2-1.6.2

Go to $AXIS2_HOME/webapp and run ant create.war
cd $AXIS2_HOME/webapp
ant create.war

Copy the axis2.war file to tomcat directory
sudo cp $AXIS2_HOME/dist/axis2.war /var/lib/tomcat7/webapps

Restart tomcat to pick up the axis2 war file
sudo /etc/init.d/tomcat7 restart

Go to the axis2 webpage
go to http://<ipaddress>:8080/axis2

You should see the axis webpage. click on the validate link. This will show you if the system is configured correctly

Create the Web Service

First, create a directory META-INF and create a services.xml file with the following contents.
<service name="GetDate" scope="application">
        <description>
                Get the date
        </description>
        <parameter name="ServiceClass" locked="false">
                test.GetDate
        </parameter>
        <operation name="getDate">
                <messageReceiver class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
        </operation>
</service>

Create a directory, test and create the java file, GetDate.java in it
package test;

import java.util.Calendar;

public class GetDate {
        public String getDate() {
                Calendar cal = Calendar.getInstance();
                int year = cal.get(Calendar.YEAR);
                int month = cal.get(Calendar.MONTH) + 1;
                int day = cal.get(Calendar.DAY_OF_MONTH);

                String date = String.format("%02d", day) + "/" +
                                String.format("%02d", month) + "/" + year;
                return date;
        }
}

Compile the java file
javac test/GetDate.java

If you need any external jars, make sure to place the jar files in a lib directory

Create the aar file
jar -cvf GetDate.aar *

Copy the aar file to the AXIS2 services directory
sudo cp GetDate.aar /var/lib/tomcat7/webapps/axis2/WEB-INF/services

There is no need to restart Tomcat, AXIS2 will pick up the changes automatically.
Go to the the following URL
http://<ip address of Pi>:8080/axis2/services/listServices

You should see the GetDate service. If you click on the GetDate link, you will be redirected to the WSDL.
http://<ip address of Pi>:8080/axis2/services/GetDate?wsdl

Creating the client

Import the WSDL
wsimport -keep -s src http://192.168.2.4:8080/axis2/services/GetDate?wsdl

With the generated files, create the following client that queries the web service
import test.GetDate_Service;

public class TestGetDateWebService {


public static void main(String[] args) {
GetDate_Service service = new GetDate_Service();
String response = service.getGetDateHttpSoap11Endpoint().getDate();
System.out.println("the date is = " + response);
}
}
If you import the WSDL into SOAPUI, you can see the SOAP messages that are sent and received by the webservice
Request
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:test="http://test">
   <soapenv:Header/>
   <soapenv:Body>
      <test:getDate/>
   </soapenv:Body>
</soapenv:Envelope>

Response
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Body>
      <ns:getDateResponse xmlns:ns="http://test">
         <ns:return>31/08/2013</ns:return>
      </ns:getDateResponse>
   </soapenv:Body>
</soapenv:Envelope>

Echo Service
Now that we can use basic functionality of a WebService, we will use the webservice to echo what we send it

echo/EchoService.java
package echo;


public class EchoService {
public String getMessage(String msg) {
return "You sent: " + msg;
}
}

META-INF/services.xml
<service name="EchoService" scope="application">
        <description>
                This service echos whatever is sent into it
        </description>
        <parameter name="ServiceClass" locked="false">
                echo.EchoService
        </parameter>
        <operation name="getMessage">
                <messageReceiver class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
        </operation>
</service>

Create and copy the aar file to the tomcat axis2 services directory.

Import the wsdl and generate the source code using wsimport. Create an Echo Client using the generated code.

EchoClient
import echo.EchoService;

public class EchoClient {

 /**
  * @param args
  */
 public static void main(String[] args) {
 EchoService echoService = new EchoService();
 String response = echoService.getEchoServiceHttpSoap11Endpoint().getMessage("Hello from the client");
 System.out.println(response);
 }

}

These are the SOAP requests and responses

SOAP request
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:echo="http://echo">
   <soapenv:Header/>
   <soapenv:Body>
      <echo:getMessage>
         <!--Optional:-->
         <echo:args0>test</echo:args0>
      </echo:getMessage>
   </soapenv:Body>
</soapenv:Envelope>

SOAP response
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Body>
      <ns:getMessageResponse xmlns:ns="http://echo">
         <ns:return>You sent: test</ns:return>
      </ns:getMessageResponse>
   </soapenv:Body>
</soapenv:Envelope>

Setting up SVN on Raspberry Pi

Notes from http://www.jeremymorgan.com/tutorials/raspberry-pi/raspberry-pi-how-to-svn-server/

Install Subversion
sudo apt-get install subversion

Create a directory to hold the repositories
mkdir -p /home/pi/repos

Create a new repository
svnadmin create /home/pi/repos/<repo name>

Import a project to svn repository
sudo svn import /home/pi/projects/<project to import> file://localhost/home/pi/repos/<repo name>

Install apache
sudo apt-get install apache2 libapache2-svn


Modify the file /etc/apache2/mods-available/dav_svn.conf
add the following to the file

<Location /svn>
DAV svn
SVNParentPath /home/pi/repos
AuthType Basic
AuthName "Subversion Repo"
AuthUserFile /etc/apache2/dav_svn.passwd
<LimitExcept GET PROPFIND OPTIONS REPORT>
Require valid-user
</LimitExcept>
</Location>


Restart Apache to pick up the config
sudo /etc/init.d/apache2 restart


Change the permissions of the repos directory
sudo chown -R www-data:www-data /home/pi/repos


Set up an svn user
sudo htpasswd -c /etc/apache2/dav_svn.passwd <username>

go to http://<ip of pi>/svn/<project name> and you should be able to see the revision of the project in the browser

Create a new repository
svnadmin create /home/pi/repos/<repo name>
Import the new project into the repo
sudo svn import /home/pi/<new project> file://localhost/home/pi/repos/<new repo>
Change the permissions of the repo
sudo chown -R www-data:www-data /home/pi/repos
Check out the project
svn co --username <username> http://localhost/svn/<project name>

Raspberry Pi Wifi Disconnects after an arbitrary amount of time

Raspberry Pi Wifi Disconnects after an arbitrary amount of time

I was working with my Raspberry Pi and I often noticed that it would disconnect from the network after an arbitrary amount of time. I had to either reboot or manually restart networking to get it going again. It turns out that the power management is switched on.
You can see if power management is on or off by using the following command. The iwconfig command configures a wireless network interface.
iwconfig
wlan0     IEEE 802.11bgn  ESSID:"ssid"
          Mode:Managed  Frequency:2.437 GHz  Access Point: FF:FF:FF:FF:FF:FF
          Bit Rate=52 Mb/s   Tx-Power=20 dBm
          Retry  long limit:7   RTS thr:off   Fragment thr:off
          Power Management:on          Link Quality=41/70  Signal level=-69 dBm
          Rx invalid nwid:0  Rx invalid crypt:0  Rx invalid frag:0
          Tx excessive retries:50  Invalid misc:26   Missed beacon:0


I then disabled power management for the by editing the wireless interface section in /etc/network/interfaces file. I did this by adding "wireless-power off"
iface wlan0 inet dhcp
    wpa-ssid "ssid"
    wpa-psk "password"
    wireless-power off

Once this is done, I restarted networking to pick up the power management changes.
sudo /etc/init.d/networking restart
If you run iwconfig again, you should see "Power Management: off"