XPage Java dev Tutorial 2 – AdminPanel prt 1


 

General Feels and Gratitude

Hello Everybody!!  Today I am really happy to present my first NotesIn9 video!  It was really great being able to make this sub-series and be a part of the tutorials that really got me going with XPage development.  I want to thank David Leedy for giving me the opportunity as well as thank my employer for allowing me to use what I learn on company time to create content for others.  This is turning out to be a hobby that is really starting to take off.  Again, I have to thank twitter, David Leedy, and Paul Withers for sharing my first blog posts and spreading the word that this blog is out and about.  I would not be so into this right now if it were not for the fresh feeling of being able to do good for others and not just use this website as my own knowledge repository. Thank you to those who read these posts, watch the videos, and of course who retweet, comment and like what I am doing.  All that really makes it easier to stay motivated.


 

Down to Business

What is this mini/sub -series all about?

As you may or may not be aware, everything that we are doing here has a basis in my day to day development.  I started out using java for my xpage dev about a year ago (I had already used java extensively in my daily programming, just not in combination with XPages for which I mostly relied on JavaScript.) To really get started with Java, I decided to make a utility package that included everything that I needed to know to really get going.  I started off with making a sessionHelper.  I did this because I needed to learn how to get a session object.  I did not know anything about the variable resolver at first, and I also had a lot of trouble finding resources to figure it out.  After I managed that, I moved on to one of the most important features of all databases that I develop, the Admin Panel.

The Admin Panel is (currently) a custom control where I store tables that show the variable names and values of all objects located in the applicationScope, the sessionScope, and the viewScope.  I do not waste my time with the requestScope, although I suspect that such a thing would be possible if I found a use case for it.  Additionally to this, I show another HTML table that presents cookie information.  This is a part of another module that I call “the cookie helper”.  Finally, a larger and more complex table presents logging information to the user with a particular role.  The custom control contains functions that erase the variables located in the scoped maps (although I have not made that work without causing errors) add string variables to the scopes (not very helpful, but cool), and delete logging information shown in the debug section of the admin panel.  A great feature of the debug table is that there are six different error levels that all use different row styles.  This allows the trace information to be shown in a more understated way, and fatal errors to pop out like a sore thumb.  Later, I turned this same functionality around to store and show entire session logging documents in a logging database.

Today we are going to look at how to build your own Admin Panel using information built, retained, and retrieved in Java.

How is this sub-series built?

Due to time, I broke this down into three different parts.  Since I am actually coding on camera as much as possible, it is taking a while to get through it.  I am doing this so that you can see where I have difficulty, so that you can hear me commenting as I go, and because my entire concept in this Java Tutorial is to program an application from start to finish together.  When it is just taking too long and when I do not have a lot to say, I do edit out some parts.

Part one (this part) is going to be a basic introduction.  We do, for this one time only, go through a PowerPoint presentation where I go into what we are doing, the three parts, and some basic information about myself.  One thing that changed from the making of the PowerPoint slides to the videos is that the concept had to be changed from asking question before the recording of the next part to all the questions being asked in comments and through email and me answering them in a written format or in a fourth video.  It makes sense for numerous reasons, but we do not need to get into that.

Part two is primarily Java construction.  Although some Java classes were started in the first part, in part two we really get going.  I do not want to spoil it too much here, but we basically finish up all the beans that we are going to need for the custom control.

Part three is being my slight PITA.  I recorded it once already, but am not pleased with how it turned out.  I really need to stop doing my recordings after 1 AM.  I am going to be deleting the changes and redoing the video.  Part three includes registering the beans that we already made with the faces-config.xml file and designing our custom control.  We go into how to add a few custom properties, although we admittedly do not go into every detail that you could possibly go over.  There are numerous NotesIn9s if you need help specifically with Custom Controls.

 Why is this a sub-series?

This is a sub-series because it is a small part in the project that we are building together.  I was trying to find some way to make videos for this page’s main tutorial while also making content for NotesIn9.  I decided that it would be awesome to make some of the content that can really stand alone its own sub series and give them to David Leedy.  For those who follow along here, it should seem pretty seamless.  To those who watch the NotesIn9s, it is my hope that you can watch that content and get what you need without too much knowledge of what we are doing in the rest of the tutorials.  At any rate, I am posting the code on this website.  That being said, without any further ado- I give you the video, and following the video, the code!  Enjoy!


Video

Find the video here!


Code

COMING SOON!

Java and Encryption

Welcome to a small tutorial like lesson where I go into a bit of encryption etc in Java.  This will not be a highly detailed discuss, I will just go into the basics.

First off, what is encryption?
Cryptography is, in its most basic form, preparing information for transmission in such a way that it cannot be read or understood by others.  Cryptography got its start thousands of years ago, and has taken on may forms.  My favorite historical example is a method whereby a piece of “paper” could be wrapped around a stick.  The message would then be written on the paper.  Once unwrapped, it would be difficult to know what it was saying without knowing the diameter of the stick that was used to “encrypt” the message, if you could tell what it was in the first place.  It is said that the Spartans used this system.  Later, another encryption system was used where the letters would be transposed a few spaces.  In other words, ‘A’ would become ‘C’, ‘B’ to ‘D’ and so on.  Current methods are not too different.

Why am I using encryption in BudgIt?

My use case is fairly simple.  I want to be able to store some basic program information that the normal user should not be able to see or change without my business logic.  I need the information available without a database connection, so that would not do, and although I could use some sort of a binary reader/writer, the point of BudgIt is to learn, so that is what I am going to do.

Encryption would probably be better if the goal is to transfer data across the internet.  This would hopefully prevent eavesdroppers from getting personal and sensitive information. although you still have to worry about the NSA.  😀  In fact, it has even been reported that they have overseen the development of a few ciphers in order to make sure that they have a “master key” that can unlock any encrypted transmission.  But alas: politics is not the reason for this post, so lets just jump into it.

Lets create a key in java

private void createKey(){
		String msg;
		KeyGenerator keygenerator;
		SecretKey key;
		String keyfile = FILE_KEY;
		ObjectOutputStream oos = null;
		File f = new File(keyfile);
		if(f.exists()){
			//Warning: Key already exists!  Would you like to generate a new key?  This could make information that already exists unreadable.;

		}
		try{
			keygenerator = KeyGenerator.getInstance("DES"); // this says to use the DES algorithm when it creates the key file.
			keygenerator.init(new SecureRandom());
			key = keygenerator.generateKey();
//initiate the key generator and create a key
			SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
			Class<?> spec = Class.forName("javax.crypto.spec.DESKeySpec");
			DESKeySpec ks = (DESKeySpec) skf.getKeySpec(key,  spec);

			oos = new ObjectOutputStream(new FileOutputStream(keyfile));
			oos.writeObject(ks.getKey());

			Cipher c = Cipher.getInstance("DES/CFB8/NoPadding");
			c.init(Cipher.ENCRYPT_MODE, key);
			oos.writeObject(c.getIV());
			oos.close();

		} catch(NoSuchAlgorithmException e) + many others that I will skip{
			//The encryption algorithm DES is unknown to this system.
		} finally{
			if (oos != null){
				try {
					oos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

This is a very complex bit of code to wade through and I do not really want to rip it to pieces explaining what each part does, but I will say this.  This bit of code is creating a key and saving that key to a file to be used later by an encryption and decryption function.  It is important to note that if this key is lost, the files saved using this key will no longer be able to be read.  (unless you are the NSA).

 

Next, we are going to use that file to encrypt an array of strings.  Again, I am not going to go line by line through it, but it is pretty self explanatory.  It looks more scary than it really is.

public void encryptToFile(String fileName, String[] strings) {

		// check existance of the key
		File f = new File(FILE_KEY);
		if (!f.exists()){
			//An encryption key could not be found!  
		}

		ObjectInputStream ois = null;
		PrintWriter pw = null;

		try{
			ois = new ObjectInputStream(new FileInputStream(f));
			DESKeySpec ks = new DESKeySpec((byte[])ois.readObject());
			SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
			SecretKey key = skf.generateSecret(ks);

			Cipher c = Cipher.getInstance("DES/CFB8/NoPadding");
			c.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec((byte[])ois.readObject()));
			CipherOutputStream cos = new CipherOutputStream(new FileOutputStream(fileName), c);
			pw = new PrintWriter(new OutputStreamWriter(cos));
			for (String s : strings){
				pw.println(s);
			}
			pw.flush();
		} catch long list of exceptions {

		} finally{
			if(ois != null){
				try {
					ois.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (pw != null){
				pw.close();
			}
		}
	}

Here we are decrypting a file that we already saved.  This must use the same key that we used to encrypt the file.

 
public ArrayList<String> dycryptFile(String fileName) throws FileNotFoundException, IOException{

		ArrayList strings = new ArrayList();

		String msg;
		// check existance of the key
		File f = new File(FILE_KEY);
		if (!f.exists()){
			//An encryption key could not be found!
		}

		ObjectInputStream ois = null;
		CipherInputStream cis = null;
		BufferedReader br = null;
		String input = "";

		try{
			//********************************************** get cipher**********************************
			ois = new ObjectInputStream(new FileInputStream(f));
			DESKeySpec ks = new DESKeySpec((byte[])ois.readObject());
			SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
			SecretKey key = skf.generateSecret(ks);

			Cipher c = Cipher.getInstance("DES/CFB8/NoPadding");
			c.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec((byte[])ois.readObject()));
			// ************************************************* decrypt file********************************

			cis = new CipherInputStream(new FileInputStream(fileName), c);
			br = new BufferedReader( new InputStreamReader(cis));

			while ((input = br.readLine()) != null){
				strings.add(input);
			}

		} 
		//... catch long list of exceptions ...

		} finally {
			if(ois != null){
				try {
					ois.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(br != null){
				br.close();
			}
		}
		return strings;
	}

This is just a quick block to get all of you interested people an example to look at.  I do hope to write again soon and go into each of the methods and say what each part is actually doing and why it is important, but for now I hope that it can be understood.