Monday, November 29, 2010

Screen Scraping and scripting AS400 with Java!!

If you are like me you've been pulling your hair out trying to mess with the TN5250 stream so that you can automate things from you Java applications.

Well stop messing with the protocol itself and let TN5250j do that for you.

Here's how to do it with Netbeans 6.9:

First get TN5250j from here.

Next you will need Netbeans, duh. Netbeans!

Now start a new Java application. On the next screen name the program TestApp.

Now make Main.java say the following:


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package testapp;

import java.net.UnknownHostException;
import org.tn5250j.Session5250;
import org.tn5250j.beans.ProtocolBean;
import org.tn5250j.framework.tn5250.Screen5250;
import org.tn5250j.framework.tn5250.ScreenPlanes;

public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) throws UnknownHostException, InterruptedException {
ProtocolBean pb = new ProtocolBean("test", "123");
pb.setHostName("192.168.1.2");
Session5250 session = pb.getSession();
pb.connect();
Screen5250 screen = session.getScreen();
char [] buffer = new char[1920];
StringBuilder sb = new StringBuilder();
Thread.sleep(3000L);
screen.GetScreen(buffer, 1920, ScreenPlanes.PLANE_TEXT);
String showme = new String(buffer);
for(int i=0;i<showme.length();i+=80) {
sb.append(showme.substring(i, i+80));
sb.append("\n");
}
System.out.println(sb.toString());
session.disconnect();
}

}



Run your program and you should see the results in your output window.

Let me run through these lines. I'll have to break up a detail description of each line over the next few post.

ProtocolBean is a bean that the TN5250j exposes that allows programmers to use the bulk of TN5250j's api to control the TN5250 data stream. It wraps all the nasty stuff into one nice little bean. There is one catch to this. You cannot use the ProtocolBean inside of the AWT-Event Loop. So if you are doing a GUI then you'll need to start the session outside of the AWT-Event Loop.

The ProtocolBean has two constructors. I'm using the more basic one here. Using the basic ctor means that you have to call a couple of methods from ProtocolBean before starting up. I'll cover the other ctor later. Here we call the setHostName method which should not surprise you that it sets the IP address of the host.

Oh and by-the-by if you are wondering what the ctor for the protocol bean is doing... The first argument creates a config file that TN5250j will use and the second names the session. So if you've ever used the PCOMM ECL then you know all about this, if not, Sessions have two names an ID and a name. The ID runs from 1 to 65536 or so, in the order that you start them. The name is whatever you like to call stuff. Libraries, can access a client by either the ID... Look I'm getting off topic, we'll save all that for another day.

Okay next thing is the Session5250. We grab the session first and then connect. Long story short, you should always grab the session first and then call the connect method from the protocol bean.

Next is to grab the screen. Now I'm on a really slow connection so I added a Thread.sleep() to slow things down. I'll cover later how you can actually check if the connection is ready to be used.

First grab the screen into a Screnn5250 object.
Next we need to make a char[] it will act as a buffer for all the data that we will get form the TN5250 stream. Yes, this is how you must do it. No, there is no way around it. I've checked the source code for TN5250j.

Next I'm just going to print to stdout the actual screen. My screen defaults to 24x80. Most of the time this is what the stream will always be. However, at my company we have a system that does 27x132. You need to check to make sure that the system isn't requesting 27x132 because most of the time this will make the session end abnormally if you don't report that you can handle 27x132.

As you can see I use a for loop to add a new line at every 80 chars. This makes it look exactly like the terminal.

Oh yeah if you are wondering about that GetScreen method. The parameters are char[] that will act as the buffer. How large is the buffer? And from which plane should I get data from? I'll explain ScreenPlanes.PLANE_TEXT later. For now that's the one that you want.

Anyway...

So then I System.out.println() my StringBuilder.

Then I call the disconnect method from the session object.

You can download the source code for TN5250j and read all about the Session5250 and Screen5250 classes.

I've got to go for now!

Monday, November 01, 2010

Oh and...

Just wanted to let you all know that the company Glassfish server was moved to version 3.0.1. We had no problems with 2.1 per se. We moved to 3.0.1 because we got clustering working, JNLP working, and we really needed some of the features of 3.0.1. Don't know which ones but the 3.0.1 was the one that we all finally settled on.

I was pushing JBoss but they would like to see 6.0 out of RC before going down that road.

Been gone for a while.

Well it's sad but I've been a way for a bit, at least blogging.

As you may know, Oracle bought out Sun and pretty much every Java community that was started by Sun and was still under Sun's wings during the last days have all abandoned Oracle. I don't blame them.

So I heard from friends, "So are you going to continue to develop using Java?"

The answer is of course. The JVM and the Java platform is not entirely Oracle's, they do have leadership over the core but the community of Java projects still exist, just no longer listening to Oracle. Oracle is slowly loosing the Java community and with it the fresh ideas that the community has produced, such as JSF 2.0 and EJB 3!

In the end Oracle will be playing catch up and Java's core will suffer but the community which has driven Java development for the last ten years will still stay strong. It's a shame because ideas from the community were actually being placed into the core Java spec towards the end of Sun's days.

Java as a platform isn't dead, the Java community isn't dead, just our relationship with Oracle. It's a shame that the bottom dollar is the only thing that they seem to think about but it's their bloody company and they can run how they please.

So what about Oracle's contributions to the open source world?

If you head over to Oracle's website you'll see the contributions that Oracle has made to the OSS community...

If you review all of their contributions you will see that they all lead back to Oracle products. I see their contributions on the same level as the Visual Studio Express versions that Microsoft offers. The independents will all die a slow death, which is sad because bringing them back via an OSS fork is always a slow to start process. Just look at OpenOffice.org and now Libre Office.

This shouldn't come as a surprise to anyone. But I think that this will make the Java community tighter and closer knit. Yes it does toss Java back about five to seven years, community / corporate wise, but I think the OpenOffice people are showing us all what the Netbeans, MySQL, Glassfish people will all eventually come to do, break ties with a company that refuses to work with the community and instead does the equal of food dumping into the open source community.

I will start posting more, I swear this time! We'll start slow, maybe twice a week?

Friday, September 10, 2010

Throbber for Java

Have you ever wanted to do a please wait for a Java application?  Did you want a little spinny logo to animate while they waited?

As Professor Fransworth would say, "Good news everybody!"

Let's start out with a preview of the graphic that I'll be using.
Spinner Image

Now this is actually nine different images, I've just haphazardly put them into one image here so you can see what I'm doing. I made these images in about five minutes using Inkscape but you can use whatever. You do need to export the images into a format that Java understands, I usually default to png.

I've named the rotor images rotor1.png through rotor8.png and the final image (the check mark) as rotord.png. The check mark is optional and the code below is clear cut enough to be able to remove the check mark. At any rate I'm placing the images into a package called sample.img

Now here's what we need to do. We need to create a custom JFrame (of Swing fame) that will be our spinning logo. IF you are using Netbeans, DO NOT USE NEW JFrame CLASS. If you are using Netbeans select Create New Java class. This gives you a no frills attached blank document with a shell of a Java class to begin with. If you do use the JFrame class in Netbeans it adds an XML document behind the scenes that allows you to use the GUI-fied editor, which will only serve to get in your way, in this case at least.

So let's build our customer JFrame.



package sample.ui;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JPanel;

/**
*
* @author John Doe
*/
public class RotorPanel extends JPanel {

private Image[] rotorImg;
private Image rotorComplete;
private boolean done;
private int current = 0;
private final int max_image = 7;

public RotorPanel() {
this.rotorImg = new Image[max_image+1];
for(int i=0; i<max_image+1; i++)
this.rotorImg[i] = Toolkit.getDefaultToolkit().createImage(getClass().getResource("/sample/img/rotor" + (i+1) + ".png"));
this.rotorComplete = Toolkit.getDefaultToolkit().createImage(getClass().getResource("/sample/img/rotord.png"));
this.done = false;
}

@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
if(!done)
g2.drawImage(this.rotorImg[this.current], 0, 0, this);
else
g2.drawImage(this.rotorComplete, 0, 0, this);
}

public void increment() {
this.current++;
if(this.current>this.max_image)
this.current = 0;
}

public void setDone(boolean done) {
this.done = done;
}

public boolean isDone() {
return done;
}

}



As you can see it is pretty straight forward in approach. The constructor loads the images into an array and sets the done flag to false. The increment method moves us through the images. We've overridden the paint method to draw the image.

Now let's use our JPanel. If you are using Netbeans, go ahead an use the JDialog template, that's what I'll be covering here. In Netbeans add a standard JPanel from the palette and then in the properties window click on the code tab. In the custom creation code add "new RotorPanel()". This replaces the new javax.swing.JPanel that is found in the protected area (which is controlled by the XML file behind the scenes) with this code, which is what we want.

Next in the constructor code right after the initComponents call add the following code.


this.t = new Thread() {
@Override
public void run() {
RotorPanel p = (RotorPanel) PleaseWaitDialog.this.jPanel1;
while(!p.isDone()) {
p.increment();
p.repaint();
try { Thread.sleep(65); }
catch (InterruptedException ex) {}
}
p.repaint();
}
};


This creates a thread that will call the increment method to rotate the image and then the repaint method which will update our image. The Thread.sleep(65) call is to sleep 65 ms and then repaint the image, this roughly controls the speed of the animation. Notice that the loop checks the done flag. When you are done and want this thread to die, simply call ((RotorPanel) this.jPanel1).setDone(true);

In 65 ms or less the thread will die because we exit the while loop and the run method of the thread returns. Of course this doesn't mean that you need to stop displaying something, just that you will no longer be rotating the image, hence the check mark image. The actual image doesn't go away until you kill the JDialog.

Pretty simple animation. If you want better control over animation and what-not, I would suggest looking into the timing framework that is located at https://timingframework.dev.java.net/. This framework will allow you have a better control over animating something. However, this is a simple little snippit of code that you can use for simple animations.

Cheers!

Powered by ScribeFire.

Thursday, September 02, 2010

Websockets are cool!

I won't go into a lot of detail today, but I tried out serving up some PHP with websockets enabled. Websockets are way cool... I won't go to the end of saying, "OMG!! This will revolutionize the Internetz!!11!!" But I must say that this is will be a big game changer in terms of Internet applications. Combinded with HTML5, web sockets will be the new preferred method for messaging between server and client as opposed to AJAX and similar push technologies.


The best part of Web Sockets is the simple approach they take to passing messages between client and server combined with just how powerful they truly are. If you have ever used callback handlers then web sockets will be a very easy topic for you. You simply register what the web page should be listening for. You web page emits messages to the server and the server emits messages back. On each message received the web page checks what has been registered and the action associated with it.


This has the upshoot of being a write the handler and forget it approach which usually is a disservice to an API, but found that it serves JavaScript quite well.


The only problem will be getting frameworks to start jumping ship from AJAX to Websockets. XML can still be passed using Websockets and most likely that's the way most people will go, but any kind of data can be sent and that includes binary data which tends to be faster and more compact than XML. Most AJAX platforms already present their API as a series of callbacks for people to use in their web pages so Webdevs are already in the right thinking for Websockets.


Another barrier to websockets is the lack of servers that have support for it. The PHP version is still in beta and Apache feels that third parties will fill in the void for them. Jetty (Java server) and a few third party SilverLight stacks provide production grade Websockets at the current moment. The final barrier is the fact that the Websocket standard hasn't been approved as final by IETF, in fact it's still draft. So everything in the standard could change in a moments notice. That alone could keep vendors from adding it to their server. Browser support is Chrome, Opera, and Firefox 4. Basically all the next gen browsers, except our favorite browser to hate IE (including the latest IE 9 build).


All that said Websockets provide a new method of communicating with clients that out matches all currently existing technology and at some point full duplex communications is going to come to all browser and servers, be it websockets or something else down the road. Most likely Websockets will be the winner the biggest question will be in what shape as the standard could change as we all wait for it to become a final standard.

Tuesday, August 31, 2010

Using Cairo with Gtkmm

Okay we should be all familiar with the Cairo API. If this is the first time you've ever heard of Cairo outside of a reference to Egypt then let me give you a quick peek at Cairo.



Cairo is pretty much the main library used for drawing anything with vectors. It is used everywhere, sort of like SQLite. The website is http://cairographics.org/



In the GNOME trifecta of things, Cairo provides the 2D drawing API, whereas Pango provides the Text Rendering API, and Gtk-Glib provide the toolkit/glue for all the above.



The neat thing about Cairo is that output is not limited to the screen. Backends for Cairo can be written for anything, so things drawn in Cairo can be outputted to an SVG file, OpenGL commands, a printer, or to a Pixbuf for use in a very popular web browser (Firefox anyone).



So today I'm going to use Cairomm (C++ bindings for Cairo) to do some basic drawing. Here is our header file justin_draw.h that defines our DrawingArea.



#ifndef SAMPLE04_JUSTIN
#define SAMPLE04_JUSTIN

#include <gtkmm/drawingarea.h>

class JustinDraw : public Gtk::DrawingArea
{

public:
JustinDraw();
virtual ~JustinDraw();

protected:
virtual bool on_expose_event(GdkEventExpose* event);

};

#endif



The only thing of note here is that we are going to define an on_expose_event. This is important because this is the method that is called when the window needs to draw itself. Either because the Window is new, or we've uncovered the window an exposed a part of it that was under another window.




Now let's implement our Gtk::DrawingArea with our justin_draw.cc file:



#include "justin_draw.h"
#include <cairomm/context.h>

JustinDraw::JustinDraw() {}

JustinDraw::~JustinDraw() {}

bool JustinDraw::on_expose_event(GdkEventExpose* event)
{
Glib::RefPtr<Gdk::Window> window = get_window();

if (window)
{
Gtk::Allocation a = get_allocation();
const int w = a.get_width();
const int h = a.get_height();

int xc, yc;
xc = w/2;
yc = h/2;

Cairo::RefPtr<Cairo::Context> cr = window->create_cairo_context();
cr->set_line_width(10.0);

cr->rectangle(event->area.x, event->area.y, event->area.width, event->area.height);
cr->clip();

cr->set_source_rgb(0.8, 0.0, 0.0);
cr->move_to(0,0);
cr->line_to(xc,yc);
cr->line_to(0,h);
cr->move_to(xc,yc);
cr->line_to(w,yc);
cr->stroke();
}

return true;
}



Notice a couple of things here before we move on. Drawing an entire screen with Cairo should be done very rarely. Not to say Cairo is slow but there is no need to waste time on drawing. The cr->rectangle(...); cr->clip(); parts allow us to focus on only the part of the window that has changed. Pretty much all code that uses Cairo has something similar to this so it's a good idea to include something like this in you code before you actually do any drawing.




Also notice that we are using a Cairo::RefPtr. Yes Cairo has it's own type of RefPtr's that you must use to hold Cairo related things. You have no idea how much time you can waste using the wrong type of RefPtr.




Finally, our program that uses our new Gtk::DrawingArea. main.cc

#include "justin_draw.h"
#include <gtkmm/main.h>
#include <gtkmm/window.h>

int main(int argc, char** argv)
{
Gtk::Main kit(argc, argv);

Gtk::Window win;
win.set_title("DrawingArea");

JustinDraw area;
win.add(area);
area.show();

Gtk::Main::run(win);

return 0;
}



And that's all there is to it! You can hit up basically any manual on Cairo to find all the 2D API commands. It's basically a 1:1 translation between the C and C++ bindings so you shouldn't have any problems there.




Tomorrow I'm going to cover Making a throbbing image in Java, because I'm gotten two emails over the last four days asking how to do that. Till then, Cheers!

Sunday, August 29, 2010

Trying out L2TPv3 in Linux 2.6.35.4

So I built me a 2.6.35.4 kernel to try out the new L2TPv3 support offered in this kernel.

L2TPv3 is pretty good and the newest kernel provides awesome RFC 3931 support, but I would advise some people to stick with L2TPv2. Not a lot of 3rd party vendors are there yet and the newest version has a lot of overhead over the wire.

I'm still on the fence about btrfs. I'll give it another six months before I actually change my LVM over.

Oh and by the by. The new kernel improves LVM response by about 5% - 10% depending on setup.

Friday, August 13, 2010

I hate Jennifer Aniston.

This is f'ing funny.


Jennifer Aniston Adopts 33-Year-Old Boyfriend From Africa

Wednesday, August 04, 2010

A Quick try of Gtkmm

Okay I figure I would give my hand a try at some Gtkmm. The API is pretty much like most curses and Java Windowing framework. So let's do a quick sample.

Let's start with our header file for the Window, we'll call it window1.h


#ifndef WINDOW_1_DEF_H
#define WINDOW_1_DEF_H

#include<gtkmm/window.h>
#include<gtkmm/button.h>
#include<gtkmm/entry.h>
#include<gtkmm/box.h>

class Window1 : public Gtk::Window {

public:

Window1();
virtual ~Window1();

protected:

void on_button1_clicked();

private:

Gtk::Button button1, button2;
Gtk::Entry entry1;
Gtk::VBox vbox1;

};

#endif



All of that should explain itself. Basically the object is a Gtk::Window, which is the top level container (widget, whatever you want to call it). We are adding two Gtk::Button, a Gtk::Entry (text entry widget), and a Gtk::VBox which is the layout container.

Now the fun thing about Gtkmm is that you don't have to "new" objects into existence. Instead Gtkmm will handle the memory allocation for you in most cases!! However, if you need to dynamically allocate objects or you need them outside of the class scope then your own your own, unless you use the Gtkmm smart pointer Glib::RefPtr<>, which is basically the same as the std::auto_ptr<> for those of you who have studied standard C++.

Okay let's implement the window, this will be in most logically window1.cc


#include "window1.h"
#include <iostream>
#include<gtkmm/main.h>

Window1::Window1() : button1("Print"), button2("Ouit") {

set_size_request(200,100);
set_title("Text Entry Demo");

add(vbox1);

entry1.set_max_length(25);
entry1.set_text("Enter something");
entry1.select_region(0,entry1.get_text_length());

vbox1.add(entry1);

button1.signal_clicked().connect(sigc::mem_fun(*this,&Window1::on_button1_clicked));
button2.signal_clicked().connect(sigc::ptr_fun(&Gtk::Main::quit));

vbox1.add(button1);
vbox1.add(button2);

show_all();
}

Window1::~Window1() {
using namespace std;
cout << "Say goodbye" << endl;
}

void Window1::on_button1_clicked() {
std::cout << "You have entered: " << entry1.get_text() << std::endl;
}



Okay this one has a couple of things to cover. Like what the heck is the sigc namespace?!

sigc is the library that Gtkmm uses to implement callbacks. A callback is a function or method that is called from another function. Basically the on_click method of your buttons gets called when you click on them. The method basically says, when I'm clicked run ________(insert blank line)________. The callback fills in the blank line.

Now historically there is basically one way to do this in C, but in C++ there must be at least a dozen libraries that do this. I won't get into why this is because that's a much bigger topic.

At anyrate, sigc is the tool that Gtkmm has chosen to implement callbacks. sigc has two ways to add callbacks. mem_fun and ptr_fun, both used here. mem_fun, allows you to call a method and ptr_fun allows you to call a function. Pretty clear cut there. As you can see I've connected the button2's click to the Gtk::Main::quit, which of course does what it says. Quits.

The other button, button1, I've connected to the on_button1_clicked method. This method simply uses standard C++ cout to write information to standard out. You may notice that I use the entry1.get_text() method within the on_button1_clicked() method and that I don't cast it's result to std::string. That's the neatest part of Gtkmm is that it was made to work with the C++ STL so well. Gtkmm already implements the logic needed to cast Glib::ustring (which is what the get_text() wethod returns) to std::string.

The rest of the code is pretty simple to follow.

So now that we have implemented our window we need an application that actually uses it.

I present main.cc


#include<gtkmm/main.h>
#include"window1.h"

int main(int argc, char *argv[]){

Gtk::Main kit(argc, argv);
Window1 w;
Gtk::Main::run(w);

return 0;
}



This is as basic as you can make an application that uses our window.

The results are here.


Clicking on the Print button outputs the text box on standard out and clicking quit, well quits. As you can see Gtkmm is very much like most other Toolkits, semantics are a little different here and there and you'll use some of the core tools of Gtkmm a little differently but overall you'll easily see how Gtkmm compares to things like SWT, Swing, and QT.

And since I said something about QT, it's worth saying something about it. If you have ever used QT then you know about it's signal/slot system and moc. Well Gtkmm takes the "high road" on this one and uses sigc to implement callbacks in a C++ standard-ish kind of way. The downfall of this, however, is that every callback must be statically typed. This amounts to a lot of double work. If you implement a signal connection in Glade, you must also implement that connection in Gtkmm by importing the widget and then using sigc.

I know this is one of the downfalls of C++'s strong type safety system and name mangling system. QT gets around this with moc but then using moc makes your code non-C++ standard compliant, which I don't think anybody really has a problem with except the people behind Gtkmm.

At anyrate, at risk for getting way off topic, Gtkmm is a neat little wrapper around Gtk+ and you should give it a whirl. You'll be making Gtk+ applications in no time, and best of all is the Gtkmm library works on Windows, Mac, Linux, BSD, and other Unix systems.
Link to Gtkmm

Tuesday, August 03, 2010

Is it just me?

Does it seem that Colbie Caillat has incredibly "wide" eyes? Is that even a thing? Maybe, I'm just mental?



Oh her song on the radio is a nifty little tune, and she was on the the Next Food Network Star show too. Before that I would have sworn that you were talking about a type of cheese.

Saturday, July 24, 2010

Working on a neat project

Usually I have the most fun with design and coding. Rarely do I go back and play with the UI in the sense of having fun with it.

It's just mostly checking if the UI is okay and if there are any bugs/misspellings.

Well I've just got a project that I'm having fun with the UI as well because the interface is a Text based User Interface (TUI, if you are so inclined to use that).

It's cool using JCurses. JCurses is a very loose JNI for the Curses environment, nCurses on Linux. Since it does use JNI that means that you do loose the cross platform compatibility, but JCurses comes with sources and Win32 and Linux x86 binary libraries.

I've been able to compile JCurses for Linux amd64, Mac OSX, and PPA systems. So you should be covered for systems that you may want to run this on.(Note: I don't have access to an ARM chip so I don't know if you can use JCurses there).

The setup at work is to provide a SSH session via RF scanner to our warehouse users, noting new there we've been serving TN-5250 sessions via wireless for the past fifteen years (longer than I've been there).

However, this is the first time that I've actually been calling EJBs from a text based interface. The principal is basically the same, call the remote endpoint from the Java code, present results bark to user.

The fun part is with a text based interface, you really have to concentrate on features and how you present them. A screen full of text is impossible to use effectively, and the more options you present at once the more cluttered the screen appears.

I've found that the best way to break up things is not present all the needed input at once, but instead to take an ask on need approach. So when the next step is to get an EAN or UCC128 code that's what you ask and only that and the options that might effect that.

Also, keyboard functions are limited to basically, TAB, ENTER, F1 through F4, the numbers 0 through 9, and BACKSPACE. Obviously there are no mouse functions.

All of this, limited input, limited screen size, and limited ways of getting the user's attention (Curses can only ring the system bell) really forces you to really think out the UI in a manner that end users usually can't help with.

That's not to say that I never think of the UI for GUIs, but usually we have a company layout and guideline on how our GUIs are created. You simply follow that, get end user feedback, and modify as needed without breaking something.

I'll have to post some examples of JCurses and EJBs soon.

Wednesday, July 21, 2010

Heading on the road, again.

Well.  I'm heading on the road again.  Travel sucks and double much when it is business travel.  The hope is that this round is my last round for a good bit of time, until next year.

At any rate, I've really got to get back to blogging because I enjoyed it so much.

I've had time in the air to think of some little projects that I'd like to do personally on my system.  I'll have to share them when I'm not in the air.  Also, trains suck.  It never fails that I am delayed twenty minutes going to anywhere by a train crossing.  Just yesterday while going from one building to another I wasted forty-five minutes, the break down is as follows:

  1. Rail construction, the construction train was at the crossing on Highway 11.  Wasted 23 minutes.
  2. Slow moving train coming back via different route.  Wasted 17 minutes.
  3. What the heck! A mostly unused train track is being used to move cargo into a rail-yard. Wasted 9 minutes.
That last one was just to spite me.  I think CSX personally has a vendetta out on me.

Well I'm off.  Cheers!

Monday, June 14, 2010

Where I work trains are a big problem. they can take up to fifteen minutes some times like this guy.
From my phone.

Thursday, June 03, 2010

Yeah I know. I've been on the road for company related stuff.

So I've shown how to add security annotations to a pretty vanilla EJB. When you develop EJBs remember to keep them limited in scope. For example, if you have an EJB that handles Inbound orders (placeOrder, reviewOrder, cancelOrder, addToOrder, removeFromOrder, etc...) do not feature creep by having that same EJB handle Outbound orders or worst yet schedule orders in a calendar app.

I cannot tell you the number of times that I've run across an EJB where 30% of the code really belongs in its own EJB unit. For example the calendar app should view Inbound orders as a Collection not as a derived member called SchdOrd (PS use freaking descriptive names! The next guy will not understand that OrdTckChcExc is short for Order Ticket Cache Exchange; nor will that name mean anything to them.) A calendar *HAS A* Collection of Inbound orders makes more sense than A Scheduled Order *IS AN* Inbound Order.

The reason it makes more sense? Just because something is a something else does not mean that the logic for the unit is clarified by the statement. The statement only implies a date an doesn't do a very good job of telling anyone what that date means to anybody. A calendar (thus we get the date concept) has a (okay that tells us something about storage) collection (alrighty this tells us that we are going to be looking at a lot of similar things at once) of Inbound orders.

As you can see the HAS A statement tell more about the underlying logic than the IS A statement. So, more than likely by Justin's 23rd rule of programming, the logic will be easier to implement.

I'm getting off on a tangent here, sorry.

Next post I'll cover using a JAAS callback to implement acustom login dialog and how to handle a failed login, yes you do have to handle those Glassfish will not do it for you.

Cheers!

Wednesday, May 26, 2010

Had my first in and out burger. awesome.

Monday, May 24, 2010

teenage girl won't stop fighting

teenage girl won't stop fighting mom on aa flight1959. So we're landing in Phoenix. She was hand cuffed! Flight delay!

Saturday, May 22, 2010

Posting from my phone!

So I can post during those long drives (If I was to type at say four letters a minute, I'd fill more than one text message).  Just to give you some scope of how long my drive to work is.  Cheers!

The switch to v2 over v3.

We had to downgrade to Glassfish v2.1.1 at work and I've been busy making sure everything is running smoothly. Our biggest issue (since I don't want to go on a rant about glassfish I'll just leave it at this issue) was the Java Web Start snafu. I know that the real problem lies with the JRE but we can keeping making workarounds on our Apache server and making custom JNPL's.

At any rate our requirement of JSF 2.0 was easily assuaged and I'd like to share that with you.

You can get all the information to install Mojarra v2.0.2 on Glassfish v2.1.1 form here.

Just follow those and you'll be able to deploy JSF 2.0 pages in no time!

UPDATE ON 7/21/2010:
Just so you know we're sticking with Glassfish v2.1.1 but the Glassfish 3.0.1 server has the issue pretty much fixed for most cases.

The upshoot with v2 is that we can actual take our three glassfish servers and have them talk to each other to keep everyone up to date!  Our v3 system had a cron, shell script, and NFS mount to do that but the v2 way is much better.

Saturday, May 01, 2010

Apple will destroy you! Try not to be happy about how shiny your death will be.

Apple is the anti-Christ of computers. For years we all hated on Microsoft because they we're big bullies who try to take over everything. Now, don't get me wrong MS is evil, they will want you to use whatever they sell, but that have come to the conclusion that they can't control everything.

Enter Apple, they do believe that they can control everything, they will control how you get books on your iPad, they will control which book you have access to, they will control which apps you can buy, they will control how and when you can use said apps you just bought, they control what you can and can not do on the Internet, they control how you will use the Internet, they control how you have access to content, they control the content that you access...

I could go on forever, in short, it will be Apple's way or no way. It will be Apple's software or no software. In no way is Apple equal to a free market of any sorts and in every single way possible is Apple total vendor lock-in. Once you go Apple it is over, you no longer have *your* documents, you have access to *Apple's* documents.

This all come in the wake of Apple's latest move to destroy Google's platform, increase the operating cost of YouTube, lock out any Microsoft tools, destroy any sharing between KHTML devs and WebKit devs, and now their move to remove Adobe and Ogg from the Internet.

I know what most people would say, just don't buy Apple, good luck on getting that to work. I'm currently on the campaign (since I'm tired of Apple treating open source like a little redheaded bitch) to ensure that people I know don't buy Apple ever again. I ask anyone and everyone who believes in a open world of software to get the word out that Apple is the largest private company threat to everyone's freedom on the Internet. Apple, don't buy into it!

Monday, April 12, 2010

Where was I?

So sorry. Lost track of what I was doing here. I'll try to keep that to a minimum.

At any rate. If you are using Glassfish v3 to serve up application clients via Java Web Start, then check your client's (the people who will be running your crap) JVM. JRE 1.6 u 18 has a nasty bug that prevents Glassfish v3 JWS from working correctly.

I've got to get back on this horse. I'll see you all soon!

Thursday, April 01, 2010

What's going on? I know it has been awhile since my last post. Been a bit busy, also workplace has banned blogger from the network. So I'm posting this from my Wii. Fun stuff! Gnome 2.30 is released if you are into that kind of thing. happy April fools day!

Tuesday, March 02, 2010

Adding Security to EJB

Alright let's take a quick look at the HelloBean.java file with security annotations:


package com.blogger.ramen;

import javax.ejb.Stateless;
import javax.annotation.security.RolesAllowed;
import javax.annotation.security.DeclareRoles;

@Stateless(name="HelloBean")
@DeclareRoles("SecureUser")
public class HelloBean implements HelloRemote {

@RolesAllowed("SecureUser")
public String sayHello() {
return "Hello from EJB!";
}

}


As you can see I've added the DeclareRoles and RolesAllowed annotations. The EJB container will read the meta-data in the class see the annotations and enforce the security described in them. This happens each time you call the method since it is Stateless.

So the next question is how does the container know you belong to the SecureUser role? Because the security mappings in your sun-ejb-jar.xml file. Here's what you need to add:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sun-ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Application Server 9.0 EJB 3.0//EN" "http://www.sun.com/software/appserver/dtds/sun-ejb-jar_3_0-0.dtd">
<sun-ejb-jar>
<enterprise-beans>
<ejb>
<ejb-name>HelloBean</ejb-name>
<jndi-name>ejb/Helloness/HelloThere</jndi-name>
<ior-security-config>
<as-context>
<auth-method>USERNAME_PASSWORD</auth-method>
<realm>OurDBRealm</realm>
<required>true</required>
</as-context>
</ior-security-config>
</ejb>
</enterprise-beans>
</sun-ejb-jar>


As you can see the <ior-security-config> and all of it's friends to add a realm to our EJB. Our realm being OurDBRealm that we already setup using the JDBCRealm method that was given earlier. We need to add one more thing to that file, our security mapping, this will map something that will match an entry in the JDBCRealm with the annotation we've giving here. We add this snippit right after the <sun-ejb-jar> element.


<security-role-mapping>
<role-name>SecureUser</role-name>
<group-name>SUSER</group-name>
</security-role-mapping>


Deploy your EJB and rerun your client. You should get the default login prompt that's built into Glassfish. Login with the information you've stored in the database and you should see results. Viola! Secure EJB. Of course, if you give bad login information then you will get an exception. At any rate this is a pretty cut and dry use of secure EJBs. We'll look at how to provide your own login dialog and how to catch exceptions on login.

Cheers!

Thursday, February 25, 2010

Just so we can get on with it. Go here to see how to add a realm to your Glassfish server. Once you've added the realm you'll need to create some groups. For the best method, give each group a specific task as it is easier to focus on a limit set of permissions than code for roles.

You may have a task like add a product, review a shopping cart, delete an account, or add a bank transaction. Roles are more like Super users, accountants, managers, etc.

Focus on task in your groups and then add triggers or EJB beans that focus on roles, which in turn aggregate your tasks.

Tuesday, February 23, 2010

Where have I been? Sorry I've just not had the time to post code samples here. Car had some issues, got them fixed, house had issues, cot those fixed, work has issues, not a damn thing I can do about those.

Friday, February 05, 2010

Okay, so here is a quick example of using the FedEx WSDL to build a simple tracking application. To get the FedEx WSDL you just go over to their developer website at http://www.fedex.com/us/developer. You will need to sign up to get a key and password to use their service. When you do sign up give it a couple of days for the key and password to be activated. If it takes longer than two days for the key and password to come online, just give the FedEx number a call.

So download the WSDL and add it to your web services on the services tab of NetBeans. Start a new Java Project and drag the track service from the services tab into the main method in your project.

You should now see some code that looks like this:



package javaapplication34;

/**
*
* @author Me
*/
public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {

try {
com.fedex.ws.track.v4.TrackRequest trackRequest = null;
com.fedex.ws.track.v4.TrackService service = new com.fedex.ws.track.v4.TrackService();
com.fedex.ws.track.v4.TrackPortType port = service.getTrackServicePort();
// TODO process result here
com.fedex.ws.track.v4.TrackReply result = port.track(trackRequest);
System.out.println("Result = " + result);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}


We are going to change that code to look like this:



package javaapplication34;

import com.fedex.ws.track.v4.ClientDetail;
import com.fedex.ws.track.v4.Notification;
import com.fedex.ws.track.v4.NotificationSeverityType;
import com.fedex.ws.track.v4.TrackDetail;
import com.fedex.ws.track.v4.TrackIdentifierType;
import com.fedex.ws.track.v4.TrackPackageIdentifier;
import com.fedex.ws.track.v4.TrackRequest;
import com.fedex.ws.track.v4.TransactionDetail;
import com.fedex.ws.track.v4.VersionId;
import com.fedex.ws.track.v4.WebAuthenticationCredential;
import com.fedex.ws.track.v4.WebAuthenticationDetail;
import com.fedex.ws.track.v4.TrackService;
import com.fedex.ws.track.v4.TrackPortType;
import com.fedex.ws.track.v4.TrackReply;

/**
*
* @author me
*/
public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {

try {
TrackRequest trackRequest = new TrackRequest();
VersionId verId = new VersionId();
verId.setServiceId("trck");
verId.setMajor(4);
verId.setIntermediate(0);
verId.setMinor(0);
//The WSDL does not say that this is required but it is.
trackRequest.setVersion(verId);

WebAuthenticationDetail auth = new WebAuthenticationDetail();
WebAuthenticationCredential cred = new WebAuthenticationCredential();
//This is the key.
cred.setKey("XXXX");
//This is the password
cred.setPassword("XXXX");
auth.setUserCredential(cred);

ClientDetail detail = new ClientDetail();
//This is the test account number
detail.setAccountNumber("XXXX");
//This is the test meter number
detail.setMeterNumber("XXXX");

TransactionDetail trans_detail = new TransactionDetail();
trans_detail.setCustomerTransactionId("Tracking with Java");

TrackPackageIdentifier packId = new TrackPackageIdentifier();
packId.setType(TrackIdentifierType.TRACKING_NUMBER_OR_DOORTAG);
//This is some tracking number that you already have.
packId.setValue("XXXX");

trackRequest.setWebAuthenticationDetail(auth);
trackRequest.setClientDetail(detail);
trackRequest.setTransactionDetail(trans_detail);
trackRequest.setPackageIdentifier(packId);
trackRequest.setIncludeDetailedScans(Boolean.TRUE);

TrackService service = new TrackService();
TrackPortType port = service.getTrackServicePort();

TrackReply result = port.track(trackRequest);
if (result.getHighestSeverity() != NotificationSeverityType.FAILURE && result.getHighestSeverity() != NotificationSeverityType.ERROR) {
System.out.println("----RESULTS----");
if (!result.getTrackDetails().isEmpty()) {
for (TrackDetail d : result.getTrackDetails()) {
System.out.println("Tracking Number " + d.getTrackingNumber());
System.out.println("Tracking Description " + d.getStatusDescription());
}
}
} else {
for (Notification n : result.getNotifications()) {
System.err.println(n.getMessage());
}
}
} catch (Exception ex) {
ex.printStackTrace();
}

}
}


Ta-da! Simple example of the FedEx tracking Web-Service in action. If your account has not been enabled yet you will receive an "Authentication Failed" message. Otherwise you should start seeing some detail about the package. I suggest that you give the TrackDetail class a quick glance since that will be where most of the information you need to access will be. Remember to read those pesky annotations in the WSDL for more information and the PDF on the FedEx developer's website.

Tuesday, February 02, 2010

Best Description of today's computer reporting

With all the tech buzz that is going on these days, there is no end to the number of "reporters" that generate "news" stories about said tech buzz. However, while looking over one of the news stories on a site I found a comment that justly defines what is really going on here.


If next week Steve Jobs called a press conference and sliced his dick off with a silver scalpel in a room full of stunned reporters, I have no doubt that -- not to be outdone -- Sergey Brin would cut off his with a chainsaw on nation-wide TV seven days later.

And no one in the tech punditry -- all happy just to have jobs and something to write about besides the latest PC graphics card -- would question *WHY* these idiots are emasculating themselves, they'd just write tedious "thought" pieces contrasting the metaphors of Job's elegant, shiny castration versus Brin's use of loud horsepower.


--RobotRunAmok

Absolutely classic.

Monday, February 01, 2010

The world of apps. There's an app for that.

Warning, I am a Java fanboi (even if they sold out to Oracle)

A few years ago a platform was made called Java. It promised to allow people to write and compile their code once and run it everywhere. Of course real life set in an everyone realized that a VM just made software run slow. Basically you had two computers running in the space of one, the OS and the VM. However the idea was that a program could run anywhere and the idea was incredibly huge.

Microsoft tried their hand at Java and found out quickly that Sun meant business when it meant Java compliance. Microsoft would go on to make their own version of Java called .NET eventually. Most other players, IBM / Oracle / Apple / RedHat / Novell played fine with Sun and Java. However, without support from the MS desktop world, Java slowly migrated to business applications and middle-ware. Seeing who were the big players it's no surprise.

Then came along a thing called XML. Now the Internet was hot, but XML made it more flexible, more robust, and more friendlier. With XML, JavaScript, and Asynchronous HTTP you had AJAX. With XML, XSLT, and scripting you had blogs and walls. With XML and SOAP you had web APIs. For the first time the web was becoming a platform and not just a presentation layer. Add in the Open Source movement and MySOL / Linux / PHP / Apache and the web was becoming more and more about sites that provided services and tools for others.

Enter Google. Google has been the driver of the Web Platform, MS tried with ASP, then ASP.NET, and so forth, but all has not been about giving to people but instead just a platform of putting stuff on the web (I'm sorry I dropped my GeoCities account back in '97). MS has created an API to end making APIs. Google embraced the idea of taking an API an making an API out of it.

With the web becoming the cross platform application and presentation layers, Java slowly started grinding towards that goal, of making Java and web work together. Well, happily, no one was going to sit and wait for Sun Microsystems to get off their tush and start making stuff transpire. Struts was born, Spring was born, Tomcat was born, and so on... Sun was quickly loosing their driver's seat to Open Source projects that ran on Java. And to an extent Sun was begrudgingly accepting of the change.

Then the mobile generation started, and that brings me to my muse.

Apple pushed a web central platform with a native SDK as a last option for their phone platform.
Google is pushing a web central platform with a native SDK as a last option for their phone platform.
Microsoft is pushing their .NET platform, yadda yadda yadda, it does some web stuff too for their phonelaptopcomputerservertoasterXbox360sink platform.
Oh yeah and Palm is doing something web centric for their phone platform.

However, sans Palm, all have made big markets in their native application space. The HTML5 platform has been somewhat missing in all of their market software.

Wasn't the idea of Java to build apps that would run on the iPhone, Droid, Pre, and whatever monster MS puts out? Wasn't JavaFX to make apps so easy that people wouldn't think of native?

What went wrong? The what I call "70's mindset" has dominated the cell phone market. That hardware dictates software is the 70's mindset. Vendors do this because of two reason:

1. Control
2, Ease

Apple has a very tight grip over their API, in fact they take in very little input as to what the next SDK will have. Pretty much the same over at the Google camp. They have it open sourced, but very little is changed by outsiders as far as the standard API goes. Do I need to even mention the amount of control MS has over .NET?

Control makes Ease. Picture if you will how absolutely easy it would be to build a platform if you design the platform to run only your specs! That in is the problem with Java on the phone. There are (were, give it a couple of more years) many Java phones out in the world (unless you have Verizon). But Java has gotten away from Sun, quite literally now thanks to Oracle, and control is now anyone (and everyones) game.

HTML5 may prove to be the ultimate winner, but the road ahead is long. The W3C may have the final say but a lot of players, like Apple and Google, are in a big tug of war with the standard that HTML5 for mobile may be out of reach to be a real goal anytime soon.

Thus, we have hardware specific (er, platform) applications that could have used Java but chose not to. We must muse, why is HTML5 better than Java on mobile phones?

Cheers

Trying out Blokkal

Since I'm a big KDE user, yes that means KDE 4 as well. I decided that I would try an actual KDE client to write to my blog.

So this is a test of that.

Also I want to try out pre:


public class Hello {

public static void main(String [] args) {
System.out.println("Hello, World");
}

}


Cheers!

Secure Simple EJB Bean making the DB tables.

Alright, it has been awhile but I swear I've been away for very good reasons.

So if you remember our basic EJB HelloBean, let's look at how to add security measures to provide a login for people to run our EJB code.

First we need to setup our JDBC realm. To do that we need an actual database. I'll be using MySQL as it is a wonderfully simple database to use and maintain, at the same time MySQL scales nicely and can be used for very big projects. So let's say you have your MySQL server up and running. Let's create a database called helloDB. To do that from the MySQL prompt (hereafter known as the sql prompt (since I hate having to hit the shift key for SQL)) type in:


CREATE DATABASE helloDB


Now let's create two tables, one to hold user names and passwords, the other to hold user names and groups. We'll call these tables USERTBL and GRPTBL.


CREATE TABLE USERTBL (
USERNAME VARCHAR(13) NOT NULL,
SHAPASSWD CHAR(64) NOT NULL,
PRIMARY KEY (USERNAME)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE GRPTBL (
ENTRYID INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
USERNAME VARCHAR(13) NOT NULL,
GROUPING VARCHAR(20) NOT NULL,
PRIMARY KEY (ENTRYID),
UNIQUE KEY (USERNAME, GROUPING),
CONSTRAINT FOREIGN KEY (USERNAME) REFERENCES USERTBL (USERNAME) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


Here we've created the two tables we need to start a security realm using the JDBCRealm module. The SHAPASSWD field of the USERTBL is to store our passwords in SHA-256 encoded strings. You can use any kind of hash function that is known to Java, like MD-5 or SHA-1, I'm going with SHA-256 because I like it among other things.

Also note that I did not make a composite primary key for the GRPTBL but instead created a unique key for the user name / group name pair. I don't like composite primary keys, I don't know many DB admins that do, they have a purpose but just using them anywhere is not really a good idea.

Well there you have the DB side of it. I'll look at the Glassfish end of it in the next post. Cheers!