Archive

Archive for the ‘Java’ Category

Split Up CamelCase Strings

November 14th, 2009 1 comment

Java code to split up a cAmelCaSe string by using the uppercase characters as the separators. For example, aBcDe into a_b_c_d_e.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
private String convertCamelCaseString(String camelCaseString, String optionalSeparator) {
  int n = camelCaseString.trim().length();
  StringBuilder sb = new StringBuilder(n * 2);
  for (int i = 0; i < n; i++) {
    char c = camelCaseString.charAt(i);
    int x = (int) c;
    // A=65, N=78, Z=90, a=97
    // See http://blossomassociates.net/ascii.html
    if(optionalSeparator==null) optionalSeparator="";
    if (x >= 65 && x <= 90) { // Converting to lower case
      c = (char) (x + 32);
      sb.append(optionalSeparator).append(c);
    } else
      sb.append(c);
  }
 
  // Final string converted from camelCaseString
  String convertedString = sb.toString();
  sb = null;
  return convertedString;
}
Categories: Java Tags:

Passing Objects To Struts 2 Select Tag

September 25th, 2009 No comments

In my code, there is a Struts 2 ActionSupport subclass passing a List of Item objects to a form, to be used to populate a Struts 2 Select tag.

The relevant part of the form, is

<s:form action="someAction" method="POST">
<s:select label="Associate This With Item" 
  name="itemId" 
  list="items" 
  listKey="id" 
  listValue="title" 
  value="%{items.{title}}"/>
<s:submit type="button" value="Associate" />
</s:form>

Here, the Item object’s title attribute is being displayed and upon form submit, the id attribute of the selected Item object is passed to the backend. This is specified by using the listValue and listKey parameters respectively.

Categories: Java Tags:

Preselect Radio Button In Struts 2

September 25th, 2009 Comments off

Form used to update an entity, involving a radio button.

<s:form action="editSomethingAction" method="POST">
<s:radio name="moduleStateSelected" key="label.state" 
    list="#{1:'Draft', 2:'Published'}" 
    value="%{module.state}" />
<s:submit value="Update" align="right"/>
</s:form>

The form parameter moduleStateSelected takes in the value of the state attribute of an object of the Module class, passed by the Struts 2 action.

The related code in the Struts 2 ActionSupport subclass,

public class SomeWebAction extends ActionSupport {
private Module module;
public Module getModule() {
  return module;
}
public void setModule(Module m) {
  this.module = m;
}
//.. other methods not listed here
}

And, relevant code of the Module class,

public class Module {
private short state;
public short getState() {
  return module;
}
public void setState(short newState) {
  this.state = newState;
}
//.. other methods not listed here
}
Categories: Java Tags:

Passing Values From Struts 2 Action To An Update Entity Form

September 25th, 2009 1 comment

I have a Struts 2 action with getter/setter methods for 3 attribute, say, name, id and an object of a class Question (which has a string attribute, questionText, which I want to access in the form).

I somehow forgot how to access the attributes to be used as the default values in a form, so after a bit of searching old code, here’s what it should look like:

<s:form action="editSomethingAction" method="POST">
<s:hidden name="id" value="%{#parameters['id']}" />
<s:hidden name="name" value="%{#parameters['name']}" />
<s:textarea name="questionText" label="" rows="3" cols="80" value="%{question.questionText}"/>
<s:submit value="Update" align="right"/>
</s:form>
Categories: Java Tags:

Handling Empty Lists In JSTL

July 28th, 2009 No comments
<c:choose>
  <c:when test="${(myList!=null) && (not empty myList) }">
    <c:forEach var="myListItem" items="${myList}">
    <!-- Loop through the list -->  
    </c:forEach>
  </c:when>
  <c:otherwise><p>My list is empty.</p></c:otherwise>
</c:choose>
Categories: Java Tags: ,

Searching Using Fragment Of A String Using Spring

July 23rd, 2009 No comments

I encountered something rather annoying using Spring. I was query something similar to

SELECT last_name FROM users WHERE email_address LIKE ?

Spring execute the query but returned 0 results when I expected at least 1 (depending on how many characters of the last_name I had passed as a parameter to this query.

Only when I changed the relevant part of the code from

Object[] parameters = new Object[1];
parameters[0] = searchStr;

to

Object[] parameters = new Object[1];
parameters[0] = searchStr + "%";

did I get the correct number of records.

Here’s the complete code (parts modified for this post)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public List<String> retrieveLastNamesBasedOnEmailAddress(String searchStr)
{ // Constructing the query
  String sqlStr = "SELECT last_name FROM users WHERE email_address LIKE ?";
  // Constructing the parameter array
  Object[] parameters = new Object[1];
  parameters[0] = searchStr + "%";
  // Executing the query
  if(this.jdbcTemplate == null) 
    this.jdbcTemplate = new JdbcTemplate(getDataSource());
  List<String> list = this.jdbcTemplate.query(
      sqlStr, 
      parameters, 
      new SingleColumnRowMapper(String.class)
      );
  return list;
}

Depending on the permissible fragment of the the search parameter, perhaps adding in the % in front and back of the search parameter might be a better idea.

6
  parameters[0] = "%" + searchStr + "%";
Categories: Java Tags:

Replacing Struts s:submit Button With An Image

July 13th, 2009 Comments off

I wanted to replace the s:submit button of a login form with an image our designer passed to us.

I tried out the most obvious way to do so, but it didn’t produce the expected result. Upon Googling, I came across Eric Martin’s post on an apparent bug in Struts 2.0.11, about the s:submit tag with type=button not rendering properly. I tried out what he posted as that didn’t work either, just as he had stated.

So, I tried something different. I got rid of s:submit button and replaced with a hyperlinked image. The HTML code looked similar to

1
2
3
4
5
6
7
8
9
10
11
12
13
<table align="center">
  <tr>
    <td>
      <s:form action="dologin" method="POST" validate="true">
      <s:textfield name="username" key="label.username"/>
      <s:password name="password" key="label.password"/>
      </s:form>
    </td>
  </tr>
  <tr>
    <td align="right"><a href="javascript: submitForm();"><img src="images/icon_go.png" alt="Sign In" width="27" height="30" align="absbottom" widtd="27"/></a></td>
  </tr>
</table>

The supporting Javascript code is simple and is placed just before closing the head element. The dologin in the document.dologin.submit() (below) is the name assigned to the form by Struts 2. Struts 2 names it dologin based on the name of the action, which is dologin (see line 4 of HTML code snippet above).

<script language="JavaScript">
  function submitForm() { document.dologin.submit(); }
</script>

This worked for me. The image appeared where I wanted it to appear.

Figure 1 : Expected Form Look With s:submit Replaced With An Image

Figure 1 : Expected Form Look With s:submit Replaced With An Image

However, the problem with this approach is that the form validation does not happen within this page itself. What do I mean by that? See Figure 2 (below)

Figure 2

Figure 2

Then upon looking up the documentation for the Submit class at http://struts.apache.org/2.0.14/struts2-core/apidocs/org/apache/struts2/components/Submit.html, i discovered that they already support rendering of a submit button!

So, by replacing the entire code snippet and the supporting Javascript (listed earlier) with the following 4 lines of code, I get the image to appear where I wanted it to appear (see Figure 1 above).

1
2
3
4
5
<s:form action="dologin" method="POST" validate="true">
<s:textfield name="username" key="label.username"/>
<s:password name="password" key="label.password"/>
<s:submit type="image" value="Sign in" src="images/icon_go.png"/>
</s:form>

See the

type="image" along with the src="images/icon_go.png"

My application is using Struts 2.0.11.1.

Categories: Java Tags:

Multiple Commands In A Midlet

July 8th, 2009 No comments

I was recently asked what difference would it make if I chose between the command types Command.SCREEN, Command.ITEM and Command.OK in a screen in a midlet with multiple menu items appearing in way similar to the screenshot below.

Midlet Screen With Multiple Menu Items

Figure 1 : Midlet Screen With Multiple Menu Items

Some simple code (below) that produces the above effect.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
 
public class MutipleCommandMidlet extends MIDlet implements CommandListener
{
  private Command exitCmd, menuItem1, menuItem2, menuItem3, menuItem4, menuItem5, menuItem6,
    menuItem7, menuItem8;
  private Form form;
 
  public MutipleCommandMidlet()
  {
    exitCmd = new Command("Exit", Command.EXIT, 1);
    menuItem1 = new Command("Item 1", Command.SCREEN, 2);
    menuItem2 = new Command("Item 2", Command.SCREEN, 3);
    menuItem3 = new Command("Item 3", Command.SCREEN, 4);
    menuItem4 = new Command("Item 4", Command.SCREEN, 5);
    menuItem5 = new Command("Item 5", Command.SCREEN, 6);
    menuItem6 = new Command("Item 6", Command.SCREEN, 7);
    menuItem7 = new Command("Item 7", Command.SCREEN, 8);
    menuItem8 = new Command("Item 8", Command.SCREEN, 9);
    form = new Form("Some Form");
  }
 
  public void commandAction(Command c, Displayable d)
  {
    String label = c.getLabel();
    if (label.startsWith("Menu Item"))
      showAlert("SCREEN Command", label + " Pressed");
    else if (label.equals("Exit"))
      showAlert("EXIT Command", label + " Pressed");
  }
 
  protected void destroyApp(boolean arg0) throws MIDletStateChangeException  { /* not implemented */ }
 
  protected void pauseApp() {  /* not implemented */ }
 
  private void showAlert(String alertTitle, String alertText)
  {
    System.out.println(alertTitle + " : " + alertText);
    Alert alert = new Alert(alertTitle, alertText, null, AlertType.INFO);
    alert.setTimeout(2000);
    Display.getDisplay(this).setCurrent(alert, form);
  }
 
  protected void startApp() throws MIDletStateChangeException
  { // Note that it does not matter which order the menu items are added
    form.addCommand(menuItem1);
    form.addCommand(menuItem3);
    form.addCommand(menuItem2);
    form.addCommand(menuItem4);
    form.addCommand(menuItem5);
    form.addCommand(menuItem6);
    form.addCommand(menuItem7);
    form.addCommand(menuItem8);
    form.addCommand(exitCmd);
    form.setCommandListener(this);
    Display.getDisplay(this).setCurrent(form);
  }// end-of-startApp
}

Take note of lines 11 to 20 and also lines 47 to 55

11
12
13
14
15
16
17
18
19
    exitCmd = new Command("Exit", Command.EXIT, 1);
    menuItem1 = new Command("Item 1", Command.SCREEN, 2);
    menuItem2 = new Command("Item 2", Command.SCREEN, 3);
    menuItem3 = new Command("Item 3", Command.SCREEN, 4);
    menuItem4 = new Command("Item 4", Command.SCREEN, 5);
    menuItem5 = new Command("Item 5", Command.SCREEN, 6);
    menuItem6 = new Command("Item 6", Command.SCREEN, 7);
    menuItem7 = new Command("Item 7", Command.SCREEN, 8);
    menuItem8 = new Command("Item 8", Command.SCREEN, 9);
47
48
49
50
51
52
53
54
55
    form.addCommand(menuItem1);
    form.addCommand(menuItem3);
    form.addCommand(menuItem2);
    form.addCommand(menuItem4);
    form.addCommand(menuItem5);
    form.addCommand(menuItem6);
    form.addCommand(menuItem7);
    form.addCommand(menuItem8);
    form.addCommand(exitCmd);

Now if we were to change the ordering in which the Commands are being added to the Form, to say something like this:

47
48
49
50
51
52
53
54
55
    form.addCommand(menuItem5);
    form.addCommand(menuItem4);
    form.addCommand(menuItem1);
    form.addCommand(menuItem3);
    form.addCommand(menuItem2);
    form.addCommand(menuItem6);
    form.addCommand(menuItem7);
    form.addCommand(menuItem8);
    form.addCommand(exitCmd);

we would still get the screen looking like Figure 1 above. The reason (I think) this happens is because of the priorities (5 and 6 respectively) assigned to menuItem4 and menuItem5.

15
16
    menuItem4 = new Command("Item 4", Command.SCREEN, 5);
    menuItem5 = new Command("Item 5", Command.SCREEN, 6);

If we were to change lines 12 to 15, so that menuItem1, menuItem4 and menuItem5 now have the same priority (level 2),

12
13
14
15
16
    menuItem1 = new Command("Item 1", Command.SCREEN, 2);
    menuItem2 = new Command("Item 2", Command.SCREEN, 3);
    menuItem3 = new Command("Item 3", Command.SCREEN, 4);
    menuItem4 = new Command("Item 4", Command.SCREEN, 2);
    menuItem5 = new Command("Item 5", Command.SCREEN, 2);

then we get the menu items appearing similar to the screenshot below.

Figure 2 : Midlet Screen With Multiple Menu Items

Figure 2 : Midlet Screen With Multiple Menu Items (Equal Priority Levels)


Here, the menu items, menuItem1, menuItem4 and menuItem5 (which have equal priority levels) appeared in the order in which they were added to the Form.

Categories: Java Tags: ,

How To Detect If A Java ME Phone Supports A Particular JSR

July 6th, 2009 No comments

A few weeks ago, I had the need to detect if a Java enabled phone supported JSR 179 (Location API for J2ME). Since then, I came accross the need to detect support for other JSRs.

The required information can be determined by calling
System.getProperty(propertyName);
If the string returned by the getProperty returns a non NULL string, it implies the particular JSR is supported.

Here is a summary of a few JSRs along with their corresponding propertyNames :

JSR 75 (FC) microedition.io.file.FileConnection.version
JSR 75 (PIM API) microedition.pim.version
JSR 82 javax.bluetooth.LocalDevice
JSR 120 javax.wireless.messaging.MessageConnection
JSR 135 (MMAPI), Check If Audio Capture Supported supports.audio.capture
JSR 135 (MMAPI), Check If Video Capture Supported supports.video.capture
JSR 179 microedition.location.version
Categories: Java Tags:

How To Detect If A Java ME Phone Supports JSR 179

June 2nd, 2009 No comments

I recently had a need to detect whether a Java enabled phone supported JSR 179 (Location API for J2ME).
Here’s a very simple way, just call
String locationAPIVersionStr = System.getProperty("microedition.location.version");
If the locationAPIVersionStr returns a non NULL string, it implies JSR 179 is supported.

Categories: Java Tags: