JSP sendRedirect Causes IllegalStateException

IllegalStateException

IllegalStateException

I am about to finalize my mini-Service Desk project called TTS for one of my Master’s course and wanted to share an important notice on using sendRedirect on your JSP pages.I use GlassFish Server 3.1.1

I have plenty of redirections throughout the application using both POST and GET methods and I paused for a few seconds when I received a java.lang.IllegalStateException during one of them.

Suddenly I realized the issue: once you are using a redirect make sure the application returns before going into another redirection:

boolean res = port.isTechnicianExists(TechnicianName);

if (res){
 response.sendRedirect("../createuser.jsp?action=createUser&status=ERR&message=Username_already_exists");
 return;
 }

Administration: Server Becomes Unresponsive Sporadically [Solved]

SSH - pstree

SSH - pstree

I have been facing with a weird issue lately – completely sporadically. My server has been becoming unresponsive once every week – besides it is not only HTTP (Apache) that cannot accept any connections but also other services such as SSH, Email Server or even system activities such as crontab. This has been a very annoying situation indeed, and all I could do was to pray that the login via SSH does not exceed the 20 seconds timeout period that I had set for security purposes. But it always did. Only option was to connect to Webmin interface, and take the appropriate actions to take the server back to life.

I did suspect it was a memory issue – and I was right, Apache was the only reason. After installing WordPress I had observed a massive increase in load on MySQL and HTTP servers but the problem was that Apache was creating way too many threads for each connection it established. I checked the configuration files and probably WordPress had added some directives regarding these settings. Modifying it according to my needs have resolved the issue:

##
## Server-Pool Size Regulation (MPM specific)
## 

# prefork MPM
# StartServers: number of server processes to start
# MinSpareServers: minimum number of server processes which are kept spare
# MaxSpareServers: maximum number of server processes which are kept spare
# MaxClients: maximum number of server processes allowed to start
# MaxRequestsPerChild: maximum number of requests a server process serves
<IfModule mpm_prefork_module>
    StartServers           2
    MinSpareServers       25
    MaxSpareServers       25
    MaxClients           150
    MaxRequestsPerChild    0
</IfModule>

# worker MPM
<IfModule mpm_worker_module>
    StartServers          2
    MinSpareThreads      25
    MaxSpareThreads      25
    ThreadLimit          25
    ThreadsPerChild      12
    MaxClients          150
    MaxRequestsPerChild   0
</IfModule>

# event MPM
<IfModule mpm_event_module>
    StartServers          2
    MaxClients          150
    MinSpareThreads      25
    MaxSpareThreads      25
    ThreadLimit          50
    ThreadsPerChild      12
    MaxRequestsPerChild   0
</IfModule>

Send Email – Authentication Error using Net::SMTP::SSL

I have been creating a simple monitoring tool for my server (alkankoray.net) at home using Perl and during that process I have come up with an error occured while I was trying to send email using Secure SMTP via Google Mail although all the account information was correct and the code appeared to be OK:

if (not $smtp = Net::SMTP::SSL->new('smtp.gmail.com', 
                Port => 465, Debug => 1))   
                         die "Server Connection Error";

$smtp->auth(" [account login] ", " [ account password ] ")
  || die "Authentication Error";

The issue was related to a missing component: SASL.

Apt-getting it resolves the issue – no clear description and reason in the debug output for the failure, but that is the solution.

sudo apt-get install libauthen-sasl-perl

Cookies with JSP – Basic Operations and Issues

I am developing a Ticketing System for a project for one of my Master’s course using Java Web Service and JSP. As expected, I need to be dealing with lots of cookies during the process. However, I would like to share an interesting issue that I have faced while accessing any cookies that I had previously created – although everything looked pretty fine.

I have a default page, /index.jsp and a login form submitted to /functions/execute.jsp as below:

<form method="POST" action="functions/execute.jsp" name="form_login">
 <input type="text" name="username"></input>
 <input type="password" name="password"></input>
 <input type="hidden" name="method" value="login"></input>
 <input type="hidden" name="url" value="<% out.println(request.getRequestURL()); %>"></input>
 <input type="submit" name="submit">
 </form>

In execute.jsp if the request is “login” I call a web service operation called login, and create cookies with the returning data, such as:

Cookie cookie_TechnicianEmail = new Cookie ("tts_TechnicianEmail",loginReturns[2]);
cookie_TechnicianEmail.setMaxAge(1 * 24 * 60 * 60);
response.addCookie(cookie_TechnicianEmail);

So far so good, to debug, I check if the cookies are set successfully after creating them in execute.jsp. However, once I redirect the user to the home page (index.jsp) these cookies are not visible anymore.

After a research that took half-an-hour I came up with a solution – add the setPath property to the cookie. Now the execute.jsp looks like:

Cookie cookie_TechnicianEmail = new Cookie ("tts_TechnicianEmail",loginReturns[2]);
 cookie_TechnicianEmail.setMaxAge(1 * 24 * 60 * 60);
 cookie_TechnicianEmail.setPath("/");
 response.addCookie(cookie_TechnicianEmail);

This will enable cookies to be visible starting from the root directory – you may want to modify the path according to your needs.

Lastly, to remove all the cookies with the pattern starting with “tts_”:

Cookie cookies [] = request.getCookies ();
if (cookies != null){
  for (int i = 0; i < cookies.length; i++) {
    if (cookies [i].getName().startsWith("tts_")){
       Cookie tmp = new Cookie(cookies[i].getName(), "");
       tmp.setMaxAge(0);
       tmp.setPath("/");
       response.addCookie(tmp);
    }
  }
}

Building a Simple Web Service Using SOAP on PHP

My webserver is running on Ubuntu 9.10 with PHP 5.2.6 and I suppose you will not be facing with any problems if you are running the same or higher versions.

Preconditions: Apache Web Server 2.2 and PHP5 is installed on your system. If you do not know how to accomplish that, I recommend doing a search on Google with “installing php on linux”.

First thing is to install the SOAP extension on PHP. To do that, simply type “sudo apt-get install php-soap”. Now, what we will be building is a simple HTML form (client.html) with a Name and Surname text field, posting data to a PHP page (client_submit.php), and a web service server page that will process the request and return the result back to the client (server.php).

1. Create the client.html with the following code:

<html>
<head><title>Web Service Test</title></head>
<body>
<form name="test" action="client_submit.php" method="POST">
Name: <input type="text" name="in_name"><br>
Last Name: <input type="text" name="in_lastname"><br>
<input type="submit" name"submit">
</form>
</body>
</html>

2. A very basic form to be submitted. Now, copy and paste the following code to client_submit.php, the page HTML will post to:

<?php
$name = $_POST["in_name"];
$lastname = $_POST["in_lastname"];

$client = new SoapClient(null, array('location' => "http://www.alkankoray.net/webservice/server.php",
                                     'uri'      => "http://www.alkankoray.net/webservice"));
$result = $client->__call("welcomeMessage",array($name,$lastname));
echo $result;
?>

This will create a new SoapClient and call the welcomeMessage on Server getting the return value of it, and display it. Please change the location and uri according to your configuration.

3. Copy & Paste the code below to your server (server.php):

<?php

function welcomeMessage($myname, $mylastname){
        return "Welcome " . $mylastname . ", " . $myname;
}

$server = new SoapServer(null, array('uri' => "http://www.alkankoray.net/webservice"));
$server->addFunction("welcomeMessage");
$server->handle();
?>

Here the welcomeMessage function and the SOAP server is defined, function added to it.

SOAP Result

SOAP Result

This was a 3-step quick tutorial on creating a basic web service. With this example both the client and server lies on the same server, however, of course this might not be the case. This is probably the most reliable and secure way to communicate through device-to-device on the internet. I will use these basics while developing a mobile application that needs to connect to the database on my alkankoray.net server, instead of using a local database such as SQLite.

Previous Posts are Still Available

Although I have closed my previous blog.alkankoray.net site, my posts are still available on my WordPress.com page. Below are the links to the latest posts that were related to iOS Development:

→ iPhone Development Tutorial: Scroll View Up on Keyboard Focus

→ iPhone Development Tutorial: Switching Between Views

→ Developing for iPhone – a Start-up

Design and Infrastucture Update

I know. I have blocked my previous blog on address http://blog.alkankoray.net, have removed the previous Home Page – as in the screenshot below – and instead have installed WordPress on my own web server. I decided to give priority to share my experiences, thoughts and projects rather than a simple welcome page.

I will be posting updates in no time.

Previous Home Page

Previous Home Page

iPhone Development Tutorial: Scroll View Up on Keyboard Focus

Consider a login or sign-up page for your application with a number of input fields such as textboxes. As the user focuses on any of the textbox, the keyboard appears on the bottom of the screen and will eventually block the the other fields as below.

Keyboard Overlap

Keyboard Overlap

The possible way to overcome this problem is to whether

  1. Design your application that all input fields are visible although the keyboard is displayed
  2. Scroll the page up and down as the user focuses and loses focus on a input field

We will try the latter one now.

First, create a new View based project, I have named it scrollview. Afterwards, place some Text fields as in the above example.

-Open the scrollviewViewController.h file generated and place the following code to create and connect the text fields:

@interface scrollviewViewController : UIViewController {
    UITextField    *txtUsername;
    UITextField    *txtPassword;
    UITextField    *txtName;
    UITextField    *txtLastName;
    UITextField     *txtPassword2;
}

@property (nonatomic, retain) IBOutlet UITextField *txtUsername;
@property (nonatomic, retain) IBOutlet UITextField *txtPassword;
@property (nonatomic, retain) IBOutlet UITextField *txtName;
@property (nonatomic, retain) IBOutlet UITextField *txtLastName;
@property (nonatomic, retain) IBOutlet UITextField *txtPassword2;

@end

- Open the .m file and synthesize:

@synthesize txtUsername, txtPassword, txtPassword2, txtName, txtLastName;

-Connect the view objects to these fields – as in the previous tutorials.
-Now, let’s create the functions to move the view up and down. Open the .h file again and place the following :

- (IBAction)BeginEditing:(UITextField *)sender;
- (void)setViewMovedUp:(BOOL)movedUp;
- (void)keyboardWillShow:(NSNotification *)notif;
- (void)viewWillAppear:(BOOL)animated;
- (void)viewWillDisappear:(BOOL)animated;
-(IBAction)textFieldHideKeyboard:(id)sender;

-Now the .m file, and further explanation is below:

-(IBAction)BeginEditing:(UITextField *)sender:(UITextField *)sender
{
    if  (self.view.frame.origin.y >= 0 && ([sender isEqual:txtName] || [sender isEqual:txtLastName])){
        scroll_value = 90;
        [self setViewMovedUp:YES];
    }else if (self.view.frame.origin.y < 0 &&  !([sender isEqual:txtName] || [sender isEqual:txtLastName])){
        [self setViewMovedUp:NO];
    }
}

-Assign this IBAction to Editing Did Begin event of “ALL” the textboxes. It will check if the focused field is Last Name or Name fields first. If yes, the view will scroll up with the set ViewMovedUp function, descibed below.

-(void)setViewMovedUp:(BOOL)movedUp
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5];

    CGRect rect = self.view.frame;
    if (movedUp)
    {
        rect.origin.y -= scroll_value;
        rect.size.height += scroll_value;
    }
    else
    {
        rect.origin.y += scroll_value;
        rect.size.height -= scroll_value;
    }
    self.view.frame = rect;
    [UIView commitAnimations];
}

-It will scroll the view up by the scroll_value defined, and revert it back once setViewMovedUp:NO is called.

-Finally, add the following to the .m file too, for notification and animation addons:

- (void)keyboardWillShow:(NSNotification *)notif
{
    if (([txtLastName isFirstResponder] || [txtName isFirstResponder]) && self.view.frame.origin.y >= 0)
    {
        [self setViewMovedUp:YES];
    }
    else if (!([txtLastName isFirstResponder] || [txtName isFirstResponder]) && self.view.frame.origin.y < 0)
    {
        [self setViewMovedUp:NO];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification object:self.view.window];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
}

-Run your application and see the result!

Scrolling the View Up

Scrolling the View Up