Author Archive

Intro to Web Services and REST in JAVA

Wednesday, October 28th, 2009
Presentation given to Texas A&M CPSC 438 (Distributed Objects Programming) Students on 10/28/2009

Presentation given to Texas A&M CPSC 438 (Distributed Objects Programming) Students on 10/28/2009

Introduction:

From a technical standpoint, building a Web Service is not entirely difficult, but it’s not a task that should be taken lightly either. Given the vast use of Web Services in the Enterprise environment, on a recent trip to Texas A&M University, I was able to speak to students (courtesy of Dr. Salih Yurttas) about Web Services and REST in JAVA.

Demo Applications:

As part of the presentation linked above, several demonstrations were given including overviews of the following projects and technologies.

  • metroSOAP
    We create a simple java object (POJO) representing a saying about Texas and it’s author. Using the Hibernate framework, we create a mapping to a mysql table for this object as well as a data access object for accessing the objects. Creating a service class, and it’s implementation, we annotate the service as necessary to produce a RPC based SOAP Web Service Web Application that is factored into a war file for deployment on a Java Web App server such as Apache Tomcat.
  • jerseyRest
    Using the same POJO, Hibernate mapping, and DAO as the previous project, we expose a resource and annotate it as necessary to produce a RESTful Web Service.

Optional Resources:

These resources are indirectly used in the demonstration of the above projects and may be necessary to recreate the given scenarios.

  • soapUI project

    Project files for SOAP UI. Import as necessary.
  • database table
    A collection of famous texas quotes returned by our service calls. May be imported into a mysql table.

Required Software:

A collection of software to build and deploy our example applications.

Optional Software:

Additional resources to test and access the Web Services in a meaningful way. I am also including references to tools that once added to SOAP UI will allow for JAVA client code generation.

License:

This article, along with any associated source code and files, is licensed under Apache License, Version 2.0

About the Author:

Dustin Talk is a consultant at Credera. He graduated from Texas A&M University with his Masters of Computer Science, B.S. in Computer Science, and a minor in Business. Throughout his academic career he developed applications using Java and .Net technologies. While in school, he worked for The Department of Statistics as a Network Administrator. He has interned for Anheuser-Busch Inc. as a Systems Engineer developing in .Net and working with industrial software.

Integrating PHP and Java

Friday, September 11th, 2009

As part of an upcoming project, I have been doing some research and coding trying to understand some of the various methods of integrating Java into a PHP environment. We can categorize the methods into three basic areas: The use of Web Services, utilizing a VM Bridge, and Direct Calling. We also take a look at another alternative, which is running PHP in a Java Environment. I will briefly describe the features of each method, giving those looking for such tools some insight as to what may best fit their application.

Web Services

Since there are many various forms of web services, I have focused my research on two commonly accepted methods.

SOAP (have a working prototype available)

  • Uses direct calls of Java functions via Java web service from within PHP
  • Can maintain independent Java & PHP environments
  • Uses Apache AXIS / AXIS 2 framework, but can be adapted for other web service platforms
  • SOAP is built into PHP5, but there are popular third party modules for older versions of PHP
  • Have the ability to use normal Java classes then auto-generate the service and a client with JUnit tests from within Eclipse JEE
  • Features an optional online management interface in AXIS2 to disable, enable, or monitor services as needed
  • Java RESTful Web Service with Jersey using JSON passing (have a working prototype available)
  • Can maintain independent Java & PHP environments
  • Requires more coding on the PHP side with independent requests to individual methods and handling JSON objects
  • JSON is built into PHP5 but may require third party libraries for older versions
  • Requires more coding on Java side with annotations and passing JSON objects; not plain Java objects
  • There are many libraries available for RESTful Service in Java, Jersey is only used as a reference
  • Is the slowest tested method due to slow http requests in PHP (1/5 second per call)
  • Can be optimized if only a single http request is required per page

VM Bridge. A bridge uses “continuation passing” to invoke procedures/methods from each environment maintaining their individual properties.

php-java-bridge.sourceforge.net (have a working prototype available)

  • Can maintain independent Java & PHP environments
  • Much faster than methods implemented above. (In my tests: 2-3x that of SOAP, 10x that of rest services with multiple requests) (Authors claim: 50x improvement over SOAP/XML-RPC)
  • Uses a VM Bridge XML Network Protocol behind the scenes to communicate with remote or local JVM running a Java app, or Java servlet
  • Have the ability to program regular Java classes
  • Can directly call Java functions in PHP (Works with apache or IIS)
  • Listed as the only free alternative to Web Services/XML-RPC
  • http://php-Java-bridge.sourceforge.net/pjb/index.php

Zend Platform PHP Java Bridge

  • Similar to the above product but a commercial package bundled as part of the Zend Platform.
  • Offers a similar API as the above product.
  • http://www.zend.com/en/products/platform/product-comparison/Java-bridge

Direct Calling

By far the simplest method for using Java in PHP, it can load java classes directly and call its methods. This is not without its drawbacks however.

Direct Java calling within PHP5

  • This is an experimental feature of PHP5
  • Authors say to use at own risk
  • http://us.php.net/manual/en/intro.Java.php

Running PHP in a Java Environment. The methods described below attempt to emulate a specific PHP version entirely in Java. This has the potential of being very fast and easy, however may not meet integration requirements.

Caucho Resin J2EE Application Server with PHP Integration

  • Runs PHP scripts fast (claim a 6x improvement in speed over apache with PHP)
  • The entire PHP implementation is built in Java
  • Not entirely all features of PHP have been implemented, may have issues with multi-threading
  • Requires only one server and environment
  • Have the ability to use regular Java classes
  • May have to adapt current PHP code for a Java environment
  • Is a good way to transition developers from PHP to Java
  • http://www.caucho.com/resin-3.0/quercus/

Tomcat PHP Java Servlet SAPI

  • Enables the entire PHP processor to be run as a servlet
  • PHP has a habit of changing the working directory and may not be able to load any classes from the relative CLASSPATH
  • Requires only one server and environment
  • Have the ability to use regular Java classes
  • PHP version 5 is not currently supported
  • May have to adapt current PHP code for a Java environment
  • http://us.php.net/manual/en/Java.servlet.php

For more information on any of the above methodologies or to request sample code, please don’t hesitate to contact me at: dtalk@credera.com

Google Voice Dialer for Windows Mobile

Thursday, September 10th, 2009

(To skip the article and go straight to the download click: here)

Windows Mobile 6.1 Screenshot

Windows Mobile 6.1 Screenshot

Introduction:

7/15/2009. (googleblog) Google comes out with Google Voice applications for the Android and the Blackberry platforms.

As a Google Voice user, while it was exciting to see mobile development for Google Voice, it left me as a Windows Mobile user in the dark. I still had two options though for my outbound calls to appear as my new Google Voice Number. One option was to connect to the online mobile interface for Google Voice to initiate calls (google.com/voice), or the second option of calling my own Google Voice number and utilizing the telephony menu system to perform and outgoing call. This second method seemed like the best option to me since it did not require the use of a data plan. Now the challenge was automating it by creating a dialer.

The dialer concept is not hard, but requires the use of new tools and frameworks; the Microsoft .Net Compact Framework. For this instance we will be specifically focusing on the .Net CF version 3.5. While one could make a dialer as fancy or minimal as they wanted, I will give a brief outline of the most important features I have implemented:

  • Dialing outbound calls with automated input
  • Saving settings to a local XML file
  • Importing a list of contacts from the phones contact list
  • Saving speed dial numbers to the registry

While these section overviews will provide only brief code samples, the full source of the project is available in for download.

Note: The forms in the code and the binary have been specifically designed to fit a mobile landscape QVGA window for a non touch-screen device. This is compatible with devices such as the Verizon HTC Ozone, Sprint Snap, and T-Mobile Dash 3G, and many others. Compatibility with other devices may require modification to the code.

Environment:

The tools necessary to setup the correct environment to compile and publish this application are listed below. I used the full version of Visual Studio and not the express version because the full version allows for a drag and drop form designer for mobile applications, along with quick deployment to a simulator for debugging. The code may work with Visual Studio Express, but will require custom compilation via the command line. I have also used the Windows Mobile 6.0 Standard SDK and not the Professional since I am not running the Professional version on my device. If you have a touch screen phone with Windows Mobile Professional, I see no reason that this code could not be adapted to work with either SDK.

  • Visual Studio 2008, C#
  • Windows Mobile 6.0 Standard SDK

Outbound Calling:

Using the reference (this must be added to the project) Microsoft.WindowsMobile.Telephony, there are only two simple lines of code needed to use the phone systems dialer to place a call.

Phone phoneCall = new Phone();
phoneCall.Talk(myGVPhoneNum);

The trick part is performing dialing and punching keys after the phone’s internal dialer has taken over. We are able to do this by waiting for the call to be connecting, then a callback is issued to our program where we send simulated keystrokes to the OS’s global keyboard buffer. A full listing of all of the keycodes can be found here: Keys and Keycodes for Windows Mobile.

public static void SendKey(byte key)
{
const int KEYEVENTF_KEYUP = 0x02;
const int KEYEVENTF_KEYDOWN = 0x00;
keybd_event(key, 0, KEYEVENTF_KEYDOWN, 0);
keybd_event(key, 0, KEYEVENTF_KEYUP, 0);
}

[DllImport("coredll", SetLastError = true)]
private static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);

Saving data to XML:

The System.Xml class XmlTextWriter provides a simple mechanism to stream data to a well formated xml file. In our program we use it to write a settings file to the filesystem. Not wanting to provide a complex encryption mechanism, and not wanting a plain-text storage of passwords, I have chosen to write the google vocie password as a base-64 encoded string. For files much larger, I would suggest prompting for a storage location or checking for file space availability first. As always, wrap IO functions to be caught in the event of an error.

System.Text.ASCIIEncoding  encoding=new System.Text.ASCIIEncoding();
XmlTextWriter writer = new XmlTextWriter(exeDirectory + "\\dialgv.xml", null);
writer.WriteStartElement("settings", "gvdial");
writer.WriteElementString("connDelay", "gvdial", txtConnDelay.Text);
writer.WriteElementString("pinDelay", "gvdial", txtPinDelay.Text);
writer.WriteElementString("dialDelay", "gvdial", "500");
writer.WriteElementString("myGVPhoneNum", "gvdial", txtPhone.Text);
writer.WriteElementString("myGVPinNum", "gvdial", Convert.ToBase64String(encoding.GetBytes(txtPin.Text)));
writer.WriteEndElement();
writer.Close();

Reading in the settings is similar to writing them, however we must account for the password stored in base-64 and take measures to convert it back into plain-text.

try
{
XmlTextReader xmlReader = new XmlTextReader(exeDirectory + "\\dialgv.xml");
if (xmlReader == null)
{
frmSettings.giveMessage();
}
else
{
xmlReader.WhitespaceHandling = WhitespaceHandling.None;
while (xmlReader.Read())
{
switch (xmlReader.Name.ToString())
{
case "connDelay":
set_connDelay(System.Convert.ToInt32(xmlReader.ReadString()));
frmSettings.set_connDelay(get_connDelay());
break;
case "pinDelay":
set_pinDelay(System.Convert.ToInt32(xmlReader.ReadString()));
frmSettings.set_pinDelay(get_pinDelay());
break;
case "myGVPhoneNum":
set_myGVPhoneNum(xmlReader.ReadString());
frmSettings.set_myGVPhoneNum(get_myGVPhoneNum());
break;
case "myGVPinNum":
set_myGVPinNum(xmlReader.ReadString());
frmSettings.set_myGVPinNum(get_myGVPinNum());
break;
}
}
}
xmlReader.Close();
}
catch (FileNotFoundException)
{
frmSettings.giveMessage();
}

Phone Contacts:

Microsoft provides the reference Microsoft.WindowsMobile.PocketOutlook, to access the contact information stored on the phone. We iterate through each of our contacts and add the phone numbers as they are found, similar to the default contact schema of Windows Mobile 6.1. An upgraded version of this would be to connect to Google Contacts and synchronize this list and store it offline. This may not be applicable however if you setup Activesync to sync contacts with Google. A tutorial on this is available from Google

OutlookSession mySession = new OutlookSession();
ContactCollection collection = mySession.Contacts.Items;

foreach (Contact contactItem in collection)
{
//add each contact
}

Reading and Writing to the Registry:

Writing to the registry is made very simple in the .Net 3.5 CF. Our first step is to create and instantiate a RegistryKey object which we will use to perform reading / writing. This object is seeded with the location of the registry key we wish to write to. In this instance it is “HKLM\\SOFTWARE\\Dustin Talk\\dialgv”. Then, careful to catch any errors we write a speed dial number to the registry by setting the string value name to the speed dial number (ex: 2) and data of the phone number it belongs to (ex: 214-722-5239).

RegistryKey reg = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Dustin Talk\\dialgv");
try
{
int num = Convert.ToInt32(<em>textBox.Text</em>);
reg.SetValue(num.ToString(), <em>String</em>);
}
catch (Exception ex)
{
MessageBox.Show("Unable to save speed dial: " + ex.Message, "Error");
}

To read the speed dials from the registry we create a similar object as we did before seeding the same location key in the registry. We will then read an array of strings from the RegistryKey object by calling the function GetValueNames(); Catching any errors, and detecting no names available, we add each item that was previously saved to our listView of items.

try
{
RegistryKey reg = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Dustin Talk\\dialgv", true);
string[] vals = reg.GetValueNames();
if (vals.Length <= 0)
{
MessageBox.Show("You do not have any speed dials saved", "Error");
return;
}
for (int i = 0; i < vals.Length; i++)
{
ListViewItem lvI = new ListViewItem(vals[i]);
lvI.SubItems.Add(pNum);
lvSpeeds.Items.Add(lvI);
}
}
catch (Exception)
{
MessageBox.Show("You do not have any speed dials saved", "Error");
}

License:

This article, along with any associated source code and files, is licensed under Apache License, Version 2.0

About the Author:

Dustin Talk is a consultant at Credera. He graduated from Texas A&M University with his Masters of Computer Science, B.S. in Computer Science, and a minor in Business. Throughout his academic career he developed applications using Java and .Net technologies. While in school, he worked for The Department of Statistics as a Network Administrator. He has interned for Anheuser-Busch Inc. as a Systems Engineer developing in .Net and working with industrial software.

Download:

Project Source Code
Binary Installation Cab for Window Mobile 6.1 Smartphone

Please use the contact me if you can offer any interesting modifications or suggestions to the code, or if you would like additional resources on your project.